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.

55790 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. #define JUCE_QUICKTIME 0
  349. #define JUCE_OPENGL 0
  350. #define JUCE_USE_CDBURNER 0
  351. #define JUCE_USE_CDREADER 0
  352. #define JUCE_WEB_BROWSER 0
  353. #define JUCE_PLUGINHOST_AU 0
  354. #define JUCE_PLUGINHOST_VST 0
  355. #endif
  356. #endif
  357. /********* End of inlined file: juce_Config.h *********/
  358. #ifdef JUCE_NAMESPACE
  359. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  360. #define END_JUCE_NAMESPACE }
  361. #else
  362. #define BEGIN_JUCE_NAMESPACE
  363. #define END_JUCE_NAMESPACE
  364. #endif
  365. /********* Start of inlined file: juce_PlatformDefs.h *********/
  366. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  367. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  368. /* This file defines miscellaneous macros for debugging, assertions, etc.
  369. */
  370. #ifdef JUCE_FORCE_DEBUG
  371. #undef JUCE_DEBUG
  372. #if JUCE_FORCE_DEBUG
  373. #define JUCE_DEBUG 1
  374. #endif
  375. #endif
  376. /** This macro defines the C calling convention used as the standard for Juce calls. */
  377. #if JUCE_MSVC
  378. #define JUCE_CALLTYPE __stdcall
  379. #else
  380. #define JUCE_CALLTYPE
  381. #endif
  382. // Debugging and assertion macros
  383. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  384. #if JUCE_LOG_ASSERTIONS
  385. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  386. #elif defined (JUCE_DEBUG)
  387. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  388. #else
  389. #define juce_LogCurrentAssertion
  390. #endif
  391. #ifdef JUCE_DEBUG
  392. // If debugging is enabled..
  393. /** Writes a string to the standard error stream.
  394. This is only compiled in a debug build.
  395. @see Logger::outputDebugString
  396. */
  397. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  398. /** Printf's a string to the standard error stream.
  399. This is only compiled in a debug build.
  400. @see Logger::outputDebugString
  401. */
  402. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  403. // Assertions..
  404. #if JUCE_WINDOWS || DOXYGEN
  405. #if JUCE_USE_INTRINSICS
  406. #pragma intrinsic (__debugbreak)
  407. /** This will try to break the debugger if one is currently hosting this app.
  408. @see jassert()
  409. */
  410. #define juce_breakDebugger __debugbreak();
  411. #elif JUCE_GCC
  412. /** This will try to break the debugger if one is currently hosting this app.
  413. @see jassert()
  414. */
  415. #define juce_breakDebugger asm("int $3");
  416. #else
  417. /** This will try to break the debugger if one is currently hosting this app.
  418. @see jassert()
  419. */
  420. #define juce_breakDebugger { __asm int 3 }
  421. #endif
  422. #elif JUCE_MAC
  423. #define juce_breakDebugger Debugger();
  424. #elif JUCE_IPHONE
  425. #define juce_breakDebugger kill (0, SIGTRAP);
  426. #elif JUCE_LINUX
  427. #define juce_breakDebugger kill (0, SIGTRAP);
  428. #endif
  429. /** This will always cause an assertion failure.
  430. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  431. in juce_Config.h).
  432. @see jassert()
  433. */
  434. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  435. /** Platform-independent assertion macro.
  436. This gets optimised out when not being built with debugging turned on.
  437. Be careful not to call any functions within its arguments that are vital to
  438. the behaviour of the program, because these won't get called in the release
  439. build.
  440. @see jassertfalse
  441. */
  442. #define jassert(expression) { if (! (expression)) jassertfalse }
  443. #else
  444. // If debugging is disabled, these dummy debug and assertion macros are used..
  445. #define DBG(dbgtext)
  446. #define DBG_PRINTF(dbgprintf)
  447. #define jassertfalse { juce_LogCurrentAssertion }
  448. #if JUCE_LOG_ASSERTIONS
  449. #define jassert(expression) { if (! (expression)) jassertfalse }
  450. #else
  451. #define jassert(a) { }
  452. #endif
  453. #endif
  454. #ifndef DOXYGEN
  455. template <bool b> struct JuceStaticAssert;
  456. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  457. #endif
  458. /** A compile-time assertion macro.
  459. If the expression parameter is false, the macro will cause a compile error.
  460. */
  461. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  462. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  463. #define JUCE_TRY try
  464. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  465. object so they can be logged by the application if it wants to.
  466. */
  467. #define JUCE_CATCH_EXCEPTION \
  468. catch (const std::exception& e) \
  469. { \
  470. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  471. } \
  472. catch (...) \
  473. { \
  474. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  475. }
  476. #define JUCE_CATCH_ALL catch (...) {}
  477. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  478. #else
  479. #define JUCE_TRY
  480. #define JUCE_CATCH_EXCEPTION
  481. #define JUCE_CATCH_ALL
  482. #define JUCE_CATCH_ALL_ASSERT
  483. #endif
  484. // Macros for inlining.
  485. #if JUCE_MSVC
  486. /** A platform-independent way of forcing an inline function.
  487. Use the syntax: @code
  488. forcedinline void myfunction (int x)
  489. @endcode
  490. */
  491. #ifdef JUCE_DEBUG
  492. #define forcedinline __forceinline
  493. #else
  494. #define forcedinline inline
  495. #endif
  496. /** A platform-independent way of stopping the compiler inlining a function.
  497. Use the syntax: @code
  498. juce_noinline void myfunction (int x)
  499. @endcode
  500. */
  501. #define juce_noinline
  502. #else
  503. /** A platform-independent way of forcing an inline function.
  504. Use the syntax: @code
  505. forcedinline void myfunction (int x)
  506. @endcode
  507. */
  508. #ifndef JUCE_DEBUG
  509. #define forcedinline inline __attribute__((always_inline))
  510. #else
  511. #define forcedinline inline
  512. #endif
  513. /** A platform-independent way of stopping the compiler inlining a function.
  514. Use the syntax: @code
  515. juce_noinline void myfunction (int x)
  516. @endcode
  517. */
  518. #define juce_noinline __attribute__((noinline))
  519. #endif
  520. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  521. /********* End of inlined file: juce_PlatformDefs.h *********/
  522. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  523. #if JUCE_MSVC
  524. #pragma warning (push)
  525. #pragma warning (disable: 4514 4245 4100)
  526. #endif
  527. #include <cstdlib>
  528. #include <cstdarg>
  529. #include <climits>
  530. #include <cmath>
  531. #include <cwchar>
  532. #include <stdexcept>
  533. #include <typeinfo>
  534. #include <cstring>
  535. #include <cstdio>
  536. #if JUCE_USE_INTRINSICS
  537. #include <intrin.h>
  538. #endif
  539. #if JUCE_MAC
  540. #include <libkern/OSAtomic.h>
  541. #endif
  542. #if JUCE_LINUX
  543. #include <signal.h>
  544. #endif
  545. #if JUCE_MSVC && JUCE_DEBUG
  546. #include <crtdbg.h>
  547. #endif
  548. #if JUCE_MSVC
  549. #pragma warning (pop)
  550. #endif
  551. // DLL building settings on Win32
  552. #if JUCE_MSVC
  553. #ifdef JUCE_DLL_BUILD
  554. #define JUCE_API __declspec (dllexport)
  555. #pragma warning (disable: 4251)
  556. #elif defined (JUCE_DLL)
  557. #define JUCE_API __declspec (dllimport)
  558. #pragma warning (disable: 4251)
  559. #endif
  560. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  561. #ifdef JUCE_DLL_BUILD
  562. #define JUCE_API __attribute__ ((visibility("default")))
  563. #endif
  564. #endif
  565. #ifndef JUCE_API
  566. /** This macro is added to all juce public class declarations. */
  567. #define JUCE_API
  568. #endif
  569. /** This macro is added to all juce public function declarations. */
  570. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  571. // Now include some basics that are needed by most of the Juce classes...
  572. BEGIN_JUCE_NAMESPACE
  573. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  574. #if JUCE_LOG_ASSERTIONS
  575. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  576. #endif
  577. /********* Start of inlined file: juce_Memory.h *********/
  578. #ifndef __JUCE_MEMORY_JUCEHEADER__
  579. #define __JUCE_MEMORY_JUCEHEADER__
  580. /*
  581. This file defines the various juce_malloc(), juce_free() macros that should be used in
  582. preference to the standard calls.
  583. */
  584. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  585. #ifndef JUCE_DLL
  586. // Win32 debug non-DLL versions..
  587. /** This should be used instead of calling malloc directly. */
  588. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  589. /** This should be used instead of calling calloc directly. */
  590. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  591. /** This should be used instead of calling realloc directly. */
  592. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  593. /** This should be used instead of calling free directly. */
  594. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  595. #else
  596. // Win32 debug DLL versions..
  597. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  598. // way all juce calls in the DLL and in the host API will all use the same allocator.
  599. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  600. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  601. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  602. extern JUCE_API void juce_DebugFree (void* const block);
  603. /** This should be used instead of calling malloc directly. */
  604. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  605. /** This should be used instead of calling calloc directly. */
  606. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  607. /** This should be used instead of calling realloc directly. */
  608. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  609. /** This should be used instead of calling free directly. */
  610. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  611. #endif
  612. #if ! defined (_AFXDLL)
  613. /** This macro can be added to classes to add extra debugging information to the memory
  614. allocated for them, so you can see the type of objects involved when there's a dump
  615. of leaked objects at program shutdown. (Only works on win32 at the moment).
  616. */
  617. #define juce_UseDebuggingNewOperator \
  618. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  619. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  620. static void operator delete (void* p) { juce_free (p); }
  621. #endif
  622. #elif defined (JUCE_DLL)
  623. // Win32 DLL (release) versions..
  624. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  625. // way all juce calls in the DLL and in the host API will all use the same allocator.
  626. extern JUCE_API void* juce_Malloc (const int size);
  627. extern JUCE_API void* juce_Calloc (const int size);
  628. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  629. extern JUCE_API void juce_Free (void* const block);
  630. /** This should be used instead of calling malloc directly. */
  631. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  632. /** This should be used instead of calling calloc directly. */
  633. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  634. /** This should be used instead of calling realloc directly. */
  635. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  636. /** This should be used instead of calling free directly. */
  637. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  638. #define juce_UseDebuggingNewOperator \
  639. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  640. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  641. static void operator delete (void* p) { juce_free (p); }
  642. #else
  643. // Mac, Linux and Win32 (release) versions..
  644. /** This should be used instead of calling malloc directly. */
  645. #define juce_malloc(numBytes) malloc (numBytes)
  646. /** This should be used instead of calling calloc directly. */
  647. #define juce_calloc(numBytes) calloc (1, numBytes)
  648. /** This should be used instead of calling realloc directly. */
  649. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  650. /** This should be used instead of calling free directly. */
  651. #define juce_free(location) free (location)
  652. #endif
  653. /** This macro can be added to classes to add extra debugging information to the memory
  654. allocated for them, so you can see the type of objects involved when there's a dump
  655. of leaked objects at program shutdown. (Only works on win32 at the moment).
  656. Note that if you create a class that inherits from a class that uses this macro,
  657. your class must also use the macro, otherwise you'll probably get compile errors
  658. because of ambiguous new operators.
  659. Most of the JUCE classes use it, so see these for examples of where it should go.
  660. */
  661. #ifndef juce_UseDebuggingNewOperator
  662. #define juce_UseDebuggingNewOperator
  663. #endif
  664. #if JUCE_MSVC
  665. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  666. E.g.
  667. @code
  668. juce_ThreadLocal int myVariable;
  669. @endcode
  670. */
  671. #define juce_ThreadLocal __declspec(thread)
  672. #else
  673. #define juce_ThreadLocal __thread
  674. #endif
  675. /** Clears a block of memory. */
  676. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  677. /** Clears a reference to a local structure. */
  678. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  679. /** A handy macro that calls delete on a pointer if it's non-zero, and
  680. then sets the pointer to null.
  681. */
  682. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  683. #endif // __JUCE_MEMORY_JUCEHEADER__
  684. /********* End of inlined file: juce_Memory.h *********/
  685. /********* Start of inlined file: juce_MathsFunctions.h *********/
  686. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  687. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  688. /*
  689. This file sets up some handy mathematical typdefs and functions.
  690. */
  691. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  692. /** A platform-independent 8-bit signed integer type. */
  693. typedef signed char int8;
  694. /** A platform-independent 8-bit unsigned integer type. */
  695. typedef unsigned char uint8;
  696. /** A platform-independent 16-bit signed integer type. */
  697. typedef signed short int16;
  698. /** A platform-independent 16-bit unsigned integer type. */
  699. typedef unsigned short uint16;
  700. /** A platform-independent 32-bit signed integer type. */
  701. typedef signed int int32;
  702. /** A platform-independent 32-bit unsigned integer type. */
  703. typedef unsigned int uint32;
  704. #if JUCE_MSVC
  705. /** A platform-independent 64-bit integer type. */
  706. typedef __int64 int64;
  707. /** A platform-independent 64-bit unsigned integer type. */
  708. typedef unsigned __int64 uint64;
  709. /** A platform-independent macro for writing 64-bit literals, needed because
  710. different compilers have different syntaxes for this.
  711. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  712. GCC, or 0x1000000000 for MSVC.
  713. */
  714. #define literal64bit(longLiteral) ((__int64) longLiteral)
  715. #else
  716. /** A platform-independent 64-bit integer type. */
  717. typedef long long int64;
  718. /** A platform-independent 64-bit unsigned integer type. */
  719. typedef unsigned long long uint64;
  720. /** A platform-independent macro for writing 64-bit literals, needed because
  721. different compilers have different syntaxes for this.
  722. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  723. GCC, or 0x1000000000 for MSVC.
  724. */
  725. #define literal64bit(longLiteral) (longLiteral##LL)
  726. #endif
  727. #if JUCE_64BIT
  728. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  729. typedef int64 pointer_sized_int;
  730. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  731. typedef uint64 pointer_sized_uint;
  732. #elif _MSC_VER >= 1300
  733. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  734. typedef _W64 int pointer_sized_int;
  735. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  736. typedef _W64 unsigned int pointer_sized_uint;
  737. #else
  738. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  739. typedef int pointer_sized_int;
  740. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  741. typedef unsigned int pointer_sized_uint;
  742. #endif
  743. /** A platform-independent unicode character type. */
  744. typedef wchar_t juce_wchar;
  745. // Some indispensible min/max functions
  746. /** Returns the larger of two values. */
  747. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  748. /** Returns the larger of two values. */
  749. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  750. /** Returns the larger of two values. */
  751. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  752. /** Returns the larger of two values. */
  753. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  754. /** Returns the larger of three values. */
  755. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  756. /** Returns the larger of three values. */
  757. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  758. /** Returns the larger of three values. */
  759. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  760. /** Returns the larger of three values. */
  761. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  762. /** Returns the larger of four values. */
  763. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  764. /** Returns the larger of four values. */
  765. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  766. /** Returns the larger of four values. */
  767. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  768. /** Returns the larger of four values. */
  769. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  770. /** Returns the smaller of two values. */
  771. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  772. /** Returns the smaller of two values. */
  773. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  774. /** Returns the smaller of two values. */
  775. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  776. /** Returns the smaller of two values. */
  777. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  778. /** Returns the smaller of three values. */
  779. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  780. /** Returns the smaller of three values. */
  781. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  782. /** Returns the smaller of three values. */
  783. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  784. /** Returns the smaller of three values. */
  785. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  786. /** Returns the smaller of four values. */
  787. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  788. /** Returns the smaller of four values. */
  789. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  790. /** Returns the smaller of four values. */
  791. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  792. /** Returns the smaller of four values. */
  793. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  794. /** Constrains a value to keep it within a given range.
  795. This will check that the specified value lies between the lower and upper bounds
  796. specified, and if not, will return the nearest value that would be in-range. Effectively,
  797. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  798. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  799. the results will be unpredictable.
  800. @param lowerLimit the minimum value to return
  801. @param upperLimit the maximum value to return
  802. @param valueToConstrain the value to try to return
  803. @returns the closest value to valueToConstrain which lies between lowerLimit
  804. and upperLimit (inclusive)
  805. @see jlimit0To, jmin, jmax
  806. */
  807. template <class Type>
  808. inline Type jlimit (const Type lowerLimit,
  809. const Type upperLimit,
  810. const Type valueToConstrain) throw()
  811. {
  812. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  813. return (valueToConstrain < lowerLimit) ? lowerLimit
  814. : ((valueToConstrain > upperLimit) ? upperLimit
  815. : valueToConstrain);
  816. }
  817. /** Handy function to swap two values over.
  818. */
  819. template <class Type>
  820. inline void swapVariables (Type& variable1, Type& variable2) throw()
  821. {
  822. const Type tempVal = variable1;
  823. variable1 = variable2;
  824. variable2 = tempVal;
  825. }
  826. /** Handy macro for getting the number of elements in a simple const C array.
  827. E.g.
  828. @code
  829. static int myArray[] = { 1, 2, 3 };
  830. int numElements = numElementsInArray (myArray) // returns 3
  831. @endcode
  832. */
  833. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  834. // Some useful maths functions that aren't always present with all compilers and build settings.
  835. #if JUCE_WINDOWS || defined (DOXYGEN)
  836. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  837. versions of these functions of various platforms and compilers. */
  838. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  839. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  840. versions of these functions of various platforms and compilers. */
  841. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  842. #else
  843. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  844. versions of these functions of various platforms and compilers. */
  845. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  846. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  847. versions of these functions of various platforms and compilers. */
  848. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  849. #endif
  850. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  851. /** A predefined value for Pi, at double-precision.
  852. @see float_Pi
  853. */
  854. const double double_Pi = 3.1415926535897932384626433832795;
  855. /** A predefined value for Pi, at sngle-precision.
  856. @see double_Pi
  857. */
  858. const float float_Pi = 3.14159265358979323846f;
  859. /** The isfinite() method seems to vary greatly between platforms, so this is a
  860. platform-independent macro for it.
  861. */
  862. #if JUCE_LINUX || JUCE_MAC || JUCE_IPHONE
  863. #define juce_isfinite(v) std::isfinite(v)
  864. #elif JUCE_WINDOWS && ! defined (isfinite)
  865. #define juce_isfinite(v) _finite(v)
  866. #else
  867. #define juce_isfinite(v) isfinite(v)
  868. #endif
  869. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  870. /********* End of inlined file: juce_MathsFunctions.h *********/
  871. /********* Start of inlined file: juce_DataConversions.h *********/
  872. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  873. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  874. #if JUCE_USE_INTRINSICS
  875. #pragma intrinsic (_byteswap_ulong)
  876. #endif
  877. // Endianness conversions..
  878. #if JUCE_IPHONE
  879. // a gcc compiler error seems to mean that these functions only work properly
  880. // on the iPhone if they are declared static..
  881. static forcedinline uint32 swapByteOrder (uint32 n) throw();
  882. static inline uint16 swapByteOrder (const uint16 n) throw();
  883. static inline uint64 swapByteOrder (const uint64 value) throw();
  884. #endif
  885. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  886. forcedinline uint32 swapByteOrder (uint32 n) throw()
  887. {
  888. #if JUCE_MAC || JUCE_IPHONE
  889. // Mac version
  890. return OSSwapInt32 (n);
  891. #elif JUCE_GCC
  892. // Inpenetrable GCC version..
  893. asm("bswap %%eax" : "=a"(n) : "a"(n));
  894. return n;
  895. #elif JUCE_USE_INTRINSICS
  896. // Win32 intrinsics version..
  897. return _byteswap_ulong (n);
  898. #else
  899. // Win32 version..
  900. __asm {
  901. mov eax, n
  902. bswap eax
  903. mov n, eax
  904. }
  905. return n;
  906. #endif
  907. }
  908. /** Swaps the byte-order of a 16-bit short. */
  909. inline uint16 swapByteOrder (const uint16 n) throw()
  910. {
  911. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  912. // Win32 intrinsics version..
  913. return (uint16) _byteswap_ushort (n);
  914. #else
  915. return (uint16) ((n << 8) | (n >> 8));
  916. #endif
  917. }
  918. inline uint64 swapByteOrder (const uint64 value) throw()
  919. {
  920. #if JUCE_MAC || JUCE_IPHONE
  921. return OSSwapInt64 (value);
  922. #elif JUCE_USE_INTRINSICS
  923. return _byteswap_uint64 (value);
  924. #else
  925. return (((int64) swapByteOrder ((uint32) value)) << 32)
  926. | swapByteOrder ((uint32) (value >> 32));
  927. #endif
  928. }
  929. #if JUCE_LITTLE_ENDIAN
  930. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  931. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  932. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  933. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  934. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  935. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  936. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  937. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  938. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  939. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  940. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  941. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  942. /** Turns 4 bytes into a little-endian integer. */
  943. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  944. /** Turns 2 bytes into a little-endian integer. */
  945. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  946. /** Turns 4 bytes into a big-endian integer. */
  947. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  948. /** Turns 2 bytes into a big-endian integer. */
  949. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  950. #else
  951. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  952. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  953. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  954. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  955. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  956. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  957. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  958. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  959. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  960. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  961. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  962. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  963. /** Turns 4 bytes into a little-endian integer. */
  964. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  965. /** Turns 2 bytes into a little-endian integer. */
  966. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  967. /** Turns 4 bytes into a big-endian integer. */
  968. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  969. /** Turns 2 bytes into a big-endian integer. */
  970. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  971. #endif
  972. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  973. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  974. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  975. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  976. /** Copies a 24-bit number to 3 little-endian bytes. */
  977. 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); }
  978. /** Copies a 24-bit number to 3 big-endian bytes. */
  979. 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); }
  980. /** Fast floating-point-to-integer conversion.
  981. This is faster than using the normal c++ cast to convert a double to an int, and
  982. it will round the value to the nearest integer, rather than rounding it down
  983. like the normal cast does.
  984. Note that this routine gets its speed at the expense of some accuracy, and when
  985. rounding values whose floating point component is exactly 0.5, odd numbers and
  986. even numbers will be rounded up or down differently. For a more accurate conversion,
  987. see roundDoubleToIntAccurate().
  988. */
  989. inline int roundDoubleToInt (const double value) throw()
  990. {
  991. union { int asInt[2]; double asDouble; } n;
  992. n.asDouble = value + 6755399441055744.0;
  993. #if JUCE_BIG_ENDIAN
  994. return n.asInt [1];
  995. #else
  996. return n.asInt [0];
  997. #endif
  998. }
  999. /** Fast floating-point-to-integer conversion.
  1000. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1001. fine for values above zero, but negative numbers are rounded the wrong way.
  1002. */
  1003. inline int roundDoubleToIntAccurate (const double value) throw()
  1004. {
  1005. return roundDoubleToInt (value + 1.5e-8);
  1006. }
  1007. /** Fast floating-point-to-integer conversion.
  1008. This is faster than using the normal c++ cast to convert a float to an int, and
  1009. it will round the value to the nearest integer, rather than rounding it down
  1010. like the normal cast does.
  1011. Note that this routine gets its speed at the expense of some accuracy, and when
  1012. rounding values whose floating point component is exactly 0.5, odd numbers and
  1013. even numbers will be rounded up or down differently.
  1014. */
  1015. inline int roundFloatToInt (const float value) throw()
  1016. {
  1017. union { int asInt[2]; double asDouble; } n;
  1018. n.asDouble = value + 6755399441055744.0;
  1019. #if JUCE_BIG_ENDIAN
  1020. return n.asInt [1];
  1021. #else
  1022. return n.asInt [0];
  1023. #endif
  1024. }
  1025. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  1026. /********* End of inlined file: juce_DataConversions.h *********/
  1027. /********* Start of inlined file: juce_Logger.h *********/
  1028. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1029. #define __JUCE_LOGGER_JUCEHEADER__
  1030. /********* Start of inlined file: juce_String.h *********/
  1031. #ifndef __JUCE_STRING_JUCEHEADER__
  1032. #define __JUCE_STRING_JUCEHEADER__
  1033. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1034. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1035. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1036. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1037. (in the default system encoding) as its internal representation.
  1038. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1039. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1040. literals in the T("abcd") macro, so that it all works nicely either way round.
  1041. */
  1042. #if JUCE_STRINGS_ARE_UNICODE
  1043. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1044. typedef juce_wchar tchar;
  1045. #define juce_tcharToWideChar(c) (c)
  1046. #else
  1047. #define JUCE_T(stringLiteral) (stringLiteral)
  1048. typedef char tchar;
  1049. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1050. #endif
  1051. #if ! JUCE_DONT_DEFINE_MACROS
  1052. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1053. or unicode.
  1054. If you write your string literals in the form T("xyz"), this will either be compiled
  1055. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1056. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1057. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1058. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1059. the juce/src directory) to avoid defining this macro. See the comments in
  1060. juce_withoutMacros.h for more info.
  1061. */
  1062. #define T(stringLiteral) JUCE_T(stringLiteral)
  1063. #endif
  1064. /**
  1065. A set of methods for manipulating characters and character strings, with
  1066. duplicate methods to handle 8-bit and unicode characters.
  1067. These are defined as wrappers around the basic C string handlers, to provide
  1068. a clean, cross-platform layer, (because various platforms differ in the
  1069. range of C library calls that they provide).
  1070. @see String
  1071. */
  1072. class JUCE_API CharacterFunctions
  1073. {
  1074. public:
  1075. static int length (const char* const s) throw();
  1076. static int length (const juce_wchar* const s) throw();
  1077. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1078. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1079. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1080. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1081. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1082. static void append (char* dest, const char* src) throw();
  1083. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1084. static int compare (const char* const s1, const char* const s2) throw();
  1085. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1086. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1087. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1088. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1089. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1090. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1091. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1092. static const char* find (const char* const haystack, const char* const needle) throw();
  1093. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1094. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1095. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1096. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1097. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1098. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1099. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1100. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1101. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1102. static int getIntValue (const char* const s) throw();
  1103. static int getIntValue (const juce_wchar* s) throw();
  1104. static int64 getInt64Value (const char* s) throw();
  1105. static int64 getInt64Value (const juce_wchar* s) throw();
  1106. static double getDoubleValue (const char* const s) throw();
  1107. static double getDoubleValue (const juce_wchar* const s) throw();
  1108. static char toUpperCase (const char character) throw();
  1109. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1110. static void toUpperCase (char* s) throw();
  1111. static void toUpperCase (juce_wchar* s) throw();
  1112. static bool isUpperCase (const char character) throw();
  1113. static bool isUpperCase (const juce_wchar character) throw();
  1114. static char toLowerCase (const char character) throw();
  1115. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1116. static void toLowerCase (char* s) throw();
  1117. static void toLowerCase (juce_wchar* s) throw();
  1118. static bool isLowerCase (const char character) throw();
  1119. static bool isLowerCase (const juce_wchar character) throw();
  1120. static bool isWhitespace (const char character) throw();
  1121. static bool isWhitespace (const juce_wchar character) throw();
  1122. static bool isDigit (const char character) throw();
  1123. static bool isDigit (const juce_wchar character) throw();
  1124. static bool isLetter (const char character) throw();
  1125. static bool isLetter (const juce_wchar character) throw();
  1126. static bool isLetterOrDigit (const char character) throw();
  1127. static bool isLetterOrDigit (const juce_wchar character) throw();
  1128. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1129. hex digit.
  1130. */
  1131. static int getHexDigitValue (const tchar digit) throw();
  1132. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1133. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1134. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1135. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1136. };
  1137. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1138. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1139. /**
  1140. The JUCE String class!
  1141. Using a reference-counted internal representation, these strings are fast
  1142. and efficient, and there are methods to do just about any operation you'll ever
  1143. dream of.
  1144. @see StringArray, StringPairArray
  1145. */
  1146. class JUCE_API String
  1147. {
  1148. public:
  1149. /** Creates an empty string.
  1150. @see empty
  1151. */
  1152. String() throw();
  1153. /** Creates a copy of another string. */
  1154. String (const String& other) throw();
  1155. /** Creates a string from a zero-terminated text string.
  1156. The string is assumed to be stored in the default system encoding.
  1157. */
  1158. String (const char* const text) throw();
  1159. /** Creates a string from an string of characters.
  1160. This will use up the the first maxChars characters of the string (or
  1161. less if the string is actually shorter)
  1162. */
  1163. String (const char* const text,
  1164. const int maxChars) throw();
  1165. /** Creates a string from a zero-terminated unicode text string. */
  1166. String (const juce_wchar* const unicodeText) throw();
  1167. /** Creates a string from a unicode text string.
  1168. This will use up the the first maxChars characters of the string (or
  1169. less if the string is actually shorter)
  1170. */
  1171. String (const juce_wchar* const unicodeText,
  1172. const int maxChars) throw();
  1173. /** Creates a string from a single character. */
  1174. static const String charToString (const tchar character) throw();
  1175. /** Destructor. */
  1176. ~String() throw();
  1177. /** This is an empty string that can be used whenever one is needed.
  1178. It's better to use this than String() because it explains what's going on
  1179. and is more efficient.
  1180. */
  1181. static const String empty;
  1182. /** Generates a probably-unique 32-bit hashcode from this string. */
  1183. int hashCode() const throw();
  1184. /** Generates a probably-unique 64-bit hashcode from this string. */
  1185. int64 hashCode64() const throw();
  1186. /** Returns the number of characters in the string. */
  1187. int length() const throw();
  1188. // Assignment and concatenation operators..
  1189. /** Replaces this string's contents with another string. */
  1190. const String& operator= (const tchar* const other) throw();
  1191. /** Replaces this string's contents with another string. */
  1192. const String& operator= (const String& other) throw();
  1193. /** Appends another string at the end of this one. */
  1194. const String& operator+= (const tchar* const textToAppend) throw();
  1195. /** Appends another string at the end of this one. */
  1196. const String& operator+= (const String& stringToAppend) throw();
  1197. /** Appends a character at the end of this string. */
  1198. const String& operator+= (const char characterToAppend) throw();
  1199. /** Appends a character at the end of this string. */
  1200. const String& operator+= (const juce_wchar characterToAppend) throw();
  1201. /** Appends a string at the end of this one.
  1202. @param textToAppend the string to add
  1203. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1204. */
  1205. void append (const tchar* const textToAppend,
  1206. const int maxCharsToTake) throw();
  1207. /** Appends a string at the end of this one.
  1208. @returns the concatenated string
  1209. */
  1210. const String operator+ (const String& stringToAppend) const throw();
  1211. /** Appends a string at the end of this one.
  1212. @returns the concatenated string
  1213. */
  1214. const String operator+ (const tchar* const textToAppend) const throw();
  1215. /** Appends a character at the end of this one.
  1216. @returns the concatenated string
  1217. */
  1218. const String operator+ (const tchar characterToAppend) const throw();
  1219. /** Appends a character at the end of this string. */
  1220. String& operator<< (const char n) throw();
  1221. /** Appends a character at the end of this string. */
  1222. String& operator<< (const juce_wchar n) throw();
  1223. /** Appends another string at the end of this one. */
  1224. String& operator<< (const char* const text) throw();
  1225. /** Appends another string at the end of this one. */
  1226. String& operator<< (const juce_wchar* const text) throw();
  1227. /** Appends another string at the end of this one. */
  1228. String& operator<< (const String& text) throw();
  1229. /** Appends a decimal number at the end of this string. */
  1230. String& operator<< (const short number) throw();
  1231. /** Appends a decimal number at the end of this string. */
  1232. String& operator<< (const unsigned short number) throw();
  1233. /** Appends a decimal number at the end of this string. */
  1234. String& operator<< (const int number) throw();
  1235. /** Appends a decimal number at the end of this string. */
  1236. String& operator<< (const unsigned int number) throw();
  1237. /** Appends a decimal number at the end of this string. */
  1238. String& operator<< (const long number) throw();
  1239. /** Appends a decimal number at the end of this string. */
  1240. String& operator<< (const unsigned long number) throw();
  1241. /** Appends a decimal number at the end of this string. */
  1242. String& operator<< (const float number) throw();
  1243. /** Appends a decimal number at the end of this string. */
  1244. String& operator<< (const double number) throw();
  1245. // Comparison methods..
  1246. /** Returns true if the string contains no characters.
  1247. Note that there's also an isNotEmpty() method to help write readable code.
  1248. @see containsNonWhitespaceChars()
  1249. */
  1250. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1251. /** Returns true if the string contains at least one character.
  1252. Note that there's also an isEmpty() method to help write readable code.
  1253. @see containsNonWhitespaceChars()
  1254. */
  1255. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1256. /** Case-sensitive comparison with another string. */
  1257. bool operator== (const String& other) const throw();
  1258. /** Case-sensitive comparison with another string. */
  1259. bool operator== (const tchar* const other) const throw();
  1260. /** Case-sensitive comparison with another string. */
  1261. bool operator!= (const String& other) const throw();
  1262. /** Case-sensitive comparison with another string. */
  1263. bool operator!= (const tchar* const other) const throw();
  1264. /** Case-insensitive comparison with another string. */
  1265. bool equalsIgnoreCase (const String& other) const throw();
  1266. /** Case-insensitive comparison with another string. */
  1267. bool equalsIgnoreCase (const tchar* const other) const throw();
  1268. /** Case-sensitive comparison with another string. */
  1269. bool operator> (const String& other) const throw();
  1270. /** Case-sensitive comparison with another string. */
  1271. bool operator< (const tchar* const other) const throw();
  1272. /** Case-sensitive comparison with another string. */
  1273. bool operator>= (const String& other) const throw();
  1274. /** Case-sensitive comparison with another string. */
  1275. bool operator<= (const tchar* const other) const throw();
  1276. /** Case-sensitive comparison with another string.
  1277. @returns 0 if the two strings are identical; negative if this string
  1278. comes before the other one alphabetically, or positive if it
  1279. comes after it.
  1280. */
  1281. int compare (const tchar* const other) const throw();
  1282. /** Case-insensitive comparison with another string.
  1283. @returns 0 if the two strings are identical; negative if this string
  1284. comes before the other one alphabetically, or positive if it
  1285. comes after it.
  1286. */
  1287. int compareIgnoreCase (const tchar* const other) const throw();
  1288. /** Lexicographic comparison with another string.
  1289. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1290. characters, making it good for sorting human-readable strings.
  1291. @returns 0 if the two strings are identical; negative if this string
  1292. comes before the other one alphabetically, or positive if it
  1293. comes after it.
  1294. */
  1295. int compareLexicographically (const tchar* const other) const throw();
  1296. /** Tests whether the string begins with another string.
  1297. Uses a case-sensitive comparison.
  1298. */
  1299. bool startsWith (const tchar* const text) const throw();
  1300. /** Tests whether the string begins with a particular character.
  1301. Uses a case-sensitive comparison.
  1302. */
  1303. bool startsWithChar (const tchar character) const throw();
  1304. /** Tests whether the string begins with another string.
  1305. Uses a case-insensitive comparison.
  1306. */
  1307. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1308. /** Tests whether the string ends with another string.
  1309. Uses a case-sensitive comparison.
  1310. */
  1311. bool endsWith (const tchar* const text) const throw();
  1312. /** Tests whether the string ends with a particular character.
  1313. Uses a case-sensitive comparison.
  1314. */
  1315. bool endsWithChar (const tchar character) const throw();
  1316. /** Tests whether the string ends with another string.
  1317. Uses a case-insensitive comparison.
  1318. */
  1319. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1320. /** Tests whether the string contains another substring.
  1321. Uses a case-sensitive comparison.
  1322. */
  1323. bool contains (const tchar* const text) const throw();
  1324. /** Tests whether the string contains a particular character.
  1325. Uses a case-sensitive comparison.
  1326. */
  1327. bool containsChar (const tchar character) const throw();
  1328. /** Tests whether the string contains another substring.
  1329. Uses a case-insensitive comparison.
  1330. */
  1331. bool containsIgnoreCase (const tchar* const text) const throw();
  1332. /** Tests whether the string contains another substring as a distict word.
  1333. @returns true if the string contains this word, surrounded by
  1334. non-alphanumeric characters
  1335. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1336. */
  1337. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1338. /** Tests whether the string contains another substring as a distict word.
  1339. @returns true if the string contains this word, surrounded by
  1340. non-alphanumeric characters
  1341. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1342. */
  1343. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1344. /** Finds an instance of another substring if it exists as a distict word.
  1345. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1346. then this will return the index of the start of the substring. If it isn't
  1347. found, then it will return -1
  1348. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1349. */
  1350. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1351. /** Finds an instance of another substring if it exists as a distict word.
  1352. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1353. then this will return the index of the start of the substring. If it isn't
  1354. found, then it will return -1
  1355. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1356. */
  1357. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1358. /** Looks for any of a set of characters in the string.
  1359. Uses a case-sensitive comparison.
  1360. @returns true if the string contains any of the characters from
  1361. the string that is passed in.
  1362. */
  1363. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1364. /** Looks for a set of characters in the string.
  1365. Uses a case-sensitive comparison.
  1366. @returns true if the all the characters in the string are also found in the
  1367. string that is passed in.
  1368. */
  1369. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1370. /** Returns true if this string contains any non-whitespace characters.
  1371. This will return false if the string contains only whitespace characters, or
  1372. if it's empty.
  1373. It is equivalent to calling "myString.trim().isNotEmpty()".
  1374. */
  1375. bool containsNonWhitespaceChars() const throw();
  1376. /** Returns true if the string matches this simple wildcard expression.
  1377. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1378. This isn't a full-blown regex though! The only wildcard characters supported
  1379. are "*" and "?". It's mainly intended for filename pattern matching.
  1380. */
  1381. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1382. // Substring location methods..
  1383. /** Searches for a character inside this string.
  1384. Uses a case-sensitive comparison.
  1385. @returns the index of the first occurrence of the character in this
  1386. string, or -1 if it's not found.
  1387. */
  1388. int indexOfChar (const tchar characterToLookFor) const throw();
  1389. /** Searches for a character inside this string.
  1390. Uses a case-sensitive comparison.
  1391. @param startIndex the index from which the search should proceed
  1392. @param characterToLookFor the character to look for
  1393. @returns the index of the first occurrence of the character in this
  1394. string, or -1 if it's not found.
  1395. */
  1396. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1397. /** Returns the index of the first character that matches one of the characters
  1398. passed-in to this method.
  1399. This scans the string, beginning from the startIndex supplied, and if it finds
  1400. a character that appears in the string charactersToLookFor, it returns its index.
  1401. If none of these characters are found, it returns -1.
  1402. If ignoreCase is true, the comparison will be case-insensitive.
  1403. @see indexOfChar, lastIndexOfAnyOf
  1404. */
  1405. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1406. const int startIndex = 0,
  1407. const bool ignoreCase = false) const throw();
  1408. /** Searches for a substring within this string.
  1409. Uses a case-sensitive comparison.
  1410. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1411. */
  1412. int indexOf (const tchar* const text) const throw();
  1413. /** Searches for a substring within this string.
  1414. Uses a case-sensitive comparison.
  1415. @param startIndex the index from which the search should proceed
  1416. @param textToLookFor the string to search for
  1417. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1418. */
  1419. int indexOf (const int startIndex,
  1420. const tchar* const textToLookFor) const throw();
  1421. /** Searches for a substring within this string.
  1422. Uses a case-insensitive comparison.
  1423. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1424. */
  1425. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1426. /** Searches for a substring within this string.
  1427. Uses a case-insensitive comparison.
  1428. @param startIndex the index from which the search should proceed
  1429. @param textToLookFor the string to search for
  1430. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1431. */
  1432. int indexOfIgnoreCase (const int startIndex,
  1433. const tchar* const textToLookFor) const throw();
  1434. /** Searches for a character inside this string (working backwards from the end of the string).
  1435. Uses a case-sensitive comparison.
  1436. @returns the index of the last occurrence of the character in this
  1437. string, or -1 if it's not found.
  1438. */
  1439. int lastIndexOfChar (const tchar character) const throw();
  1440. /** Searches for a substring inside this string (working backwards from the end of the string).
  1441. Uses a case-sensitive comparison.
  1442. @returns the index of the start of the last occurrence of the
  1443. substring within this string, or -1 if it's not found.
  1444. */
  1445. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1446. /** Searches for a substring inside this string (working backwards from the end of the string).
  1447. Uses a case-insensitive comparison.
  1448. @returns the index of the start of the last occurrence of the
  1449. substring within this string, or -1 if it's not found.
  1450. */
  1451. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1452. /** Returns the index of the last character in this string that matches one of the
  1453. characters passed-in to this method.
  1454. This scans the string backwards, starting from its end, and if it finds
  1455. a character that appears in the string charactersToLookFor, it returns its index.
  1456. If none of these characters are found, it returns -1.
  1457. If ignoreCase is true, the comparison will be case-insensitive.
  1458. @see lastIndexOf, indexOfAnyOf
  1459. */
  1460. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1461. const bool ignoreCase = false) const throw();
  1462. // Substring extraction and manipulation methods..
  1463. /** Returns the character at this index in the string.
  1464. No checks are made to see if the index is within a valid range, so be careful!
  1465. */
  1466. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1467. /** Returns a character from the string such that it can also be altered.
  1468. This can be used as a way of easily changing characters in the string.
  1469. Note that the index passed-in is not checked to see whether it's in-range, so
  1470. be careful when using this.
  1471. */
  1472. tchar& operator[] (const int index) throw();
  1473. /** Returns the final character of the string.
  1474. If the string is empty this will return 0.
  1475. */
  1476. tchar getLastCharacter() const throw();
  1477. /** Returns a subsection of the string.
  1478. If the range specified is beyond the limits of the string, as much as
  1479. possible is returned.
  1480. @param startIndex the index of the start of the substring needed
  1481. @param endIndex all characters from startIndex up to (but not including)
  1482. this index are returned
  1483. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1484. */
  1485. const String substring (int startIndex,
  1486. int endIndex) const throw();
  1487. /** Returns a section of the string, starting from a given position.
  1488. @param startIndex the first character to include. If this is beyond the end
  1489. of the string, an empty string is returned. If it is zero or
  1490. less, the whole string is returned.
  1491. @returns the substring from startIndex up to the end of the string
  1492. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1493. */
  1494. const String substring (const int startIndex) const throw();
  1495. /** Returns a version of this string with a number of characters removed
  1496. from the end.
  1497. @param numberToDrop the number of characters to drop from the end of the
  1498. string. If this is greater than the length of the string,
  1499. an empty string will be returned. If zero or less, the
  1500. original string will be returned.
  1501. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1502. */
  1503. const String dropLastCharacters (const int numberToDrop) const throw();
  1504. /** Returns a number of characters from the end of the string.
  1505. This returns the last numCharacters characters from the end of the string. If the
  1506. string is shorter than numCharacters, the whole string is returned.
  1507. @see substring, dropLastCharacters, getLastCharacter
  1508. */
  1509. const String getLastCharacters (const int numCharacters) const throw();
  1510. /** Returns a section of the string starting from a given substring.
  1511. This will search for the first occurrence of the given substring, and
  1512. return the section of the string starting from the point where this is
  1513. found (optionally not including the substring itself).
  1514. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1515. fromFirstOccurrenceOf ("34", false) would return "56".
  1516. If the substring isn't found, the method will return an empty string.
  1517. If ignoreCase is true, the comparison will be case-insensitive.
  1518. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1519. */
  1520. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1521. const bool includeSubStringInResult,
  1522. const bool ignoreCase) const throw();
  1523. /** Returns a section of the string starting from the last occurrence of a given substring.
  1524. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1525. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1526. return the whole of the original string.
  1527. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1528. */
  1529. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1530. const bool includeSubStringInResult,
  1531. const bool ignoreCase) const throw();
  1532. /** Returns the start of this string, up to the first occurrence of a substring.
  1533. This will search for the first occurrence of a given substring, and then
  1534. return a copy of the string, up to the position of this substring,
  1535. optionally including or excluding the substring itself in the result.
  1536. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1537. upTo ("34", true) would return "1234".
  1538. If the substring isn't found, this will return the whole of the original string.
  1539. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1540. */
  1541. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1542. const bool includeSubStringInResult,
  1543. const bool ignoreCase) const throw();
  1544. /** Returns the start of this string, up to the last occurrence of a substring.
  1545. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1546. If the substring isn't found, this will return an empty string.
  1547. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1548. */
  1549. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1550. const bool includeSubStringInResult,
  1551. const bool ignoreCase) const throw();
  1552. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1553. const String trim() const throw();
  1554. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1555. const String trimStart() const throw();
  1556. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1557. const String trimEnd() const throw();
  1558. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1559. Characters are removed from the start of the string until it finds one that is not in the
  1560. specified set, and then it stops.
  1561. @param charactersToTrim the set of characters to remove. This must not be null.
  1562. @see trim, trimStart, trimCharactersAtEnd
  1563. */
  1564. const String trimCharactersAtStart (const tchar* charactersToTrim) const throw();
  1565. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1566. Characters are removed from the end of the string until it finds one that is not in the
  1567. specified set, and then it stops.
  1568. @param charactersToTrim the set of characters to remove. This must not be null.
  1569. @see trim, trimEnd, trimCharactersAtStart
  1570. */
  1571. const String trimCharactersAtEnd (const tchar* charactersToTrim) const throw();
  1572. /** Returns an upper-case version of this string. */
  1573. const String toUpperCase() const throw();
  1574. /** Returns an lower-case version of this string. */
  1575. const String toLowerCase() const throw();
  1576. /** Replaces a sub-section of the string with another string.
  1577. This will return a copy of this string, with a set of characters
  1578. from startIndex to startIndex + numCharsToReplace removed, and with
  1579. a new string inserted in their place.
  1580. Note that this is a const method, and won't alter the string itself.
  1581. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1582. it will be constrained to a valid range.
  1583. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1584. characters will be taken out.
  1585. @param stringToInsert the new string to insert at startIndex after the characters have been
  1586. removed.
  1587. */
  1588. const String replaceSection (int startIndex,
  1589. int numCharactersToReplace,
  1590. const tchar* const stringToInsert) const throw();
  1591. /** Replaces all occurrences of a substring with another string.
  1592. Returns a copy of this string, with any occurrences of stringToReplace
  1593. swapped for stringToInsertInstead.
  1594. Note that this is a const method, and won't alter the string itself.
  1595. */
  1596. const String replace (const tchar* const stringToReplace,
  1597. const tchar* const stringToInsertInstead,
  1598. const bool ignoreCase = false) const throw();
  1599. /** Returns a string with all occurrences of a character replaced with a different one. */
  1600. const String replaceCharacter (const tchar characterToReplace,
  1601. const tchar characterToInsertInstead) const throw();
  1602. /** Replaces a set of characters with another set.
  1603. Returns a string in which each character from charactersToReplace has been replaced
  1604. by the character at the equivalent position in newCharacters (so the two strings
  1605. passed in must be the same length).
  1606. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1607. Note that this is a const method, and won't affect the string itself.
  1608. */
  1609. const String replaceCharacters (const String& charactersToReplace,
  1610. const tchar* const charactersToInsertInstead) const throw();
  1611. /** Returns a version of this string that only retains a fixed set of characters.
  1612. This will return a copy of this string, omitting any characters which are not
  1613. found in the string passed-in.
  1614. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1615. Note that this is a const method, and won't alter the string itself.
  1616. */
  1617. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1618. /** Returns a version of this string with a set of characters removed.
  1619. This will return a copy of this string, omitting any characters which are
  1620. found in the string passed-in.
  1621. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1622. Note that this is a const method, and won't alter the string itself.
  1623. */
  1624. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1625. /** Returns a section from the start of the string that only contains a certain set of characters.
  1626. This returns the leftmost section of the string, up to (and not including) the
  1627. first character that doesn't appear in the string passed in.
  1628. */
  1629. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1630. /** Returns a section from the start of the string that only contains a certain set of characters.
  1631. This returns the leftmost section of the string, up to (and not including) the
  1632. first character that occurs in the string passed in.
  1633. */
  1634. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1635. /** Checks whether the string might be in quotation marks.
  1636. @returns true if the string begins with a quote character (either a double or single quote).
  1637. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1638. @see unquoted, quoted
  1639. */
  1640. bool isQuotedString() const throw();
  1641. /** Removes quotation marks from around the string, (if there are any).
  1642. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1643. at the ends of the string are not affected. If there aren't any quotes, the original string
  1644. is returned.
  1645. Note that this is a const method, and won't alter the string itself.
  1646. @see isQuotedString, quoted
  1647. */
  1648. const String unquoted() const throw();
  1649. /** Adds quotation marks around a string.
  1650. This will return a copy of the string with a quote at the start and end, (but won't
  1651. add the quote if there's already one there, so it's safe to call this on strings that
  1652. may already have quotes around them).
  1653. Note that this is a const method, and won't alter the string itself.
  1654. @param quoteCharacter the character to add at the start and end
  1655. @see isQuotedString, unquoted
  1656. */
  1657. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1658. /** Writes text into this string, using printf style-arguments.
  1659. This will replace the contents of the string with the output of this
  1660. formatted printf.
  1661. Note that using the %s token with a juce string is probably a bad idea, as
  1662. this may expect differect encodings on different platforms.
  1663. @see formatted
  1664. */
  1665. void printf (const tchar* const format, ...) throw();
  1666. /** Returns a string, created using arguments in the style of printf.
  1667. This will return a string which is the result of a sprintf using the
  1668. arguments passed-in.
  1669. Note that using the %s token with a juce string is probably a bad idea, as
  1670. this may expect differect encodings on different platforms.
  1671. @see printf, vprintf
  1672. */
  1673. static const String formatted (const tchar* const format, ...) throw();
  1674. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1675. This will replace the contents of the string with the output of this
  1676. formatted printf. Used by other methods, this is public in case it's
  1677. useful for other purposes where you want to pass a va_list through directly.
  1678. Note that using the %s token with a juce string is probably a bad idea, as
  1679. this may expect differect encodings on different platforms.
  1680. @see printf, formatted
  1681. */
  1682. void vprintf (const tchar* const format, va_list& args) throw();
  1683. /** Creates a string which is a version of a string repeated and joined together.
  1684. @param stringToRepeat the string to repeat
  1685. @param numberOfTimesToRepeat how many times to repeat it
  1686. */
  1687. static const String repeatedString (const tchar* const stringToRepeat,
  1688. int numberOfTimesToRepeat) throw();
  1689. /** Creates a string from data in an unknown format.
  1690. This looks at some binary data and tries to guess whether it's Unicode
  1691. or 8-bit characters, then returns a string that represents it correctly.
  1692. Should be able to handle Unicode endianness correctly, by looking at
  1693. the first two bytes.
  1694. */
  1695. static const String createStringFromData (const void* const data,
  1696. const int size) throw();
  1697. // Numeric conversions..
  1698. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1699. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1700. */
  1701. explicit String (const int decimalInteger) throw();
  1702. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1703. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1704. */
  1705. explicit String (const unsigned int decimalInteger) throw();
  1706. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1707. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1708. */
  1709. explicit String (const short decimalInteger) throw();
  1710. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1711. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1712. */
  1713. explicit String (const unsigned short decimalInteger) throw();
  1714. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1715. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1716. */
  1717. explicit String (const int64 largeIntegerValue) throw();
  1718. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1719. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1720. */
  1721. explicit String (const uint64 largeIntegerValue) throw();
  1722. /** Creates a string representing this floating-point number.
  1723. @param floatValue the value to convert to a string
  1724. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1725. decimal places, and will not use exponent notation. If 0 or
  1726. less, it will use exponent notation if necessary.
  1727. @see getDoubleValue, getIntValue
  1728. */
  1729. explicit String (const float floatValue,
  1730. const int numberOfDecimalPlaces = 0) throw();
  1731. /** Creates a string representing this floating-point number.
  1732. @param doubleValue the value to convert to a string
  1733. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1734. decimal places, and will not use exponent notation. If 0 or
  1735. less, it will use exponent notation if necessary.
  1736. @see getFloatValue, getIntValue
  1737. */
  1738. explicit String (const double doubleValue,
  1739. const int numberOfDecimalPlaces = 0) throw();
  1740. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1741. @returns the value of the string as a 32 bit signed base-10 integer.
  1742. @see getTrailingIntValue, getHexValue32, getHexValue64
  1743. */
  1744. int getIntValue() const throw();
  1745. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1746. @returns the value of the string as a 64 bit signed base-10 integer.
  1747. */
  1748. int64 getLargeIntValue() const throw();
  1749. /** Parses a decimal number from the end of the string.
  1750. This will look for a value at the end of the string.
  1751. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1752. Negative numbers are not handled, so "xyz-5" returns 5.
  1753. @see getIntValue
  1754. */
  1755. int getTrailingIntValue() const throw();
  1756. /** Parses this string as a floating point number.
  1757. @returns the value of the string as a 32-bit floating point value.
  1758. @see getDoubleValue
  1759. */
  1760. float getFloatValue() const throw();
  1761. /** Parses this string as a floating point number.
  1762. @returns the value of the string as a 64-bit floating point value.
  1763. @see getFloatValue
  1764. */
  1765. double getDoubleValue() const throw();
  1766. /** Parses the string as a hexadecimal number.
  1767. Non-hexadecimal characters in the string are ignored.
  1768. If the string contains too many characters, then the lowest significant
  1769. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1770. @returns a 32-bit number which is the value of the string in hex.
  1771. */
  1772. int getHexValue32() const throw();
  1773. /** Parses the string as a hexadecimal number.
  1774. Non-hexadecimal characters in the string are ignored.
  1775. If the string contains too many characters, then the lowest significant
  1776. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1777. @returns a 64-bit number which is the value of the string in hex.
  1778. */
  1779. int64 getHexValue64() const throw();
  1780. /** Creates a string representing this 32-bit value in hexadecimal. */
  1781. static const String toHexString (const int number) throw();
  1782. /** Creates a string representing this 64-bit value in hexadecimal. */
  1783. static const String toHexString (const int64 number) throw();
  1784. /** Creates a string representing this 16-bit value in hexadecimal. */
  1785. static const String toHexString (const short number) throw();
  1786. /** Creates a string containing a hex dump of a block of binary data.
  1787. @param data the binary data to use as input
  1788. @param size how many bytes of data to use
  1789. @param groupSize how many bytes are grouped together before inserting a
  1790. space into the output. e.g. group size 0 has no spaces,
  1791. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1792. like "bea1 c2ff".
  1793. */
  1794. static const String toHexString (const unsigned char* data,
  1795. const int size,
  1796. const int groupSize = 1) throw();
  1797. // Casting to character arrays..
  1798. #if JUCE_STRINGS_ARE_UNICODE
  1799. /** Returns a version of this string using the default 8-bit system encoding.
  1800. Because it returns a reference to the string's internal data, the pointer
  1801. that is returned must not be stored anywhere, as it can be deleted whenever the
  1802. string changes.
  1803. */
  1804. operator const char*() const throw();
  1805. /** Returns a unicode version of this string.
  1806. Because it returns a reference to the string's internal data, the pointer
  1807. that is returned must not be stored anywhere, as it can be deleted whenever the
  1808. string changes.
  1809. */
  1810. inline operator const juce_wchar*() const throw() { return text->text; }
  1811. #else
  1812. /** Returns a version of this string using the default 8-bit system encoding.
  1813. Because it returns a reference to the string's internal data, the pointer
  1814. that is returned must not be stored anywhere, as it can be deleted whenever the
  1815. string changes.
  1816. */
  1817. inline operator const char*() const throw() { return text->text; }
  1818. /** Returns a unicode version of this string.
  1819. Because it returns a reference to the string's internal data, the pointer
  1820. that is returned must not be stored anywhere, as it can be deleted whenever the
  1821. string changes.
  1822. */
  1823. operator const juce_wchar*() const throw();
  1824. #endif
  1825. /** Copies the string to a buffer.
  1826. @param destBuffer the place to copy it to
  1827. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1828. not including the tailing zero, so this shouldn't be
  1829. larger than the size of your destination buffer - 1
  1830. */
  1831. void copyToBuffer (char* const destBuffer,
  1832. const int maxCharsToCopy) const throw();
  1833. /** Copies the string to a unicode buffer.
  1834. @param destBuffer the place to copy it to
  1835. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1836. not including the tailing zero, so this shouldn't be
  1837. larger than the size of your destination buffer - 1
  1838. */
  1839. void copyToBuffer (juce_wchar* const destBuffer,
  1840. const int maxCharsToCopy) const throw();
  1841. /** Copies the string to a buffer as UTF-8 characters.
  1842. Returns the number of bytes copied to the buffer, including the terminating null
  1843. character.
  1844. @param destBuffer the place to copy it to; if this is a null pointer,
  1845. the method just returns the number of bytes required
  1846. (including the terminating null character).
  1847. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1848. string won't fit, it'll put in as many as it can while
  1849. still allowing for a terminating null char at the end,
  1850. and will return the number of bytes that were actually
  1851. used. If this value is < 0, no limit is used.
  1852. */
  1853. int copyToUTF8 (uint8* const destBuffer, const int maxBufferSizeBytes = 0x7fffffff) const throw();
  1854. /** Returns a pointer to a UTF-8 version of this string.
  1855. Because it returns a reference to the string's internal data, the pointer
  1856. that is returned must not be stored anywhere, as it can be deleted whenever the
  1857. string changes.
  1858. */
  1859. const char* toUTF8() const throw();
  1860. /** Creates a String from a UTF-8 encoded buffer.
  1861. If the size is < 0, it'll keep reading until it hits a zero.
  1862. */
  1863. static const String fromUTF8 (const uint8* const utf8buffer,
  1864. int bufferSizeBytes = -1) throw();
  1865. /** Increases the string's internally allocated storage.
  1866. Although the string's contents won't be affected by this call, it will
  1867. increase the amount of memory allocated internally for the string to grow into.
  1868. If you're about to make a large number of calls to methods such
  1869. as += or <<, it's more efficient to preallocate enough extra space
  1870. beforehand, so that these methods won't have to keep resizing the string
  1871. to append the extra characters.
  1872. @param numCharsNeeded the number of characters to allocate storage for. If this
  1873. value is less than the currently allocated size, it will
  1874. have no effect.
  1875. */
  1876. void preallocateStorage (const int numCharsNeeded) throw();
  1877. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1878. private:
  1879. struct InternalRefCountedStringHolder
  1880. {
  1881. int refCount;
  1882. int allocatedNumChars;
  1883. #if JUCE_STRINGS_ARE_UNICODE
  1884. wchar_t text[1];
  1885. #else
  1886. char text[1];
  1887. #endif
  1888. };
  1889. InternalRefCountedStringHolder* text;
  1890. static InternalRefCountedStringHolder emptyString;
  1891. // internal constructor that preallocates a certain amount of memory
  1892. String (const int numChars, const int dummyVariable) throw();
  1893. void deleteInternal() throw();
  1894. void createInternal (const int numChars) throw();
  1895. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1896. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1897. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1898. void dupeInternalIfMultiplyReferenced() throw();
  1899. };
  1900. /** Global operator to allow a String to be appended to a string literal.
  1901. This allows the use of expressions such as "abc" + String (x)
  1902. @see String
  1903. */
  1904. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1905. const String& string2) throw();
  1906. /** Global operator to allow a String to be appended to a string literal.
  1907. This allows the use of expressions such as "abc" + String (x)
  1908. @see String
  1909. */
  1910. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1911. const String& string2) throw();
  1912. #endif // __JUCE_STRING_JUCEHEADER__
  1913. /********* End of inlined file: juce_String.h *********/
  1914. /**
  1915. Acts as an application-wide logging class.
  1916. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1917. method and this will then be used by all calls to writeToLog.
  1918. The logger class also contains methods for writing messages to the debugger's
  1919. output stream.
  1920. @see FileLogger
  1921. */
  1922. class JUCE_API Logger
  1923. {
  1924. public:
  1925. /** Destructor. */
  1926. virtual ~Logger();
  1927. /** Sets the current logging class to use.
  1928. Note that the object passed in won't be deleted when no longer needed.
  1929. A null pointer can be passed-in to disable any logging.
  1930. If deleteOldLogger is set to true, the existing logger will be
  1931. deleted (if there is one).
  1932. */
  1933. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1934. const bool deleteOldLogger = false);
  1935. /** Writes a string to the current logger.
  1936. This will pass the string to the logger's logMessage() method if a logger
  1937. has been set.
  1938. @see logMessage
  1939. */
  1940. static void JUCE_CALLTYPE writeToLog (const String& message);
  1941. /** Writes a message to the standard error stream.
  1942. This can be called directly, or by using the DBG() macro in
  1943. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1944. */
  1945. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1946. /** Writes a message to the standard error stream.
  1947. This can be called directly, or by using the DBG_PRINTF() macro in
  1948. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1949. */
  1950. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1951. protected:
  1952. Logger();
  1953. /** This is overloaded by subclasses to implement custom logging behaviour.
  1954. @see setCurrentLogger
  1955. */
  1956. virtual void logMessage (const String& message) = 0;
  1957. };
  1958. #endif // __JUCE_LOGGER_JUCEHEADER__
  1959. /********* End of inlined file: juce_Logger.h *********/
  1960. END_JUCE_NAMESPACE
  1961. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1962. /********* End of inlined file: juce_StandardHeader.h *********/
  1963. BEGIN_JUCE_NAMESPACE
  1964. #if JUCE_MSVC
  1965. // this is set explicitly in case the app is using a different packing size.
  1966. #pragma pack (push, 8)
  1967. #pragma warning (push)
  1968. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1969. #endif
  1970. #if JUCE_MAC || JUCE_IPHONE
  1971. #pragma align=natural
  1972. #endif
  1973. #define JUCE_PUBLIC_INCLUDES
  1974. // this is where all the class header files get brought in..
  1975. /********* Start of inlined file: juce_core_includes.h *********/
  1976. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1977. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1978. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1979. /********* Start of inlined file: juce_Atomic.h *********/
  1980. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1981. #define __JUCE_ATOMIC_JUCEHEADER__
  1982. // Atomic increment/decrement operations..
  1983. #if (JUCE_MAC || JUCE_IPHONE) && ! DOXYGEN
  1984. #include <libkern/OSAtomic.h>
  1985. static forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1986. static forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1987. static forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1988. static forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1989. #elif JUCE_GCC
  1990. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1991. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1992. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1993. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1994. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1995. #else
  1996. /** Increments an integer in a thread-safe way. */
  1997. forcedinline void atomicIncrement (int& variable) throw()
  1998. {
  1999. __asm__ __volatile__ (
  2000. #if JUCE_64BIT
  2001. "lock incl (%%rax)"
  2002. :
  2003. : "a" (&variable)
  2004. : "cc", "memory");
  2005. #else
  2006. "lock incl %0"
  2007. : "=m" (variable)
  2008. : "m" (variable));
  2009. #endif
  2010. }
  2011. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2012. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  2013. {
  2014. int result;
  2015. __asm__ __volatile__ (
  2016. #if JUCE_64BIT
  2017. "lock xaddl %%ebx, (%%rax) \n\
  2018. incl %%ebx"
  2019. : "=b" (result)
  2020. : "a" (&variable), "b" (1)
  2021. : "cc", "memory");
  2022. #else
  2023. "lock xaddl %%eax, (%%ecx) \n\
  2024. incl %%eax"
  2025. : "=a" (result)
  2026. : "c" (&variable), "a" (1)
  2027. : "memory");
  2028. #endif
  2029. return result;
  2030. }
  2031. /** Decrememts an integer in a thread-safe way. */
  2032. forcedinline void atomicDecrement (int& variable) throw()
  2033. {
  2034. __asm__ __volatile__ (
  2035. #if JUCE_64BIT
  2036. "lock decl (%%rax)"
  2037. :
  2038. : "a" (&variable)
  2039. : "cc", "memory");
  2040. #else
  2041. "lock decl %0"
  2042. : "=m" (variable)
  2043. : "m" (variable));
  2044. #endif
  2045. }
  2046. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2047. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  2048. {
  2049. int result;
  2050. __asm__ __volatile__ (
  2051. #if JUCE_64BIT
  2052. "lock xaddl %%ebx, (%%rax) \n\
  2053. decl %%ebx"
  2054. : "=b" (result)
  2055. : "a" (&variable), "b" (-1)
  2056. : "cc", "memory");
  2057. #else
  2058. "lock xaddl %%eax, (%%ecx) \n\
  2059. decl %%eax"
  2060. : "=a" (result)
  2061. : "c" (&variable), "a" (-1)
  2062. : "memory");
  2063. #endif
  2064. return result;
  2065. }
  2066. #endif
  2067. #elif JUCE_USE_INTRINSICS
  2068. #pragma intrinsic (_InterlockedIncrement)
  2069. #pragma intrinsic (_InterlockedDecrement)
  2070. /** Increments an integer in a thread-safe way. */
  2071. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2072. {
  2073. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2074. }
  2075. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2076. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2077. {
  2078. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2079. }
  2080. /** Decrememts an integer in a thread-safe way. */
  2081. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2082. {
  2083. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2084. }
  2085. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2086. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2087. {
  2088. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2089. }
  2090. #else
  2091. /** Increments an integer in a thread-safe way. */
  2092. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2093. {
  2094. __asm {
  2095. mov ecx, dword ptr [variable]
  2096. lock inc dword ptr [ecx]
  2097. }
  2098. }
  2099. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2100. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2101. {
  2102. int result;
  2103. __asm {
  2104. mov ecx, dword ptr [variable]
  2105. mov eax, 1
  2106. lock xadd dword ptr [ecx], eax
  2107. inc eax
  2108. mov result, eax
  2109. }
  2110. return result;
  2111. }
  2112. /** Decrememts an integer in a thread-safe way. */
  2113. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2114. {
  2115. __asm {
  2116. mov ecx, dword ptr [variable]
  2117. lock dec dword ptr [ecx]
  2118. }
  2119. }
  2120. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2121. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2122. {
  2123. int result;
  2124. __asm {
  2125. mov ecx, dword ptr [variable]
  2126. mov eax, -1
  2127. lock xadd dword ptr [ecx], eax
  2128. dec eax
  2129. mov result, eax
  2130. }
  2131. return result;
  2132. }
  2133. #endif
  2134. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2135. /********* End of inlined file: juce_Atomic.h *********/
  2136. #endif
  2137. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2138. #endif
  2139. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2140. /********* Start of inlined file: juce_FileLogger.h *********/
  2141. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2142. #define __JUCE_FILELOGGER_JUCEHEADER__
  2143. /********* Start of inlined file: juce_File.h *********/
  2144. #ifndef __JUCE_FILE_JUCEHEADER__
  2145. #define __JUCE_FILE_JUCEHEADER__
  2146. /********* Start of inlined file: juce_OwnedArray.h *********/
  2147. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2148. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2149. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2150. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2151. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2152. /** The default size of chunk in which arrays increase their storage.
  2153. Used by ArrayAllocationBase and its subclasses.
  2154. */
  2155. const int juceDefaultArrayGranularity = 8;
  2156. /**
  2157. Implements some basic array storage allocation functions.
  2158. This class isn't really for public use - it's used by the other
  2159. array classes, but might come in handy for some purposes.
  2160. @see Array, OwnedArray, ReferenceCountedArray
  2161. */
  2162. template <class ElementType>
  2163. class ArrayAllocationBase
  2164. {
  2165. protected:
  2166. /** Creates an empty array.
  2167. @param granularity_ this is the size of increment by which the internal storage
  2168. will be increased.
  2169. */
  2170. ArrayAllocationBase (const int granularity_) throw()
  2171. : elements (0),
  2172. numAllocated (0),
  2173. granularity (granularity_)
  2174. {
  2175. jassert (granularity > 0);
  2176. }
  2177. /** Destructor. */
  2178. ~ArrayAllocationBase() throw()
  2179. {
  2180. delete[] elements;
  2181. }
  2182. /** Changes the amount of storage allocated.
  2183. This will retain any data currently held in the array, and either add or
  2184. remove extra space at the end.
  2185. @param numElements the number of elements that are needed
  2186. */
  2187. void setAllocatedSize (const int numElements) throw()
  2188. {
  2189. if (numAllocated != numElements)
  2190. {
  2191. if (numElements > 0)
  2192. {
  2193. ElementType* const newElements = new ElementType [numElements];
  2194. const int itemsToRetain = jmin (numElements, numAllocated);
  2195. for (int i = 0; i < itemsToRetain; ++i)
  2196. newElements[i] = elements[i];
  2197. delete[] elements;
  2198. elements = newElements;
  2199. }
  2200. else if (elements != 0)
  2201. {
  2202. delete[] elements;
  2203. elements = 0;
  2204. }
  2205. numAllocated = numElements;
  2206. }
  2207. }
  2208. /** Increases the amount of storage allocated if it is less than a given amount.
  2209. This will retain any data currently held in the array, but will add
  2210. extra space at the end to make sure there it's at least as big as the size
  2211. passed in. If it's already bigger, no action is taken.
  2212. @param minNumElements the minimum number of elements that are needed
  2213. */
  2214. void ensureAllocatedSize (int minNumElements) throw()
  2215. {
  2216. if (minNumElements > numAllocated)
  2217. {
  2218. // for arrays with small granularity that get big, start
  2219. // increasing the size in bigger jumps
  2220. if (minNumElements > (granularity << 6))
  2221. {
  2222. minNumElements += (minNumElements / granularity);
  2223. if (minNumElements > (granularity << 8))
  2224. minNumElements += granularity << 6;
  2225. else
  2226. minNumElements += granularity << 5;
  2227. }
  2228. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2229. }
  2230. }
  2231. ElementType* elements;
  2232. int numAllocated, granularity;
  2233. private:
  2234. ArrayAllocationBase (const ArrayAllocationBase&);
  2235. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2236. };
  2237. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2238. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2239. /********* Start of inlined file: juce_ElementComparator.h *********/
  2240. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2241. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2242. /**
  2243. Sorts a range of elements in an array.
  2244. The comparator object that is passed-in must define a public method with the following
  2245. signature:
  2246. @code
  2247. int compareElements (ElementType first, ElementType second);
  2248. @endcode
  2249. ..and this method must return:
  2250. - a value of < 0 if the first comes before the second
  2251. - a value of 0 if the two objects are equivalent
  2252. - a value of > 0 if the second comes before the first
  2253. To improve performance, the compareElements() method can be declared as static or const.
  2254. @param comparator an object which defines a compareElements() method
  2255. @param array the array to sort
  2256. @param firstElement the index of the first element of the range to be sorted
  2257. @param lastElement the index of the last element in the range that needs
  2258. sorting (this is inclusive)
  2259. @param retainOrderOfEquivalentItems if true, the order of items that the
  2260. comparator deems the same will be maintained - this will be
  2261. a slower algorithm than if they are allowed to be moved around.
  2262. @see sortArrayRetainingOrder
  2263. */
  2264. template <class ElementType, class ElementComparator>
  2265. static void sortArray (ElementComparator& comparator,
  2266. ElementType* const array,
  2267. int firstElement,
  2268. int lastElement,
  2269. const bool retainOrderOfEquivalentItems)
  2270. {
  2271. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2272. // avoids getting warning messages about the parameter being unused
  2273. if (lastElement > firstElement)
  2274. {
  2275. if (retainOrderOfEquivalentItems)
  2276. {
  2277. for (int i = firstElement; i < lastElement; ++i)
  2278. {
  2279. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2280. {
  2281. const ElementType temp = array [i];
  2282. array [i] = array[i + 1];
  2283. array [i + 1] = temp;
  2284. if (i > firstElement)
  2285. i -= 2;
  2286. }
  2287. }
  2288. }
  2289. else
  2290. {
  2291. int fromStack[30], toStack[30];
  2292. int stackIndex = 0;
  2293. for (;;)
  2294. {
  2295. const int size = (lastElement - firstElement) + 1;
  2296. if (size <= 8)
  2297. {
  2298. int j = lastElement;
  2299. int maxIndex;
  2300. while (j > firstElement)
  2301. {
  2302. maxIndex = firstElement;
  2303. for (int k = firstElement + 1; k <= j; ++k)
  2304. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2305. maxIndex = k;
  2306. const ElementType temp = array [maxIndex];
  2307. array [maxIndex] = array[j];
  2308. array [j] = temp;
  2309. --j;
  2310. }
  2311. }
  2312. else
  2313. {
  2314. const int mid = firstElement + (size >> 1);
  2315. ElementType temp = array [mid];
  2316. array [mid] = array [firstElement];
  2317. array [firstElement] = temp;
  2318. int i = firstElement;
  2319. int j = lastElement + 1;
  2320. for (;;)
  2321. {
  2322. while (++i <= lastElement
  2323. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2324. {}
  2325. while (--j > firstElement
  2326. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2327. {}
  2328. if (j < i)
  2329. break;
  2330. temp = array[i];
  2331. array[i] = array[j];
  2332. array[j] = temp;
  2333. }
  2334. temp = array [firstElement];
  2335. array [firstElement] = array[j];
  2336. array [j] = temp;
  2337. if (j - 1 - firstElement >= lastElement - i)
  2338. {
  2339. if (firstElement + 1 < j)
  2340. {
  2341. fromStack [stackIndex] = firstElement;
  2342. toStack [stackIndex] = j - 1;
  2343. ++stackIndex;
  2344. }
  2345. if (i < lastElement)
  2346. {
  2347. firstElement = i;
  2348. continue;
  2349. }
  2350. }
  2351. else
  2352. {
  2353. if (i < lastElement)
  2354. {
  2355. fromStack [stackIndex] = i;
  2356. toStack [stackIndex] = lastElement;
  2357. ++stackIndex;
  2358. }
  2359. if (firstElement + 1 < j)
  2360. {
  2361. lastElement = j - 1;
  2362. continue;
  2363. }
  2364. }
  2365. }
  2366. if (--stackIndex < 0)
  2367. break;
  2368. jassert (stackIndex < numElementsInArray (fromStack));
  2369. firstElement = fromStack [stackIndex];
  2370. lastElement = toStack [stackIndex];
  2371. }
  2372. }
  2373. }
  2374. }
  2375. /**
  2376. Searches a sorted array of elements, looking for the index at which a specified value
  2377. should be inserted for it to be in the correct order.
  2378. The comparator object that is passed-in must define a public method with the following
  2379. signature:
  2380. @code
  2381. int compareElements (ElementType first, ElementType second);
  2382. @endcode
  2383. ..and this method must return:
  2384. - a value of < 0 if the first comes before the second
  2385. - a value of 0 if the two objects are equivalent
  2386. - a value of > 0 if the second comes before the first
  2387. To improve performance, the compareElements() method can be declared as static or const.
  2388. @param comparator an object which defines a compareElements() method
  2389. @param array the array to search
  2390. @param newElement the value that is going to be inserted
  2391. @param firstElement the index of the first element to search
  2392. @param lastElement the index of the last element in the range (this is non-inclusive)
  2393. */
  2394. template <class ElementType, class ElementComparator>
  2395. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2396. ElementType* const array,
  2397. const ElementType newElement,
  2398. int firstElement,
  2399. int lastElement)
  2400. {
  2401. jassert (firstElement <= lastElement);
  2402. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2403. // avoids getting warning messages about the parameter being unused
  2404. while (firstElement < lastElement)
  2405. {
  2406. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2407. {
  2408. ++firstElement;
  2409. break;
  2410. }
  2411. else
  2412. {
  2413. const int halfway = (firstElement + lastElement) >> 1;
  2414. if (halfway == firstElement)
  2415. {
  2416. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2417. ++firstElement;
  2418. break;
  2419. }
  2420. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2421. {
  2422. firstElement = halfway;
  2423. }
  2424. else
  2425. {
  2426. lastElement = halfway;
  2427. }
  2428. }
  2429. }
  2430. return firstElement;
  2431. }
  2432. /**
  2433. A simple ElementComparator class that can be used to sort an array of
  2434. integer primitive objects.
  2435. Example: @code
  2436. Array <int> myArray;
  2437. IntegerElementComparator<int> sorter;
  2438. myArray.sort (sorter);
  2439. @endcode
  2440. For floating point values, see the FloatElementComparator class instead.
  2441. @see FloatElementComparator, ElementComparator
  2442. */
  2443. template <class ElementType>
  2444. class IntegerElementComparator
  2445. {
  2446. public:
  2447. static int compareElements (const ElementType first,
  2448. const ElementType second) throw()
  2449. {
  2450. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2451. }
  2452. };
  2453. /**
  2454. A simple ElementComparator class that can be used to sort an array of numeric
  2455. double or floating point primitive objects.
  2456. Example: @code
  2457. Array <double> myArray;
  2458. FloatElementComparator<double> sorter;
  2459. myArray.sort (sorter);
  2460. @endcode
  2461. For integer values, see the IntegerElementComparator class instead.
  2462. @see IntegerElementComparator, ElementComparator
  2463. */
  2464. template <class ElementType>
  2465. class FloatElementComparator
  2466. {
  2467. public:
  2468. static int compareElements (const ElementType first,
  2469. const ElementType second) throw()
  2470. {
  2471. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2472. }
  2473. };
  2474. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2475. /********* End of inlined file: juce_ElementComparator.h *********/
  2476. /********* Start of inlined file: juce_CriticalSection.h *********/
  2477. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2478. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2479. /**
  2480. Prevents multiple threads from accessing shared objects at the same time.
  2481. @see ScopedLock, Thread, InterProcessLock
  2482. */
  2483. class JUCE_API CriticalSection
  2484. {
  2485. public:
  2486. /**
  2487. Creates a CriticalSection object
  2488. */
  2489. CriticalSection() throw();
  2490. /** Destroys a CriticalSection object.
  2491. If the critical section is deleted whilst locked, its subsequent behaviour
  2492. is unpredictable.
  2493. */
  2494. ~CriticalSection() throw();
  2495. /** Locks this critical section.
  2496. If the lock is currently held by another thread, this will wait until it
  2497. becomes free.
  2498. If the lock is already held by the caller thread, the method returns immediately.
  2499. @see exit, ScopedLock
  2500. */
  2501. void enter() const throw();
  2502. /** Attempts to lock this critical section without blocking.
  2503. This method behaves identically to CriticalSection::enter, except that the caller thread
  2504. does not wait if the lock is currently held by another thread but returns false immediately.
  2505. @returns false if the lock is currently held by another thread, true otherwise.
  2506. @see enter
  2507. */
  2508. bool tryEnter() const throw();
  2509. /** Releases the lock.
  2510. If the caller thread hasn't got the lock, this can have unpredictable results.
  2511. If the enter() method has been called multiple times by the thread, each
  2512. call must be matched by a call to exit() before other threads will be allowed
  2513. to take over the lock.
  2514. @see enter, ScopedLock
  2515. */
  2516. void exit() const throw();
  2517. juce_UseDebuggingNewOperator
  2518. private:
  2519. #if JUCE_WIN32
  2520. #if JUCE_64BIT
  2521. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2522. // block of memory here that's big enough to be used internally as a windows critical
  2523. // section object.
  2524. uint8 internal [44];
  2525. #else
  2526. uint8 internal [24];
  2527. #endif
  2528. #else
  2529. mutable pthread_mutex_t internal;
  2530. #endif
  2531. CriticalSection (const CriticalSection&);
  2532. const CriticalSection& operator= (const CriticalSection&);
  2533. };
  2534. /**
  2535. A class that can be used in place of a real CriticalSection object.
  2536. This is currently used by some templated array classes, and should get
  2537. optimised out by the compiler.
  2538. @see Array, OwnedArray, ReferenceCountedArray
  2539. */
  2540. class JUCE_API DummyCriticalSection
  2541. {
  2542. public:
  2543. forcedinline DummyCriticalSection() throw() {}
  2544. forcedinline ~DummyCriticalSection() throw() {}
  2545. forcedinline void enter() const throw() {}
  2546. forcedinline void exit() const throw() {}
  2547. };
  2548. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2549. /********* End of inlined file: juce_CriticalSection.h *********/
  2550. /** An array designed for holding objects.
  2551. This holds a list of pointers to objects, and will automatically
  2552. delete the objects when they are removed from the array, or when the
  2553. array is itself deleted.
  2554. Declare it in the form: OwnedArray<MyObjectClass>
  2555. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2556. After adding objects, they are 'owned' by the array and will be deleted when
  2557. removed or replaced.
  2558. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2559. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2560. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2561. */
  2562. template <class ObjectClass,
  2563. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2564. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2565. {
  2566. public:
  2567. /** Creates an empty array.
  2568. @param granularity this is the size of increment by which the internal storage
  2569. used by the array will grow. Only change it from the default if you know the
  2570. array is going to be very big and needs to be able to grow efficiently.
  2571. @see ArrayAllocationBase
  2572. */
  2573. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2574. : ArrayAllocationBase <ObjectClass*> (granularity),
  2575. numUsed (0)
  2576. {
  2577. }
  2578. /** Deletes the array and also deletes any objects inside it.
  2579. To get rid of the array without deleting its objects, use its
  2580. clear (false) method before deleting it.
  2581. */
  2582. ~OwnedArray()
  2583. {
  2584. clear (true);
  2585. }
  2586. /** Clears the array, optionally deleting the objects inside it first. */
  2587. void clear (const bool deleteObjects = true)
  2588. {
  2589. lock.enter();
  2590. if (deleteObjects)
  2591. {
  2592. while (numUsed > 0)
  2593. delete this->elements [--numUsed];
  2594. }
  2595. this->setAllocatedSize (0);
  2596. numUsed = 0;
  2597. lock.exit();
  2598. }
  2599. /** Returns the number of items currently in the array.
  2600. @see operator[]
  2601. */
  2602. inline int size() const throw()
  2603. {
  2604. return numUsed;
  2605. }
  2606. /** Returns a pointer to the object at this index in the array.
  2607. If the index is out-of-range, this will return a null pointer, (and
  2608. it could be null anyway, because it's ok for the array to hold null
  2609. pointers as well as objects).
  2610. @see getUnchecked
  2611. */
  2612. inline ObjectClass* operator[] (const int index) const throw()
  2613. {
  2614. lock.enter();
  2615. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2616. ? this->elements [index]
  2617. : (ObjectClass*) 0;
  2618. lock.exit();
  2619. return result;
  2620. }
  2621. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2622. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2623. it can be used when you're sure the index if always going to be legal.
  2624. */
  2625. inline ObjectClass* getUnchecked (const int index) const throw()
  2626. {
  2627. lock.enter();
  2628. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2629. ObjectClass* const result = this->elements [index];
  2630. lock.exit();
  2631. return result;
  2632. }
  2633. /** Returns a pointer to the first object in the array.
  2634. This will return a null pointer if the array's empty.
  2635. @see getLast
  2636. */
  2637. inline ObjectClass* getFirst() const throw()
  2638. {
  2639. lock.enter();
  2640. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2641. : (ObjectClass*) 0;
  2642. lock.exit();
  2643. return result;
  2644. }
  2645. /** Returns a pointer to the last object in the array.
  2646. This will return a null pointer if the array's empty.
  2647. @see getFirst
  2648. */
  2649. inline ObjectClass* getLast() const throw()
  2650. {
  2651. lock.enter();
  2652. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2653. : (ObjectClass*) 0;
  2654. lock.exit();
  2655. return result;
  2656. }
  2657. /** Finds the index of an object which might be in the array.
  2658. @param objectToLookFor the object to look for
  2659. @returns the index at which the object was found, or -1 if it's not found
  2660. */
  2661. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2662. {
  2663. int result = -1;
  2664. lock.enter();
  2665. ObjectClass* const* e = this->elements;
  2666. for (int i = numUsed; --i >= 0;)
  2667. {
  2668. if (objectToLookFor == *e)
  2669. {
  2670. result = (int) (e - this->elements);
  2671. break;
  2672. }
  2673. ++e;
  2674. }
  2675. lock.exit();
  2676. return result;
  2677. }
  2678. /** Returns true if the array contains a specified object.
  2679. @param objectToLookFor the object to look for
  2680. @returns true if the object is in the array
  2681. */
  2682. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2683. {
  2684. lock.enter();
  2685. ObjectClass* const* e = this->elements;
  2686. int i = numUsed;
  2687. while (i >= 4)
  2688. {
  2689. if (objectToLookFor == *e
  2690. || objectToLookFor == *++e
  2691. || objectToLookFor == *++e
  2692. || objectToLookFor == *++e)
  2693. {
  2694. lock.exit();
  2695. return true;
  2696. }
  2697. i -= 4;
  2698. ++e;
  2699. }
  2700. while (i > 0)
  2701. {
  2702. if (objectToLookFor == *e)
  2703. {
  2704. lock.exit();
  2705. return true;
  2706. }
  2707. --i;
  2708. ++e;
  2709. }
  2710. lock.exit();
  2711. return false;
  2712. }
  2713. /** Appends a new object to the end of the array.
  2714. Note that the this object will be deleted by the OwnedArray when it
  2715. is removed, so be careful not to delete it somewhere else.
  2716. Also be careful not to add the same object to the array more than once,
  2717. as this will obviously cause deletion of dangling pointers.
  2718. @param newObject the new object to add to the array
  2719. @see set, insert, addIfNotAlreadyThere, addSorted
  2720. */
  2721. void add (const ObjectClass* const newObject) throw()
  2722. {
  2723. lock.enter();
  2724. this->ensureAllocatedSize (numUsed + 1);
  2725. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2726. lock.exit();
  2727. }
  2728. /** Inserts a new object into the array at the given index.
  2729. Note that the this object will be deleted by the OwnedArray when it
  2730. is removed, so be careful not to delete it somewhere else.
  2731. If the index is less than 0 or greater than the size of the array, the
  2732. element will be added to the end of the array.
  2733. Otherwise, it will be inserted into the array, moving all the later elements
  2734. along to make room.
  2735. Be careful not to add the same object to the array more than once,
  2736. as this will obviously cause deletion of dangling pointers.
  2737. @param indexToInsertAt the index at which the new element should be inserted
  2738. @param newObject the new object to add to the array
  2739. @see add, addSorted, addIfNotAlreadyThere, set
  2740. */
  2741. void insert (int indexToInsertAt,
  2742. const ObjectClass* const newObject) throw()
  2743. {
  2744. if (indexToInsertAt >= 0)
  2745. {
  2746. lock.enter();
  2747. if (indexToInsertAt > numUsed)
  2748. indexToInsertAt = numUsed;
  2749. this->ensureAllocatedSize (numUsed + 1);
  2750. ObjectClass** const e = this->elements + indexToInsertAt;
  2751. const int numToMove = numUsed - indexToInsertAt;
  2752. if (numToMove > 0)
  2753. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2754. *e = const_cast <ObjectClass*> (newObject);
  2755. ++numUsed;
  2756. lock.exit();
  2757. }
  2758. else
  2759. {
  2760. add (newObject);
  2761. }
  2762. }
  2763. /** Appends a new object at the end of the array as long as the array doesn't
  2764. already contain it.
  2765. If the array already contains a matching object, nothing will be done.
  2766. @param newObject the new object to add to the array
  2767. */
  2768. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2769. {
  2770. lock.enter();
  2771. if (! contains (newObject))
  2772. add (newObject);
  2773. lock.exit();
  2774. }
  2775. /** Replaces an object in the array with a different one.
  2776. If the index is less than zero, this method does nothing.
  2777. If the index is beyond the end of the array, the new object is added to the end of the array.
  2778. Be careful not to add the same object to the array more than once,
  2779. as this will obviously cause deletion of dangling pointers.
  2780. @param indexToChange the index whose value you want to change
  2781. @param newObject the new value to set for this index.
  2782. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2783. @see add, insert, remove
  2784. */
  2785. void set (const int indexToChange,
  2786. const ObjectClass* const newObject,
  2787. const bool deleteOldElement = true)
  2788. {
  2789. if (indexToChange >= 0)
  2790. {
  2791. ObjectClass* toDelete = 0;
  2792. lock.enter();
  2793. if (indexToChange < numUsed)
  2794. {
  2795. if (deleteOldElement)
  2796. {
  2797. toDelete = this->elements [indexToChange];
  2798. if (toDelete == newObject)
  2799. toDelete = 0;
  2800. }
  2801. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2802. }
  2803. else
  2804. {
  2805. this->ensureAllocatedSize (numUsed + 1);
  2806. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2807. }
  2808. lock.exit();
  2809. delete toDelete;
  2810. }
  2811. }
  2812. /** Inserts a new object into the array assuming that the array is sorted.
  2813. This will use a comparator to find the position at which the new object
  2814. should go. If the array isn't sorted, the behaviour of this
  2815. method will be unpredictable.
  2816. @param comparator the comparator to use to compare the elements - see the sort method
  2817. for details about this object's structure
  2818. @param newObject the new object to insert to the array
  2819. @see add, sort, indexOfSorted
  2820. */
  2821. template <class ElementComparator>
  2822. void addSorted (ElementComparator& comparator,
  2823. ObjectClass* const newObject) throw()
  2824. {
  2825. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2826. // avoids getting warning messages about the parameter being unused
  2827. lock.enter();
  2828. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2829. lock.exit();
  2830. }
  2831. /** Finds the index of an object in the array, assuming that the array is sorted.
  2832. This will use a comparator to do a binary-chop to find the index of the given
  2833. element, if it exists. If the array isn't sorted, the behaviour of this
  2834. method will be unpredictable.
  2835. @param comparator the comparator to use to compare the elements - see the sort()
  2836. method for details about the form this object should take
  2837. @param objectToLookFor the object to search for
  2838. @returns the index of the element, or -1 if it's not found
  2839. @see addSorted, sort
  2840. */
  2841. template <class ElementComparator>
  2842. int indexOfSorted (ElementComparator& comparator,
  2843. const ObjectClass* const objectToLookFor) const throw()
  2844. {
  2845. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2846. // avoids getting warning messages about the parameter being unused
  2847. lock.enter();
  2848. int start = 0;
  2849. int end = numUsed;
  2850. for (;;)
  2851. {
  2852. if (start >= end)
  2853. {
  2854. lock.exit();
  2855. return -1;
  2856. }
  2857. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2858. {
  2859. lock.exit();
  2860. return start;
  2861. }
  2862. else
  2863. {
  2864. const int halfway = (start + end) >> 1;
  2865. if (halfway == start)
  2866. {
  2867. lock.exit();
  2868. return -1;
  2869. }
  2870. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2871. start = halfway;
  2872. else
  2873. end = halfway;
  2874. }
  2875. }
  2876. }
  2877. /** Removes an object from the array.
  2878. This will remove the object at a given index (optionally also
  2879. deleting it) and move back all the subsequent objects to close the gap.
  2880. If the index passed in is out-of-range, nothing will happen.
  2881. @param indexToRemove the index of the element to remove
  2882. @param deleteObject whether to delete the object that is removed
  2883. @see removeObject, removeRange
  2884. */
  2885. void remove (const int indexToRemove,
  2886. const bool deleteObject = true)
  2887. {
  2888. lock.enter();
  2889. ObjectClass* toDelete = 0;
  2890. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2891. {
  2892. ObjectClass** const e = this->elements + indexToRemove;
  2893. if (deleteObject)
  2894. toDelete = *e;
  2895. --numUsed;
  2896. const int numToShift = numUsed - indexToRemove;
  2897. if (numToShift > 0)
  2898. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2899. if ((numUsed << 1) < this->numAllocated)
  2900. minimiseStorageOverheads();
  2901. }
  2902. lock.exit();
  2903. delete toDelete;
  2904. }
  2905. /** Removes a specified object from the array.
  2906. If the item isn't found, no action is taken.
  2907. @param objectToRemove the object to try to remove
  2908. @param deleteObject whether to delete the object (if it's found)
  2909. @see remove, removeRange
  2910. */
  2911. void removeObject (const ObjectClass* const objectToRemove,
  2912. const bool deleteObject = true)
  2913. {
  2914. lock.enter();
  2915. ObjectClass** e = this->elements;
  2916. for (int i = numUsed; --i >= 0;)
  2917. {
  2918. if (objectToRemove == *e)
  2919. {
  2920. remove ((int) (e - this->elements), deleteObject);
  2921. break;
  2922. }
  2923. ++e;
  2924. }
  2925. lock.exit();
  2926. }
  2927. /** Removes a range of objects from the array.
  2928. This will remove a set of objects, starting from the given index,
  2929. and move any subsequent elements down to close the gap.
  2930. If the range extends beyond the bounds of the array, it will
  2931. be safely clipped to the size of the array.
  2932. @param startIndex the index of the first object to remove
  2933. @param numberToRemove how many objects should be removed
  2934. @param deleteObjects whether to delete the objects that get removed
  2935. @see remove, removeObject
  2936. */
  2937. void removeRange (int startIndex,
  2938. const int numberToRemove,
  2939. const bool deleteObjects = true)
  2940. {
  2941. lock.enter();
  2942. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2943. startIndex = jlimit (0, numUsed, startIndex);
  2944. if (endIndex > startIndex)
  2945. {
  2946. if (deleteObjects)
  2947. {
  2948. for (int i = startIndex; i < endIndex; ++i)
  2949. {
  2950. delete this->elements [i];
  2951. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2952. }
  2953. }
  2954. const int rangeSize = endIndex - startIndex;
  2955. ObjectClass** e = this->elements + startIndex;
  2956. int numToShift = numUsed - endIndex;
  2957. numUsed -= rangeSize;
  2958. while (--numToShift >= 0)
  2959. {
  2960. *e = e [rangeSize];
  2961. ++e;
  2962. }
  2963. if ((numUsed << 1) < this->numAllocated)
  2964. minimiseStorageOverheads();
  2965. }
  2966. lock.exit();
  2967. }
  2968. /** Removes the last n objects from the array.
  2969. @param howManyToRemove how many objects to remove from the end of the array
  2970. @param deleteObjects whether to also delete the objects that are removed
  2971. @see remove, removeObject, removeRange
  2972. */
  2973. void removeLast (int howManyToRemove = 1,
  2974. const bool deleteObjects = true)
  2975. {
  2976. lock.enter();
  2977. if (howManyToRemove >= numUsed)
  2978. {
  2979. clear (deleteObjects);
  2980. }
  2981. else
  2982. {
  2983. while (--howManyToRemove >= 0)
  2984. remove (numUsed - 1, deleteObjects);
  2985. }
  2986. lock.exit();
  2987. }
  2988. /** Swaps a pair of objects in the array.
  2989. If either of the indexes passed in is out-of-range, nothing will happen,
  2990. otherwise the two objects at these positions will be exchanged.
  2991. */
  2992. void swap (const int index1,
  2993. const int index2) throw()
  2994. {
  2995. lock.enter();
  2996. if (((unsigned int) index1) < (unsigned int) numUsed
  2997. && ((unsigned int) index2) < (unsigned int) numUsed)
  2998. {
  2999. swapVariables (this->elements [index1],
  3000. this->elements [index2]);
  3001. }
  3002. lock.exit();
  3003. }
  3004. /** Moves one of the objects to a different position.
  3005. This will move the object to a specified index, shuffling along
  3006. any intervening elements as required.
  3007. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3008. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3009. @param currentIndex the index of the object to be moved. If this isn't a
  3010. valid index, then nothing will be done
  3011. @param newIndex the index at which you'd like this object to end up. If this
  3012. is less than zero, it will be moved to the end of the array
  3013. */
  3014. void move (const int currentIndex,
  3015. int newIndex) throw()
  3016. {
  3017. if (currentIndex != newIndex)
  3018. {
  3019. lock.enter();
  3020. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3021. {
  3022. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3023. newIndex = numUsed - 1;
  3024. ObjectClass* const value = this->elements [currentIndex];
  3025. if (newIndex > currentIndex)
  3026. {
  3027. memmove (this->elements + currentIndex,
  3028. this->elements + currentIndex + 1,
  3029. (newIndex - currentIndex) * sizeof (ObjectClass*));
  3030. }
  3031. else
  3032. {
  3033. memmove (this->elements + newIndex + 1,
  3034. this->elements + newIndex,
  3035. (currentIndex - newIndex) * sizeof (ObjectClass*));
  3036. }
  3037. this->elements [newIndex] = value;
  3038. }
  3039. lock.exit();
  3040. }
  3041. }
  3042. /** This swaps the contents of this array with those of another array.
  3043. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3044. because it just swaps their internal pointers.
  3045. */
  3046. template <class OtherArrayType>
  3047. void swapWithArray (OtherArrayType& otherArray) throw()
  3048. {
  3049. lock.enter();
  3050. otherArray.lock.enter();
  3051. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3052. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  3053. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3054. otherArray.lock.exit();
  3055. lock.exit();
  3056. }
  3057. /** Reduces the amount of storage being used by the array.
  3058. Arrays typically allocate slightly more storage than they need, and after
  3059. removing elements, they may have quite a lot of unused space allocated.
  3060. This method will reduce the amount of allocated storage to a minimum.
  3061. */
  3062. void minimiseStorageOverheads() throw()
  3063. {
  3064. lock.enter();
  3065. if (numUsed == 0)
  3066. {
  3067. this->setAllocatedSize (0);
  3068. }
  3069. else
  3070. {
  3071. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3072. if (newAllocation < this->numAllocated)
  3073. this->setAllocatedSize (newAllocation);
  3074. }
  3075. lock.exit();
  3076. }
  3077. /** Increases the array's internal storage to hold a minimum number of elements.
  3078. Calling this before adding a large known number of elements means that
  3079. the array won't have to keep dynamically resizing itself as the elements
  3080. are added, and it'll therefore be more efficient.
  3081. */
  3082. void ensureStorageAllocated (const int minNumElements) throw()
  3083. {
  3084. this->ensureAllocatedSize (minNumElements);
  3085. }
  3086. /** Sorts the elements in the array.
  3087. This will use a comparator object to sort the elements into order. The object
  3088. passed must have a method of the form:
  3089. @code
  3090. int compareElements (ElementType first, ElementType second);
  3091. @endcode
  3092. ..and this method must return:
  3093. - a value of < 0 if the first comes before the second
  3094. - a value of 0 if the two objects are equivalent
  3095. - a value of > 0 if the second comes before the first
  3096. To improve performance, the compareElements() method can be declared as static or const.
  3097. @param comparator the comparator to use for comparing elements.
  3098. @param retainOrderOfEquivalentItems if this is true, then items
  3099. which the comparator says are equivalent will be
  3100. kept in the order in which they currently appear
  3101. in the array. This is slower to perform, but may
  3102. be important in some cases. If it's false, a faster
  3103. algorithm is used, but equivalent elements may be
  3104. rearranged.
  3105. @see sortArray, indexOfSorted
  3106. */
  3107. template <class ElementComparator>
  3108. void sort (ElementComparator& comparator,
  3109. const bool retainOrderOfEquivalentItems = false) const throw()
  3110. {
  3111. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3112. // avoids getting warning messages about the parameter being unused
  3113. lock.enter();
  3114. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3115. lock.exit();
  3116. }
  3117. /** Locks the array's CriticalSection.
  3118. Of course if the type of section used is a DummyCriticalSection, this won't
  3119. have any effect.
  3120. @see unlockArray
  3121. */
  3122. void lockArray() const throw()
  3123. {
  3124. lock.enter();
  3125. }
  3126. /** Unlocks the array's CriticalSection.
  3127. Of course if the type of section used is a DummyCriticalSection, this won't
  3128. have any effect.
  3129. @see lockArray
  3130. */
  3131. void unlockArray() const throw()
  3132. {
  3133. lock.exit();
  3134. }
  3135. juce_UseDebuggingNewOperator
  3136. private:
  3137. int numUsed;
  3138. TypeOfCriticalSectionToUse lock;
  3139. // disallow copy constructor and assignment
  3140. OwnedArray (const OwnedArray&);
  3141. const OwnedArray& operator= (const OwnedArray&);
  3142. };
  3143. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3144. /********* End of inlined file: juce_OwnedArray.h *********/
  3145. /********* Start of inlined file: juce_Time.h *********/
  3146. #ifndef __JUCE_TIME_JUCEHEADER__
  3147. #define __JUCE_TIME_JUCEHEADER__
  3148. /********* Start of inlined file: juce_RelativeTime.h *********/
  3149. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3150. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3151. /** A relative measure of time.
  3152. The time is stored as a number of seconds, at double-precision floating
  3153. point accuracy, and may be positive or negative.
  3154. If you need an absolute time, (i.e. a date + time), see the Time class.
  3155. */
  3156. class JUCE_API RelativeTime
  3157. {
  3158. public:
  3159. /** Creates a RelativeTime.
  3160. @param seconds the number of seconds, which may be +ve or -ve.
  3161. @see milliseconds, minutes, hours, days, weeks
  3162. */
  3163. explicit RelativeTime (const double seconds = 0.0) throw();
  3164. /** Copies another relative time. */
  3165. RelativeTime (const RelativeTime& other) throw();
  3166. /** Copies another relative time. */
  3167. const RelativeTime& operator= (const RelativeTime& other) throw();
  3168. /** Destructor. */
  3169. ~RelativeTime() throw();
  3170. /** Creates a new RelativeTime object representing a number of milliseconds.
  3171. @see minutes, hours, days, weeks
  3172. */
  3173. static const RelativeTime milliseconds (const int milliseconds) throw();
  3174. /** Creates a new RelativeTime object representing a number of milliseconds.
  3175. @see minutes, hours, days, weeks
  3176. */
  3177. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3178. /** Creates a new RelativeTime object representing a number of minutes.
  3179. @see milliseconds, hours, days, weeks
  3180. */
  3181. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3182. /** Creates a new RelativeTime object representing a number of hours.
  3183. @see milliseconds, minutes, days, weeks
  3184. */
  3185. static const RelativeTime hours (const double numberOfHours) throw();
  3186. /** Creates a new RelativeTime object representing a number of days.
  3187. @see milliseconds, minutes, hours, weeks
  3188. */
  3189. static const RelativeTime days (const double numberOfDays) throw();
  3190. /** Creates a new RelativeTime object representing a number of weeks.
  3191. @see milliseconds, minutes, hours, days
  3192. */
  3193. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3194. /** Returns the number of milliseconds this time represents.
  3195. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3196. */
  3197. int64 inMilliseconds() const throw();
  3198. /** Returns the number of seconds this time represents.
  3199. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3200. */
  3201. double inSeconds() const throw() { return seconds; }
  3202. /** Returns the number of minutes this time represents.
  3203. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3204. */
  3205. double inMinutes() const throw();
  3206. /** Returns the number of hours this time represents.
  3207. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3208. */
  3209. double inHours() const throw();
  3210. /** Returns the number of days this time represents.
  3211. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3212. */
  3213. double inDays() const throw();
  3214. /** Returns the number of weeks this time represents.
  3215. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3216. */
  3217. double inWeeks() const throw();
  3218. /** Returns a readable textual description of the time.
  3219. The exact format of the string returned will depend on
  3220. the magnitude of the time - e.g.
  3221. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3222. so that only the two most significant units are printed.
  3223. The returnValueForZeroTime value is the result that is returned if the
  3224. length is zero. Depending on your application you might want to use this
  3225. to return something more relevant like "empty" or "0 secs", etc.
  3226. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3227. */
  3228. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3229. /** Compares two RelativeTimes. */
  3230. bool operator== (const RelativeTime& other) const throw();
  3231. /** Compares two RelativeTimes. */
  3232. bool operator!= (const RelativeTime& other) const throw();
  3233. /** Compares two RelativeTimes. */
  3234. bool operator> (const RelativeTime& other) const throw();
  3235. /** Compares two RelativeTimes. */
  3236. bool operator< (const RelativeTime& other) const throw();
  3237. /** Compares two RelativeTimes. */
  3238. bool operator>= (const RelativeTime& other) const throw();
  3239. /** Compares two RelativeTimes. */
  3240. bool operator<= (const RelativeTime& other) const throw();
  3241. /** Adds another RelativeTime to this one and returns the result. */
  3242. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3243. /** Subtracts another RelativeTime from this one and returns the result. */
  3244. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3245. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3246. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3247. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3248. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3249. /** Adds another RelativeTime to this one. */
  3250. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3251. /** Subtracts another RelativeTime from this one. */
  3252. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3253. /** Adds a number of seconds to this time. */
  3254. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3255. /** Subtracts a number of seconds from this time. */
  3256. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3257. juce_UseDebuggingNewOperator
  3258. private:
  3259. double seconds;
  3260. };
  3261. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3262. /********* End of inlined file: juce_RelativeTime.h *********/
  3263. /**
  3264. Holds an absolute date and time.
  3265. Internally, the time is stored at millisecond precision.
  3266. @see RelativeTime
  3267. */
  3268. class JUCE_API Time
  3269. {
  3270. public:
  3271. /** Creates a Time object.
  3272. This default constructor creates a time of 1st January 1970, (which is
  3273. represented internally as 0ms).
  3274. To create a time object representing the current time, use getCurrentTime().
  3275. @see getCurrentTime
  3276. */
  3277. Time() throw();
  3278. /** Creates a copy of another Time object. */
  3279. Time (const Time& other) throw();
  3280. /** Creates a time based on a number of milliseconds.
  3281. The internal millisecond count is set to 0 (1st January 1970). To create a
  3282. time object set to the current time, use getCurrentTime().
  3283. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3284. 'epoch' (midnight Jan 1st 1970).
  3285. @see getCurrentTime, currentTimeMillis
  3286. */
  3287. Time (const int64 millisecondsSinceEpoch) throw();
  3288. /** Creates a time from a set of date components.
  3289. The timezone is assumed to be whatever the system is using as its locale.
  3290. @param year the year, in 4-digit format, e.g. 2004
  3291. @param month the month, in the range 0 to 11
  3292. @param day the day of the month, in the range 1 to 31
  3293. @param hours hours in 24-hour clock format, 0 to 23
  3294. @param minutes minutes 0 to 59
  3295. @param seconds seconds 0 to 59
  3296. @param milliseconds milliseconds 0 to 999
  3297. @param useLocalTime if true, encode using the current machine's local time; if
  3298. false, it will always work in GMT.
  3299. */
  3300. Time (const int year,
  3301. const int month,
  3302. const int day,
  3303. const int hours,
  3304. const int minutes,
  3305. const int seconds = 0,
  3306. const int milliseconds = 0,
  3307. const bool useLocalTime = true) throw();
  3308. /** Destructor. */
  3309. ~Time() throw();
  3310. /** Copies this time from another one. */
  3311. const Time& operator= (const Time& other) throw();
  3312. /** Returns a Time object that is set to the current system time.
  3313. @see currentTimeMillis
  3314. */
  3315. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3316. /** Returns the time as a number of milliseconds.
  3317. @returns the number of milliseconds this Time object represents, since
  3318. midnight jan 1st 1970.
  3319. @see getMilliseconds
  3320. */
  3321. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3322. /** Returns the year.
  3323. A 4-digit format is used, e.g. 2004.
  3324. */
  3325. int getYear() const throw();
  3326. /** Returns the number of the month.
  3327. The value returned is in the range 0 to 11.
  3328. @see getMonthName
  3329. */
  3330. int getMonth() const throw();
  3331. /** Returns the name of the month.
  3332. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3333. it'll return the long form, e.g. "January"
  3334. @see getMonth
  3335. */
  3336. const String getMonthName (const bool threeLetterVersion) const throw();
  3337. /** Returns the day of the month.
  3338. The value returned is in the range 1 to 31.
  3339. */
  3340. int getDayOfMonth() const throw();
  3341. /** Returns the number of the day of the week.
  3342. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3343. */
  3344. int getDayOfWeek() const throw();
  3345. /** Returns the name of the weekday.
  3346. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3347. false, it'll return the full version, e.g. "Tuesday".
  3348. */
  3349. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3350. /** Returns the number of hours since midnight.
  3351. This is in 24-hour clock format, in the range 0 to 23.
  3352. @see getHoursInAmPmFormat, isAfternoon
  3353. */
  3354. int getHours() const throw();
  3355. /** Returns true if the time is in the afternoon.
  3356. So it returns true for "PM", false for "AM".
  3357. @see getHoursInAmPmFormat, getHours
  3358. */
  3359. bool isAfternoon() const throw();
  3360. /** Returns the hours in 12-hour clock format.
  3361. This will return a value 1 to 12 - use isAfternoon() to find out
  3362. whether this is in the afternoon or morning.
  3363. @see getHours, isAfternoon
  3364. */
  3365. int getHoursInAmPmFormat() const throw();
  3366. /** Returns the number of minutes, 0 to 59. */
  3367. int getMinutes() const throw();
  3368. /** Returns the number of seconds, 0 to 59. */
  3369. int getSeconds() const throw();
  3370. /** Returns the number of milliseconds, 0 to 999.
  3371. Unlike toMilliseconds(), this just returns the position within the
  3372. current second rather than the total number since the epoch.
  3373. @see toMilliseconds
  3374. */
  3375. int getMilliseconds() const throw();
  3376. /** Returns true if the local timezone uses a daylight saving correction. */
  3377. bool isDaylightSavingTime() const throw();
  3378. /** Returns a 3-character string to indicate the local timezone. */
  3379. const String getTimeZone() const throw();
  3380. /** Quick way of getting a string version of a date and time.
  3381. For a more powerful way of formatting the date and time, see the formatted() method.
  3382. @param includeDate whether to include the date in the string
  3383. @param includeTime whether to include the time in the string
  3384. @param includeSeconds if the time is being included, this provides an option not to include
  3385. the seconds in it
  3386. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3387. hour notation.
  3388. @see formatted
  3389. */
  3390. const String toString (const bool includeDate,
  3391. const bool includeTime,
  3392. const bool includeSeconds = true,
  3393. const bool use24HourClock = false) const throw();
  3394. /** Converts this date/time to a string with a user-defined format.
  3395. This uses the C strftime() function to format this time as a string. To save you
  3396. looking it up, these are the escape codes that strftime uses (other codes might
  3397. work on some platforms and not others, but these are the common ones):
  3398. %a is replaced by the locale's abbreviated weekday name.
  3399. %A is replaced by the locale's full weekday name.
  3400. %b is replaced by the locale's abbreviated month name.
  3401. %B is replaced by the locale's full month name.
  3402. %c is replaced by the locale's appropriate date and time representation.
  3403. %d is replaced by the day of the month as a decimal number [01,31].
  3404. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3405. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3406. %j is replaced by the day of the year as a decimal number [001,366].
  3407. %m is replaced by the month as a decimal number [01,12].
  3408. %M is replaced by the minute as a decimal number [00,59].
  3409. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3410. %S is replaced by the second as a decimal number [00,61].
  3411. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3412. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3413. %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.
  3414. %x is replaced by the locale's appropriate date representation.
  3415. %X is replaced by the locale's appropriate time representation.
  3416. %y is replaced by the year without century as a decimal number [00,99].
  3417. %Y is replaced by the year with century as a decimal number.
  3418. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3419. %% is replaced by %.
  3420. @see toString
  3421. */
  3422. const String formatted (const tchar* const format) const throw();
  3423. /** Adds a RelativeTime to this time and returns the result. */
  3424. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3425. /** Subtracts a RelativeTime from this time and returns the result. */
  3426. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3427. /** Returns the relative time difference between this time and another one. */
  3428. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3429. /** Compares two Time objects. */
  3430. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3431. /** Compares two Time objects. */
  3432. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3433. /** Compares two Time objects. */
  3434. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3435. /** Compares two Time objects. */
  3436. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3437. /** Compares two Time objects. */
  3438. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3439. /** Compares two Time objects. */
  3440. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3441. /** Tries to set the computer's clock.
  3442. @returns true if this succeeds, although depending on the system, the
  3443. application might not have sufficient privileges to do this.
  3444. */
  3445. bool setSystemTimeToThisTime() const throw();
  3446. /** Returns the name of a day of the week.
  3447. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3448. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3449. false, it'll return the full version, e.g. "Tuesday".
  3450. */
  3451. static const String getWeekdayName (int dayNumber,
  3452. const bool threeLetterVersion) throw();
  3453. /** Returns the name of one of the months.
  3454. @param monthNumber the month, 0 to 11
  3455. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3456. it'll return the long form, e.g. "January"
  3457. */
  3458. static const String getMonthName (int monthNumber,
  3459. const bool threeLetterVersion) throw();
  3460. // Static methods for getting system timers directly..
  3461. /** Returns the current system time.
  3462. Returns the number of milliseconds since midnight jan 1st 1970.
  3463. Should be accurate to within a few millisecs, depending on platform,
  3464. hardware, etc.
  3465. */
  3466. static int64 currentTimeMillis() throw();
  3467. /** Returns the number of millisecs since system startup.
  3468. Should be accurate to within a few millisecs, depending on platform,
  3469. hardware, etc.
  3470. @see getApproximateMillisecondCounter
  3471. */
  3472. static uint32 getMillisecondCounter() throw();
  3473. /** Returns the number of millisecs since system startup.
  3474. Same as getMillisecondCounter(), but returns a more accurate value, using
  3475. the high-res timer.
  3476. @see getMillisecondCounter
  3477. */
  3478. static double getMillisecondCounterHiRes() throw();
  3479. /** Waits until the getMillisecondCounter() reaches a given value.
  3480. This will make the thread sleep as efficiently as it can while it's waiting.
  3481. */
  3482. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3483. /** Less-accurate but faster version of getMillisecondCounter().
  3484. This will return the last value that getMillisecondCounter() returned, so doesn't
  3485. need to make a system call, but is less accurate - it shouldn't be more than
  3486. 100ms away from the correct time, though, so is still accurate enough for a
  3487. lot of purposes.
  3488. @see getMillisecondCounter
  3489. */
  3490. static uint32 getApproximateMillisecondCounter() throw();
  3491. // High-resolution timers..
  3492. /** Returns the current high-resolution counter's tick-count.
  3493. This is a similar idea to getMillisecondCounter(), but with a higher
  3494. resolution.
  3495. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3496. secondsToHighResolutionTicks
  3497. */
  3498. static int64 getHighResolutionTicks() throw();
  3499. /** Returns the resolution of the high-resolution counter in ticks per second.
  3500. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3501. secondsToHighResolutionTicks
  3502. */
  3503. static int64 getHighResolutionTicksPerSecond() throw();
  3504. /** Converts a number of high-resolution ticks into seconds.
  3505. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3506. secondsToHighResolutionTicks
  3507. */
  3508. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3509. /** Converts a number seconds into high-resolution ticks.
  3510. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3511. highResolutionTicksToSeconds
  3512. */
  3513. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3514. private:
  3515. int64 millisSinceEpoch;
  3516. };
  3517. #endif // __JUCE_TIME_JUCEHEADER__
  3518. /********* End of inlined file: juce_Time.h *********/
  3519. /********* Start of inlined file: juce_StringArray.h *********/
  3520. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3521. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3522. /********* Start of inlined file: juce_VoidArray.h *********/
  3523. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3524. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3525. /********* Start of inlined file: juce_Array.h *********/
  3526. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3527. #define __JUCE_ARRAY_JUCEHEADER__
  3528. /**
  3529. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3530. Examples of arrays are: Array<int> or Array<MyClass*>
  3531. Note that when holding pointers to objects, the array doesn't take any ownership
  3532. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3533. If you're using a class or struct as the element type, it must be
  3534. capable of being copied or moved with a straightforward memcpy, rather than
  3535. needing construction and destruction code.
  3536. For holding lists of strings, use the specialised class StringArray.
  3537. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3538. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3539. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3540. */
  3541. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3542. class Array : private ArrayAllocationBase <ElementType>
  3543. {
  3544. public:
  3545. /** Creates an empty array.
  3546. @param granularity this is the size of increment by which the internal storage
  3547. used by the array will grow. Only change it from the default if you know the
  3548. array is going to be very big and needs to be able to grow efficiently.
  3549. @see ArrayAllocationBase
  3550. */
  3551. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3552. : ArrayAllocationBase <ElementType> (granularity),
  3553. numUsed (0)
  3554. {
  3555. }
  3556. /** Creates a copy of another array.
  3557. @param other the array to copy
  3558. */
  3559. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3560. : ArrayAllocationBase <ElementType> (other.granularity)
  3561. {
  3562. other.lockArray();
  3563. numUsed = other.numUsed;
  3564. this->setAllocatedSize (other.numUsed);
  3565. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3566. other.unlockArray();
  3567. }
  3568. /** Initalises from a null-terminated C array of values.
  3569. @param values the array to copy from
  3570. */
  3571. Array (const ElementType* values) throw()
  3572. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3573. numUsed (0)
  3574. {
  3575. while (*values != 0)
  3576. add (*values++);
  3577. }
  3578. /** Initalises from a C array of values.
  3579. @param values the array to copy from
  3580. @param numValues the number of values in the array
  3581. */
  3582. Array (const ElementType* values, int numValues) throw()
  3583. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3584. numUsed (numValues)
  3585. {
  3586. this->setAllocatedSize (numValues);
  3587. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3588. }
  3589. /** Destructor. */
  3590. ~Array() throw()
  3591. {
  3592. }
  3593. /** Copies another array.
  3594. @param other the array to copy
  3595. */
  3596. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3597. {
  3598. if (this != &other)
  3599. {
  3600. other.lockArray();
  3601. lock.enter();
  3602. this->granularity = other.granularity;
  3603. this->ensureAllocatedSize (other.size());
  3604. numUsed = other.numUsed;
  3605. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3606. minimiseStorageOverheads();
  3607. lock.exit();
  3608. other.unlockArray();
  3609. }
  3610. return *this;
  3611. }
  3612. /** Compares this array to another one.
  3613. Two arrays are considered equal if they both contain the same set of
  3614. elements, in the same order.
  3615. @param other the other array to compare with
  3616. */
  3617. template <class OtherArrayType>
  3618. bool operator== (const OtherArrayType& other) const throw()
  3619. {
  3620. lock.enter();
  3621. if (this->numUsed != other.numUsed)
  3622. {
  3623. lock.exit();
  3624. return false;
  3625. }
  3626. for (int i = numUsed; --i >= 0;)
  3627. {
  3628. if (this->elements [i] != other.elements [i])
  3629. {
  3630. lock.exit();
  3631. return false;
  3632. }
  3633. }
  3634. lock.exit();
  3635. return true;
  3636. }
  3637. /** Compares this array to another one.
  3638. Two arrays are considered equal if they both contain the same set of
  3639. elements, in the same order.
  3640. @param other the other array to compare with
  3641. */
  3642. template <class OtherArrayType>
  3643. bool operator!= (const OtherArrayType& other) const throw()
  3644. {
  3645. return ! operator== (other);
  3646. }
  3647. /** Removes all elements from the array.
  3648. This will remove all the elements, and free any storage that the array is
  3649. using. To clear the array without freeing the storage, use the clearQuick()
  3650. method instead.
  3651. @see clearQuick
  3652. */
  3653. void clear() throw()
  3654. {
  3655. lock.enter();
  3656. this->setAllocatedSize (0);
  3657. numUsed = 0;
  3658. lock.exit();
  3659. }
  3660. /** Removes all elements from the array without freeing the array's allocated storage.
  3661. @see clear
  3662. */
  3663. void clearQuick() throw()
  3664. {
  3665. lock.enter();
  3666. numUsed = 0;
  3667. lock.exit();
  3668. }
  3669. /** Returns the current number of elements in the array.
  3670. */
  3671. inline int size() const throw()
  3672. {
  3673. return numUsed;
  3674. }
  3675. /** Returns one of the elements in the array.
  3676. If the index passed in is beyond the range of valid elements, this
  3677. will return zero.
  3678. If you're certain that the index will always be a valid element, you
  3679. can call getUnchecked() instead, which is faster.
  3680. @param index the index of the element being requested (0 is the first element in the array)
  3681. @see getUnchecked, getFirst, getLast
  3682. */
  3683. inline ElementType operator[] (const int index) const throw()
  3684. {
  3685. lock.enter();
  3686. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3687. ? this->elements [index]
  3688. : ElementType();
  3689. lock.exit();
  3690. return result;
  3691. }
  3692. /** Returns one of the elements in the array, without checking the index passed in.
  3693. Unlike the operator[] method, this will try to return an element without
  3694. checking that the index is within the bounds of the array, so should only
  3695. be used when you're confident that it will always be a valid index.
  3696. @param index the index of the element being requested (0 is the first element in the array)
  3697. @see operator[], getFirst, getLast
  3698. */
  3699. inline ElementType getUnchecked (const int index) const throw()
  3700. {
  3701. lock.enter();
  3702. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3703. const ElementType result = this->elements [index];
  3704. lock.exit();
  3705. return result;
  3706. }
  3707. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3708. This is like getUnchecked, but returns a direct reference to the element, so that
  3709. you can alter it directly. Obviously this can be dangerous, so only use it when
  3710. absolutely necessary.
  3711. @param index the index of the element being requested (0 is the first element in the array)
  3712. @see operator[], getFirst, getLast
  3713. */
  3714. inline ElementType& getReference (const int index) const throw()
  3715. {
  3716. lock.enter();
  3717. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3718. ElementType& result = this->elements [index];
  3719. lock.exit();
  3720. return result;
  3721. }
  3722. /** Returns the first element in the array, or 0 if the array is empty.
  3723. @see operator[], getUnchecked, getLast
  3724. */
  3725. inline ElementType getFirst() const throw()
  3726. {
  3727. lock.enter();
  3728. const ElementType result = (numUsed > 0) ? this->elements [0]
  3729. : ElementType();
  3730. lock.exit();
  3731. return result;
  3732. }
  3733. /** Returns the last element in the array, or 0 if the array is empty.
  3734. @see operator[], getUnchecked, getFirst
  3735. */
  3736. inline ElementType getLast() const throw()
  3737. {
  3738. lock.enter();
  3739. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3740. : ElementType();
  3741. lock.exit();
  3742. return result;
  3743. }
  3744. /** Finds the index of the first element which matches the value passed in.
  3745. This will search the array for the given object, and return the index
  3746. of its first occurrence. If the object isn't found, the method will return -1.
  3747. @param elementToLookFor the value or object to look for
  3748. @returns the index of the object, or -1 if it's not found
  3749. */
  3750. int indexOf (const ElementType elementToLookFor) const throw()
  3751. {
  3752. int result = -1;
  3753. lock.enter();
  3754. const ElementType* e = this->elements;
  3755. for (int i = numUsed; --i >= 0;)
  3756. {
  3757. if (elementToLookFor == *e)
  3758. {
  3759. result = (int) (e - this->elements);
  3760. break;
  3761. }
  3762. ++e;
  3763. }
  3764. lock.exit();
  3765. return result;
  3766. }
  3767. /** Returns true if the array contains at least one occurrence of an object.
  3768. @param elementToLookFor the value or object to look for
  3769. @returns true if the item is found
  3770. */
  3771. bool contains (const ElementType elementToLookFor) const throw()
  3772. {
  3773. lock.enter();
  3774. const ElementType* e = this->elements;
  3775. int num = numUsed;
  3776. while (num >= 4)
  3777. {
  3778. if (*e == elementToLookFor
  3779. || *++e == elementToLookFor
  3780. || *++e == elementToLookFor
  3781. || *++e == elementToLookFor)
  3782. {
  3783. lock.exit();
  3784. return true;
  3785. }
  3786. num -= 4;
  3787. ++e;
  3788. }
  3789. while (num > 0)
  3790. {
  3791. if (elementToLookFor == *e)
  3792. {
  3793. lock.exit();
  3794. return true;
  3795. }
  3796. --num;
  3797. ++e;
  3798. }
  3799. lock.exit();
  3800. return false;
  3801. }
  3802. /** Appends a new element at the end of the array.
  3803. @param newElement the new object to add to the array
  3804. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3805. */
  3806. void add (const ElementType newElement) throw()
  3807. {
  3808. lock.enter();
  3809. this->ensureAllocatedSize (numUsed + 1);
  3810. this->elements [numUsed++] = newElement;
  3811. lock.exit();
  3812. }
  3813. /** Inserts a new element into the array at a given position.
  3814. If the index is less than 0 or greater than the size of the array, the
  3815. element will be added to the end of the array.
  3816. Otherwise, it will be inserted into the array, moving all the later elements
  3817. along to make room.
  3818. @param indexToInsertAt the index at which the new element should be
  3819. inserted (pass in -1 to add it to the end)
  3820. @param newElement the new object to add to the array
  3821. @see add, addSorted, set
  3822. */
  3823. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3824. {
  3825. lock.enter();
  3826. this->ensureAllocatedSize (numUsed + 1);
  3827. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3828. {
  3829. ElementType* const insertPos = this->elements + indexToInsertAt;
  3830. const int numberToMove = numUsed - indexToInsertAt;
  3831. if (numberToMove > 0)
  3832. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3833. *insertPos = newElement;
  3834. ++numUsed;
  3835. }
  3836. else
  3837. {
  3838. this->elements [numUsed++] = newElement;
  3839. }
  3840. lock.exit();
  3841. }
  3842. /** Inserts multiple copies of an element into the array at a given position.
  3843. If the index is less than 0 or greater than the size of the array, the
  3844. element will be added to the end of the array.
  3845. Otherwise, it will be inserted into the array, moving all the later elements
  3846. along to make room.
  3847. @param indexToInsertAt the index at which the new element should be inserted
  3848. @param newElement the new object to add to the array
  3849. @param numberOfTimesToInsertIt how many copies of the value to insert
  3850. @see insert, add, addSorted, set
  3851. */
  3852. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3853. int numberOfTimesToInsertIt) throw()
  3854. {
  3855. if (numberOfTimesToInsertIt > 0)
  3856. {
  3857. lock.enter();
  3858. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3859. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3860. {
  3861. ElementType* insertPos = this->elements + indexToInsertAt;
  3862. const int numberToMove = numUsed - indexToInsertAt;
  3863. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3864. numUsed += numberOfTimesToInsertIt;
  3865. while (--numberOfTimesToInsertIt >= 0)
  3866. *insertPos++ = newElement;
  3867. }
  3868. else
  3869. {
  3870. while (--numberOfTimesToInsertIt >= 0)
  3871. this->elements [numUsed++] = newElement;
  3872. }
  3873. lock.exit();
  3874. }
  3875. }
  3876. /** Inserts an array of values into this array at a given position.
  3877. If the index is less than 0 or greater than the size of the array, the
  3878. new elements will be added to the end of the array.
  3879. Otherwise, they will be inserted into the array, moving all the later elements
  3880. along to make room.
  3881. @param indexToInsertAt the index at which the first new element should be inserted
  3882. @param newElements the new values to add to the array
  3883. @param numberOfElements how many items are in the array
  3884. @see insert, add, addSorted, set
  3885. */
  3886. void insertArray (int indexToInsertAt,
  3887. const ElementType* newElements,
  3888. int numberOfElements) throw()
  3889. {
  3890. if (numberOfElements > 0)
  3891. {
  3892. lock.enter();
  3893. this->ensureAllocatedSize (numUsed + numberOfElements);
  3894. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3895. {
  3896. ElementType* insertPos = this->elements + indexToInsertAt;
  3897. const int numberToMove = numUsed - indexToInsertAt;
  3898. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3899. numUsed += numberOfElements;
  3900. while (--numberOfElements >= 0)
  3901. *insertPos++ = *newElements++;
  3902. }
  3903. else
  3904. {
  3905. while (--numberOfElements >= 0)
  3906. this->elements [numUsed++] = *newElements++;
  3907. }
  3908. lock.exit();
  3909. }
  3910. }
  3911. /** Appends a new element at the end of the array as long as the array doesn't
  3912. already contain it.
  3913. If the array already contains an element that matches the one passed in, nothing
  3914. will be done.
  3915. @param newElement the new object to add to the array
  3916. */
  3917. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3918. {
  3919. lock.enter();
  3920. if (! contains (newElement))
  3921. add (newElement);
  3922. lock.exit();
  3923. }
  3924. /** Replaces an element with a new value.
  3925. If the index is less than zero, this method does nothing.
  3926. If the index is beyond the end of the array, the item is added to the end of the array.
  3927. @param indexToChange the index whose value you want to change
  3928. @param newValue the new value to set for this index.
  3929. @see add, insert
  3930. */
  3931. void set (const int indexToChange,
  3932. const ElementType newValue) throw()
  3933. {
  3934. jassert (indexToChange >= 0);
  3935. if (indexToChange >= 0)
  3936. {
  3937. lock.enter();
  3938. if (indexToChange < numUsed)
  3939. {
  3940. this->elements [indexToChange] = newValue;
  3941. }
  3942. else
  3943. {
  3944. this->ensureAllocatedSize (numUsed + 1);
  3945. this->elements [numUsed++] = newValue;
  3946. }
  3947. lock.exit();
  3948. }
  3949. }
  3950. /** Replaces an element with a new value without doing any bounds-checking.
  3951. This just sets a value directly in the array's internal storage, so you'd
  3952. better make sure it's in range!
  3953. @param indexToChange the index whose value you want to change
  3954. @param newValue the new value to set for this index.
  3955. @see set, getUnchecked
  3956. */
  3957. void setUnchecked (const int indexToChange,
  3958. const ElementType newValue) throw()
  3959. {
  3960. lock.enter();
  3961. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3962. this->elements [indexToChange] = newValue;
  3963. lock.exit();
  3964. }
  3965. /** Adds elements from an array to the end of this array.
  3966. @param elementsToAdd the array of elements to add
  3967. @param numElementsToAdd how many elements are in this other array
  3968. @see add
  3969. */
  3970. void addArray (const ElementType* elementsToAdd,
  3971. int numElementsToAdd) throw()
  3972. {
  3973. lock.enter();
  3974. if (numElementsToAdd > 0)
  3975. {
  3976. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3977. while (--numElementsToAdd >= 0)
  3978. this->elements [numUsed++] = *elementsToAdd++;
  3979. }
  3980. lock.exit();
  3981. }
  3982. /** This swaps the contents of this array with those of another array.
  3983. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3984. because it just swaps their internal pointers.
  3985. */
  3986. template <class OtherArrayType>
  3987. void swapWithArray (OtherArrayType& otherArray) throw()
  3988. {
  3989. lock.enter();
  3990. otherArray.lock.enter();
  3991. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3992. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3993. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3994. otherArray.lock.exit();
  3995. lock.exit();
  3996. }
  3997. /** Adds elements from another array to the end of this array.
  3998. @param arrayToAddFrom the array from which to copy the elements
  3999. @param startIndex the first element of the other array to start copying from
  4000. @param numElementsToAdd how many elements to add from the other array. If this
  4001. value is negative or greater than the number of available elements,
  4002. all available elements will be copied.
  4003. @see add
  4004. */
  4005. template <class OtherArrayType>
  4006. void addArray (const OtherArrayType& arrayToAddFrom,
  4007. int startIndex = 0,
  4008. int numElementsToAdd = -1) throw()
  4009. {
  4010. arrayToAddFrom.lockArray();
  4011. lock.enter();
  4012. jassert (this != &arrayToAddFrom);
  4013. if (startIndex < 0)
  4014. {
  4015. jassertfalse
  4016. startIndex = 0;
  4017. }
  4018. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  4019. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  4020. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  4021. lock.exit();
  4022. arrayToAddFrom.unlockArray();
  4023. }
  4024. /** Inserts a new element into the array, assuming that the array is sorted.
  4025. This will use a comparator to find the position at which the new element
  4026. should go. If the array isn't sorted, the behaviour of this
  4027. method will be unpredictable.
  4028. @param comparator the comparator to use to compare the elements - see the sort()
  4029. method for details about the form this object should take
  4030. @param newElement the new element to insert to the array
  4031. @see add, sort
  4032. */
  4033. template <class ElementComparator>
  4034. void addSorted (ElementComparator& comparator,
  4035. const ElementType newElement) throw()
  4036. {
  4037. lock.enter();
  4038. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  4039. lock.exit();
  4040. }
  4041. /** Finds the index of an element in the array, assuming that the array is sorted.
  4042. This will use a comparator to do a binary-chop to find the index of the given
  4043. element, if it exists. If the array isn't sorted, the behaviour of this
  4044. method will be unpredictable.
  4045. @param comparator the comparator to use to compare the elements - see the sort()
  4046. method for details about the form this object should take
  4047. @param elementToLookFor the element to search for
  4048. @returns the index of the element, or -1 if it's not found
  4049. @see addSorted, sort
  4050. */
  4051. template <class ElementComparator>
  4052. int indexOfSorted (ElementComparator& comparator,
  4053. const ElementType elementToLookFor) const throw()
  4054. {
  4055. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4056. // avoids getting warning messages about the parameter being unused
  4057. lock.enter();
  4058. int start = 0;
  4059. int end = numUsed;
  4060. for (;;)
  4061. {
  4062. if (start >= end)
  4063. {
  4064. lock.exit();
  4065. return -1;
  4066. }
  4067. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4068. {
  4069. lock.exit();
  4070. return start;
  4071. }
  4072. else
  4073. {
  4074. const int halfway = (start + end) >> 1;
  4075. if (halfway == start)
  4076. {
  4077. lock.exit();
  4078. return -1;
  4079. }
  4080. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4081. start = halfway;
  4082. else
  4083. end = halfway;
  4084. }
  4085. }
  4086. }
  4087. /** Removes an element from the array.
  4088. This will remove the element at a given index, and move back
  4089. all the subsequent elements to close the gap.
  4090. If the index passed in is out-of-range, nothing will happen.
  4091. @param indexToRemove the index of the element to remove
  4092. @returns the element that has been removed
  4093. @see removeValue, removeRange
  4094. */
  4095. ElementType remove (const int indexToRemove) throw()
  4096. {
  4097. lock.enter();
  4098. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4099. {
  4100. --numUsed;
  4101. ElementType* const e = this->elements + indexToRemove;
  4102. ElementType const removed = *e;
  4103. const int numberToShift = numUsed - indexToRemove;
  4104. if (numberToShift > 0)
  4105. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4106. if ((numUsed << 1) < this->numAllocated)
  4107. minimiseStorageOverheads();
  4108. lock.exit();
  4109. return removed;
  4110. }
  4111. else
  4112. {
  4113. lock.exit();
  4114. return ElementType();
  4115. }
  4116. }
  4117. /** Removes an item from the array.
  4118. This will remove the first occurrence of the given element from the array.
  4119. If the item isn't found, no action is taken.
  4120. @param valueToRemove the object to try to remove
  4121. @see remove, removeRange
  4122. */
  4123. void removeValue (const ElementType valueToRemove) throw()
  4124. {
  4125. lock.enter();
  4126. ElementType* e = this->elements;
  4127. for (int i = numUsed; --i >= 0;)
  4128. {
  4129. if (valueToRemove == *e)
  4130. {
  4131. remove ((int) (e - this->elements));
  4132. break;
  4133. }
  4134. ++e;
  4135. }
  4136. lock.exit();
  4137. }
  4138. /** Removes a range of elements from the array.
  4139. This will remove a set of elements, starting from the given index,
  4140. and move subsequent elements down to close the gap.
  4141. If the range extends beyond the bounds of the array, it will
  4142. be safely clipped to the size of the array.
  4143. @param startIndex the index of the first element to remove
  4144. @param numberToRemove how many elements should be removed
  4145. @see remove, removeValue
  4146. */
  4147. void removeRange (int startIndex,
  4148. const int numberToRemove) throw()
  4149. {
  4150. lock.enter();
  4151. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4152. startIndex = jlimit (0, numUsed, startIndex);
  4153. if (endIndex > startIndex)
  4154. {
  4155. const int rangeSize = endIndex - startIndex;
  4156. ElementType* e = this->elements + startIndex;
  4157. int numToShift = numUsed - endIndex;
  4158. numUsed -= rangeSize;
  4159. while (--numToShift >= 0)
  4160. {
  4161. *e = e [rangeSize];
  4162. ++e;
  4163. }
  4164. if ((numUsed << 1) < this->numAllocated)
  4165. minimiseStorageOverheads();
  4166. }
  4167. lock.exit();
  4168. }
  4169. /** Removes the last n elements from the array.
  4170. @param howManyToRemove how many elements to remove from the end of the array
  4171. @see remove, removeValue, removeRange
  4172. */
  4173. void removeLast (const int howManyToRemove = 1) throw()
  4174. {
  4175. lock.enter();
  4176. numUsed = jmax (0, numUsed - howManyToRemove);
  4177. if ((numUsed << 1) < this->numAllocated)
  4178. minimiseStorageOverheads();
  4179. lock.exit();
  4180. }
  4181. /** Removes any elements which are also in another array.
  4182. @param otherArray the other array in which to look for elements to remove
  4183. @see removeValuesNotIn, remove, removeValue, removeRange
  4184. */
  4185. template <class OtherArrayType>
  4186. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4187. {
  4188. otherArray.lockArray();
  4189. lock.enter();
  4190. if (this == &otherArray)
  4191. {
  4192. clear();
  4193. }
  4194. else
  4195. {
  4196. if (otherArray.size() > 0)
  4197. {
  4198. for (int i = numUsed; --i >= 0;)
  4199. if (otherArray.contains (this->elements [i]))
  4200. remove (i);
  4201. }
  4202. }
  4203. lock.exit();
  4204. otherArray.unlockArray();
  4205. }
  4206. /** Removes any elements which are not found in another array.
  4207. Only elements which occur in this other array will be retained.
  4208. @param otherArray the array in which to look for elements NOT to remove
  4209. @see removeValuesIn, remove, removeValue, removeRange
  4210. */
  4211. template <class OtherArrayType>
  4212. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4213. {
  4214. otherArray.lockArray();
  4215. lock.enter();
  4216. if (this != &otherArray)
  4217. {
  4218. if (otherArray.size() <= 0)
  4219. {
  4220. clear();
  4221. }
  4222. else
  4223. {
  4224. for (int i = numUsed; --i >= 0;)
  4225. if (! otherArray.contains (this->elements [i]))
  4226. remove (i);
  4227. }
  4228. }
  4229. lock.exit();
  4230. otherArray.unlockArray();
  4231. }
  4232. /** Swaps over two elements in the array.
  4233. This swaps over the elements found at the two indexes passed in.
  4234. If either index is out-of-range, this method will do nothing.
  4235. @param index1 index of one of the elements to swap
  4236. @param index2 index of the other element to swap
  4237. */
  4238. void swap (const int index1,
  4239. const int index2) throw()
  4240. {
  4241. lock.enter();
  4242. if (((unsigned int) index1) < (unsigned int) numUsed
  4243. && ((unsigned int) index2) < (unsigned int) numUsed)
  4244. {
  4245. swapVariables (this->elements [index1],
  4246. this->elements [index2]);
  4247. }
  4248. lock.exit();
  4249. }
  4250. /** Moves one of the values to a different position.
  4251. This will move the value to a specified index, shuffling along
  4252. any intervening elements as required.
  4253. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4254. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4255. @param currentIndex the index of the value to be moved. If this isn't a
  4256. valid index, then nothing will be done
  4257. @param newIndex the index at which you'd like this value to end up. If this
  4258. is less than zero, the value will be moved to the end
  4259. of the array
  4260. */
  4261. void move (const int currentIndex,
  4262. int newIndex) throw()
  4263. {
  4264. if (currentIndex != newIndex)
  4265. {
  4266. lock.enter();
  4267. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4268. {
  4269. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4270. newIndex = numUsed - 1;
  4271. const ElementType value = this->elements [currentIndex];
  4272. if (newIndex > currentIndex)
  4273. {
  4274. memmove (this->elements + currentIndex,
  4275. this->elements + currentIndex + 1,
  4276. (newIndex - currentIndex) * sizeof (ElementType));
  4277. }
  4278. else
  4279. {
  4280. memmove (this->elements + newIndex + 1,
  4281. this->elements + newIndex,
  4282. (currentIndex - newIndex) * sizeof (ElementType));
  4283. }
  4284. this->elements [newIndex] = value;
  4285. }
  4286. lock.exit();
  4287. }
  4288. }
  4289. /** Reduces the amount of storage being used by the array.
  4290. Arrays typically allocate slightly more storage than they need, and after
  4291. removing elements, they may have quite a lot of unused space allocated.
  4292. This method will reduce the amount of allocated storage to a minimum.
  4293. */
  4294. void minimiseStorageOverheads() throw()
  4295. {
  4296. lock.enter();
  4297. if (numUsed == 0)
  4298. {
  4299. this->setAllocatedSize (0);
  4300. }
  4301. else
  4302. {
  4303. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4304. if (newAllocation < this->numAllocated)
  4305. this->setAllocatedSize (newAllocation);
  4306. }
  4307. lock.exit();
  4308. }
  4309. /** Increases the array's internal storage to hold a minimum number of elements.
  4310. Calling this before adding a large known number of elements means that
  4311. the array won't have to keep dynamically resizing itself as the elements
  4312. are added, and it'll therefore be more efficient.
  4313. */
  4314. void ensureStorageAllocated (const int minNumElements) throw()
  4315. {
  4316. this->ensureAllocatedSize (minNumElements);
  4317. }
  4318. /** Sorts the elements in the array.
  4319. This will use a comparator object to sort the elements into order. The object
  4320. passed must have a method of the form:
  4321. @code
  4322. int compareElements (ElementType first, ElementType second);
  4323. @endcode
  4324. ..and this method must return:
  4325. - a value of < 0 if the first comes before the second
  4326. - a value of 0 if the two objects are equivalent
  4327. - a value of > 0 if the second comes before the first
  4328. To improve performance, the compareElements() method can be declared as static or const.
  4329. @param comparator the comparator to use for comparing elements.
  4330. @param retainOrderOfEquivalentItems if this is true, then items
  4331. which the comparator says are equivalent will be
  4332. kept in the order in which they currently appear
  4333. in the array. This is slower to perform, but may
  4334. be important in some cases. If it's false, a faster
  4335. algorithm is used, but equivalent elements may be
  4336. rearranged.
  4337. @see addSorted, indexOfSorted, sortArray
  4338. */
  4339. template <class ElementComparator>
  4340. void sort (ElementComparator& comparator,
  4341. const bool retainOrderOfEquivalentItems = false) const throw()
  4342. {
  4343. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4344. // avoids getting warning messages about the parameter being unused
  4345. lock.enter();
  4346. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4347. lock.exit();
  4348. }
  4349. /** Locks the array's CriticalSection.
  4350. Of course if the type of section used is a DummyCriticalSection, this won't
  4351. have any effect.
  4352. @see unlockArray
  4353. */
  4354. void lockArray() const throw()
  4355. {
  4356. lock.enter();
  4357. }
  4358. /** Unlocks the array's CriticalSection.
  4359. Of course if the type of section used is a DummyCriticalSection, this won't
  4360. have any effect.
  4361. @see lockArray
  4362. */
  4363. void unlockArray() const throw()
  4364. {
  4365. lock.exit();
  4366. }
  4367. juce_UseDebuggingNewOperator
  4368. private:
  4369. int numUsed;
  4370. TypeOfCriticalSectionToUse lock;
  4371. };
  4372. #endif // __JUCE_ARRAY_JUCEHEADER__
  4373. /********* End of inlined file: juce_Array.h *********/
  4374. /**
  4375. A typedef for an Array of void*'s.
  4376. VoidArrays are used in various places throughout the library instead of
  4377. more strongly-typed arrays, to keep code-size low.
  4378. */
  4379. typedef Array <void*> VoidArray;
  4380. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4381. /********* End of inlined file: juce_VoidArray.h *********/
  4382. #ifndef DOXYGEN
  4383. // (used in StringArray::appendNumbersToDuplicates)
  4384. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4385. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4386. #endif
  4387. /**
  4388. A special array for holding a list of strings.
  4389. @see String, StringPairArray
  4390. */
  4391. class JUCE_API StringArray
  4392. {
  4393. public:
  4394. /** Creates an empty string array */
  4395. StringArray() throw();
  4396. /** Creates a copy of another string array */
  4397. StringArray (const StringArray& other) throw();
  4398. /** Creates a copy of an array of string literals.
  4399. @param strings an array of strings to add. Null pointers in the array will be
  4400. treated as empty strings
  4401. @param numberOfStrings how many items there are in the array
  4402. */
  4403. StringArray (const juce_wchar** const strings,
  4404. const int numberOfStrings) throw();
  4405. /** Creates a copy of an array of string literals.
  4406. @param strings an array of strings to add. Null pointers in the array will be
  4407. treated as empty strings
  4408. @param numberOfStrings how many items there are in the array
  4409. */
  4410. StringArray (const char** const strings,
  4411. const int numberOfStrings) throw();
  4412. /** Creates a copy of a null-terminated array of string literals.
  4413. Each item from the array passed-in is added, until it encounters a null pointer,
  4414. at which point it stops.
  4415. */
  4416. StringArray (const juce_wchar** const strings) throw();
  4417. /** Creates a copy of a null-terminated array of string literals.
  4418. Each item from the array passed-in is added, until it encounters a null pointer,
  4419. at which point it stops.
  4420. */
  4421. StringArray (const char** const strings) throw();
  4422. /** Destructor. */
  4423. virtual ~StringArray() throw();
  4424. /** Copies the contents of another string array into this one */
  4425. const StringArray& operator= (const StringArray& other) throw();
  4426. /** Compares two arrays.
  4427. Comparisons are case-sensitive.
  4428. @returns true only if the other array contains exactly the same strings in the same order
  4429. */
  4430. bool operator== (const StringArray& other) const throw();
  4431. /** Compares two arrays.
  4432. Comparisons are case-sensitive.
  4433. @returns false if the other array contains exactly the same strings in the same order
  4434. */
  4435. bool operator!= (const StringArray& other) const throw();
  4436. /** Returns the number of strings in the array */
  4437. inline int size() const throw() { return strings.size(); };
  4438. /** Returns one of the strings from the array.
  4439. If the index is out-of-range, an empty string is returned.
  4440. Obviously the reference returned shouldn't be stored for later use, as the
  4441. string it refers to may disappear when the array changes.
  4442. */
  4443. const String& operator[] (const int index) const throw();
  4444. /** Searches for a string in the array.
  4445. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4446. @returns true if the string is found inside the array
  4447. */
  4448. bool contains (const String& stringToLookFor,
  4449. const bool ignoreCase = false) const throw();
  4450. /** Searches for a string in the array.
  4451. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4452. @param stringToLookFor the string to try to find
  4453. @param ignoreCase whether the comparison should be case-insensitive
  4454. @param startIndex the first index to start searching from
  4455. @returns the index of the first occurrence of the string in this array,
  4456. or -1 if it isn't found.
  4457. */
  4458. int indexOf (const String& stringToLookFor,
  4459. const bool ignoreCase = false,
  4460. int startIndex = 0) const throw();
  4461. /** Appends a string at the end of the array. */
  4462. void add (const String& stringToAdd) throw();
  4463. /** Inserts a string into the array.
  4464. This will insert a string into the array at the given index, moving
  4465. up the other elements to make room for it.
  4466. If the index is less than zero or greater than the size of the array,
  4467. the new string will be added to the end of the array.
  4468. */
  4469. void insert (const int index,
  4470. const String& stringToAdd) throw();
  4471. /** Adds a string to the array as long as it's not already in there.
  4472. The search can optionally be case-insensitive.
  4473. */
  4474. void addIfNotAlreadyThere (const String& stringToAdd,
  4475. const bool ignoreCase = false) throw();
  4476. /** Replaces one of the strings in the array with another one.
  4477. If the index is higher than the array's size, the new string will be
  4478. added to the end of the array; if it's less than zero nothing happens.
  4479. */
  4480. void set (const int index,
  4481. const String& newString) throw();
  4482. /** Appends some strings from another array to the end of this one.
  4483. @param other the array to add
  4484. @param startIndex the first element of the other array to add
  4485. @param numElementsToAdd the maximum number of elements to add (if this is
  4486. less than zero, they are all added)
  4487. */
  4488. void addArray (const StringArray& other,
  4489. int startIndex = 0,
  4490. int numElementsToAdd = -1) throw();
  4491. /** Breaks up a string into tokens and adds them to this array.
  4492. This will tokenise the given string using whitespace characters as the
  4493. token delimiters, and will add these tokens to the end of the array.
  4494. @returns the number of tokens added
  4495. */
  4496. int addTokens (const tchar* const stringToTokenise,
  4497. const bool preserveQuotedStrings) throw();
  4498. /** Breaks up a string into tokens and adds them to this array.
  4499. This will tokenise the given string (using the string passed in to define the
  4500. token delimiters), and will add these tokens to the end of the array.
  4501. @param stringToTokenise the string to tokenise
  4502. @param breakCharacters a string of characters, any of which will be considered
  4503. to be a token delimiter.
  4504. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4505. which are treated as quotes. Any text occurring
  4506. between quotes is not broken up into tokens.
  4507. @returns the number of tokens added
  4508. */
  4509. int addTokens (const tchar* const stringToTokenise,
  4510. const tchar* breakCharacters,
  4511. const tchar* quoteCharacters) throw();
  4512. /** Breaks up a string into lines and adds them to this array.
  4513. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4514. to the array. Line-break characters are omitted from the strings that are added to
  4515. the array.
  4516. */
  4517. int addLines (const tchar* stringToBreakUp) throw();
  4518. /** Removes all elements from the array. */
  4519. void clear() throw();
  4520. /** Removes a string from the array.
  4521. If the index is out-of-range, no action will be taken.
  4522. */
  4523. void remove (const int index) throw();
  4524. /** Finds a string in the array and removes it.
  4525. This will remove the first occurrence of the given string from the array. The
  4526. comparison may be case-insensitive depending on the ignoreCase parameter.
  4527. */
  4528. void removeString (const String& stringToRemove,
  4529. const bool ignoreCase = false) throw();
  4530. /** Removes any duplicated elements from the array.
  4531. If any string appears in the array more than once, only the first occurrence of
  4532. it will be retained.
  4533. @param ignoreCase whether to use a case-insensitive comparison
  4534. */
  4535. void removeDuplicates (const bool ignoreCase) throw();
  4536. /** Removes empty strings from the array.
  4537. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4538. characters will also be removed
  4539. */
  4540. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4541. /** Moves one of the strings to a different position.
  4542. This will move the string to a specified index, shuffling along
  4543. any intervening elements as required.
  4544. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4545. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4546. @param currentIndex the index of the value to be moved. If this isn't a
  4547. valid index, then nothing will be done
  4548. @param newIndex the index at which you'd like this value to end up. If this
  4549. is less than zero, the value will be moved to the end
  4550. of the array
  4551. */
  4552. void move (const int currentIndex, int newIndex) throw();
  4553. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4554. void trim() throw();
  4555. /** Adds numbers to the strings in the array, to make each string unique.
  4556. This will add numbers to the ends of groups of similar strings.
  4557. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4558. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4559. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4560. also has a number appended to it.
  4561. @param preNumberString when adding a number, this string is added before the number
  4562. @param postNumberString this string is appended after any numbers that are added
  4563. */
  4564. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4565. const bool appendNumberToFirstInstance,
  4566. const tchar* const preNumberString = defaultPreNumberString,
  4567. const tchar* const postNumberString = defaultPostNumberString) throw();
  4568. /** Joins the strings in the array together into one string.
  4569. This will join a range of elements from the array into a string, separating
  4570. them with a given string.
  4571. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4572. @param separatorString the string to insert between all the strings
  4573. @param startIndex the first element to join
  4574. @param numberOfElements how many elements to join together. If this is less
  4575. than zero, all available elements will be used.
  4576. */
  4577. const String joinIntoString (const String& separatorString,
  4578. int startIndex = 0,
  4579. int numberOfElements = -1) const throw();
  4580. /** Sorts the array into alphabetical order.
  4581. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4582. */
  4583. void sort (const bool ignoreCase) throw();
  4584. /** Reduces the amount of storage being used by the array.
  4585. Arrays typically allocate slightly more storage than they need, and after
  4586. removing elements, they may have quite a lot of unused space allocated.
  4587. This method will reduce the amount of allocated storage to a minimum.
  4588. */
  4589. void minimiseStorageOverheads() throw();
  4590. juce_UseDebuggingNewOperator
  4591. private:
  4592. VoidArray strings;
  4593. };
  4594. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4595. /********* End of inlined file: juce_StringArray.h *********/
  4596. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4597. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4598. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4599. /**
  4600. A class to hold a resizable block of raw data.
  4601. */
  4602. class JUCE_API MemoryBlock
  4603. {
  4604. public:
  4605. /** Create an uninitialised block with 0 size. */
  4606. MemoryBlock() throw();
  4607. /** Creates a memory block with a given initial size.
  4608. @param initialSize the size of block to create
  4609. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4610. */
  4611. MemoryBlock (const int initialSize,
  4612. const bool initialiseToZero = false) throw();
  4613. /** Creates a copy of another memory block. */
  4614. MemoryBlock (const MemoryBlock& other) throw();
  4615. /** Creates a memory block using a copy of a block of data.
  4616. @param dataToInitialiseFrom some data to copy into this block
  4617. @param sizeInBytes how much space to use
  4618. */
  4619. MemoryBlock (const void* const dataToInitialiseFrom,
  4620. const int sizeInBytes) throw();
  4621. /** Destructor. */
  4622. ~MemoryBlock() throw();
  4623. /** Copies another memory block onto this one.
  4624. This block will be resized and copied to exactly match the other one.
  4625. */
  4626. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4627. /** Compares two memory blocks.
  4628. @returns true only if the two blocks are the same size and have identical contents.
  4629. */
  4630. bool operator== (const MemoryBlock& other) const throw();
  4631. /** Compares two memory blocks.
  4632. @returns true if the two blocks are different sizes or have different contents.
  4633. */
  4634. bool operator!= (const MemoryBlock& other) const throw();
  4635. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4636. Note that the pointer returned will probably become invalid when the
  4637. block is resized.
  4638. */
  4639. template <class DataType>
  4640. operator DataType*() const throw() { return (DataType*) data; }
  4641. /** Returns a void pointer to the data.
  4642. Note that the pointer returned will probably become invalid when the
  4643. block is resized.
  4644. */
  4645. void* getData() const throw() { return data; }
  4646. /** Returns a byte from the memory block.
  4647. This returns a reference, so you can also use it to set a byte.
  4648. */
  4649. char& operator[] (const int offset) const throw() { return data [offset]; }
  4650. /** Returns the block's current allocated size, in bytes. */
  4651. int getSize() const throw() { return size; }
  4652. /** Resizes the memory block.
  4653. This will try to keep as much of the block's current content as it can,
  4654. and can optionally be made to clear any new space that gets allocated at
  4655. the end of the block.
  4656. @param newSize the new desired size for the block
  4657. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4658. whether to clear the new section or just leave it
  4659. uninitialised
  4660. @see ensureSize
  4661. */
  4662. void setSize (const int newSize,
  4663. const bool initialiseNewSpaceToZero = false) throw();
  4664. /** Increases the block's size only if it's smaller than a given size.
  4665. @param minimumSize if the block is already bigger than this size, no action
  4666. will be taken; otherwise it will be increased to this size
  4667. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4668. whether to clear the new section or just leave it
  4669. uninitialised
  4670. @see setSize
  4671. */
  4672. void ensureSize (const int minimumSize,
  4673. const bool initialiseNewSpaceToZero = false) throw();
  4674. /** Fills the entire memory block with a repeated byte value.
  4675. This is handy for clearing a block of memory to zero.
  4676. */
  4677. void fillWith (const uint8 valueToUse) throw();
  4678. /** Adds another block of data to the end of this one.
  4679. This block's size will be increased accordingly.
  4680. */
  4681. void append (const void* const data,
  4682. const int numBytes) throw();
  4683. /** Copies data into this MemoryBlock from a memory address.
  4684. @param srcData the memory location of the data to copy into this block
  4685. @param destinationOffset the offset in this block at which the data being copied should begin
  4686. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4687. it will be clipped so not to do anything nasty)
  4688. */
  4689. void copyFrom (const void* srcData,
  4690. int destinationOffset,
  4691. int numBytes) throw();
  4692. /** Copies data from this MemoryBlock to a memory address.
  4693. @param destData the memory location to write to
  4694. @param sourceOffset the offset within this block from which the copied data will be read
  4695. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4696. zeros will be used for that portion of the data)
  4697. */
  4698. void copyTo (void* destData,
  4699. int sourceOffset,
  4700. int numBytes) const throw();
  4701. /** Chops out a section of the block.
  4702. This will remove a section of the memory block and close the gap around it,
  4703. shifting any subsequent data downwards and reducing the size of the block.
  4704. If the range specified goes beyond the size of the block, it will be clipped.
  4705. */
  4706. void removeSection (int startByte, int numBytesToRemove) throw();
  4707. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4708. characters in the system's default encoding. */
  4709. const String toString() const throw();
  4710. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4711. The block will be resized to the number of valid bytes read from the string.
  4712. Non-hex characters in the string will be ignored.
  4713. @see String::toHexString()
  4714. */
  4715. void loadFromHexString (const String& sourceHexString) throw();
  4716. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4717. void setBitRange (int bitRangeStart,
  4718. int numBits,
  4719. int binaryNumberToApply) throw();
  4720. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4721. int getBitRange (int bitRangeStart,
  4722. int numBitsToRead) const throw();
  4723. /** Returns a string of characters that represent the binary contents of this block.
  4724. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4725. of simple non-extended characters, e.g. for storage in XML.
  4726. @see fromBase64Encoding
  4727. */
  4728. const String toBase64Encoding() const throw();
  4729. /** Takes a string of encoded characters and turns it into binary data.
  4730. The string passed in must have been created by to64BitEncoding(), and this
  4731. block will be resized to recreate the original data block.
  4732. @see toBase64Encoding
  4733. */
  4734. bool fromBase64Encoding (const String& encodedString) throw();
  4735. juce_UseDebuggingNewOperator
  4736. private:
  4737. char* data;
  4738. int size;
  4739. };
  4740. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4741. /********* End of inlined file: juce_MemoryBlock.h *********/
  4742. class FileInputStream;
  4743. class FileOutputStream;
  4744. /**
  4745. Represents a local file or directory.
  4746. This class encapsulates the absolute pathname of a file or directory, and
  4747. has methods for finding out about the file and changing its properties.
  4748. To read or write to the file, there are methods for returning an input or
  4749. output stream.
  4750. @see FileInputStream, FileOutputStream
  4751. */
  4752. class JUCE_API File
  4753. {
  4754. public:
  4755. /** Creates an (invalid) file object.
  4756. The file is initially set to an empty path, so getFullPath() will return
  4757. an empty string, and comparing the file to File::nonexistent will return
  4758. true.
  4759. You can use its operator= method to point it at a proper file.
  4760. */
  4761. File() throw() {}
  4762. /** Creates a file from an absolute path.
  4763. If the path supplied is a relative path, it is taken to be relative
  4764. to the current working directory (see File::getCurrentWorkingDirectory()),
  4765. but this isn't a recommended way of creating a file, because you
  4766. never know what the CWD is going to be.
  4767. On the Mac/Linux, the path can include "~" notation for referring to
  4768. user home directories.
  4769. */
  4770. File (const String& path) throw();
  4771. /** Creates a copy of another file object. */
  4772. File (const File& other) throw();
  4773. /** Destructor. */
  4774. ~File() throw() {}
  4775. /** Sets the file based on an absolute pathname.
  4776. If the path supplied is a relative path, it is taken to be relative
  4777. to the current working directory (see File::getCurrentWorkingDirectory()),
  4778. but this isn't a recommended way of creating a file, because you
  4779. never know what the CWD is going to be.
  4780. On the Mac/Linux, the path can include "~" notation for referring to
  4781. user home directories.
  4782. */
  4783. const File& operator= (const String& newFilePath) throw();
  4784. /** Copies from another file object. */
  4785. const File& operator= (const File& otherFile) throw();
  4786. /** This static constant is used for referring to an 'invalid' file. */
  4787. static const File nonexistent;
  4788. /** Checks whether the file actually exists.
  4789. @returns true if the file exists, either as a file or a directory.
  4790. @see existsAsFile, isDirectory
  4791. */
  4792. bool exists() const throw();
  4793. /** Checks whether the file exists and is a file rather than a directory.
  4794. @returns true only if this is a real file, false if it's a directory
  4795. or doesn't exist
  4796. @see exists, isDirectory
  4797. */
  4798. bool existsAsFile() const throw();
  4799. /** Checks whether the file is a directory that exists.
  4800. @returns true only if the file is a directory which actually exists, so
  4801. false if it's a file or doesn't exist at all
  4802. @see exists, existsAsFile
  4803. */
  4804. bool isDirectory() const throw();
  4805. /** Returns the size of the file in bytes.
  4806. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4807. */
  4808. int64 getSize() const throw();
  4809. /** Utility function to convert a file size in bytes to a neat string description.
  4810. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4811. 2000000 would produce "2 MB", etc.
  4812. */
  4813. static const String descriptionOfSizeInBytes (const int64 bytes);
  4814. /** Returns the complete, absolute path of this file.
  4815. This includes the filename and all its parent folders. On Windows it'll
  4816. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4817. path starting from the root folder.
  4818. If you just want the file's name, you should use getFileName() or
  4819. getFileNameWithoutExtension().
  4820. @see getFileName, getRelativePathFrom
  4821. */
  4822. const String& getFullPathName() const throw() { return fullPath; }
  4823. /** Returns the last section of the pathname.
  4824. Returns just the final part of the path - e.g. if the whole path
  4825. is "/moose/fish/foo.txt" this will return "foo.txt".
  4826. For a directory, it returns the final part of the path - e.g. for the
  4827. directory "/moose/fish" it'll return "fish".
  4828. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4829. "/moose/.fish", it'll return ".fish"
  4830. @see getFullPathName, getFileNameWithoutExtension
  4831. */
  4832. const String getFileName() const throw();
  4833. /** Creates a relative path that refers to a file relatively to a given directory.
  4834. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4835. would return "../../foo.txt".
  4836. If it's not possible to navigate from one file to the other, an absolute
  4837. path is returned. If the paths are invalid, an empty string may also be
  4838. returned.
  4839. @param directoryToBeRelativeTo the directory which the resultant string will
  4840. be relative to. If this is actually a file rather than
  4841. a directory, its parent directory will be used instead.
  4842. If it doesn't exist, it's assumed to be a directory.
  4843. @see getChildFile, isAbsolutePath
  4844. */
  4845. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4846. /** Returns the file's extension.
  4847. Returns the file extension of this file, also including the dot.
  4848. e.g. "/moose/fish/foo.txt" would return ".txt"
  4849. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4850. */
  4851. const String getFileExtension() const throw();
  4852. /** Checks whether the file has a given extension.
  4853. @param extensionToTest the extension to look for - it doesn't matter whether or
  4854. not this string has a dot at the start, so ".wav" and "wav"
  4855. will have the same effect. The comparison used is
  4856. case-insensitve.
  4857. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4858. */
  4859. bool hasFileExtension (const String& extensionToTest) const throw();
  4860. /** Returns a version of this file with a different file extension.
  4861. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4862. @param newExtension the new extension, either with or without a dot at the start (this
  4863. doesn't make any difference). To get remove a file's extension altogether,
  4864. pass an empty string into this function.
  4865. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4866. */
  4867. const File withFileExtension (const String& newExtension) const throw();
  4868. /** Returns the last part of the filename, without its file extension.
  4869. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4870. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4871. */
  4872. const String getFileNameWithoutExtension() const throw();
  4873. /** Returns a 32-bit hash-code that identifies this file.
  4874. This is based on the filename. Obviously it's possible, although unlikely, that
  4875. two files will have the same hash-code.
  4876. */
  4877. int hashCode() const throw();
  4878. /** Returns a 64-bit hash-code that identifies this file.
  4879. This is based on the filename. Obviously it's possible, although unlikely, that
  4880. two files will have the same hash-code.
  4881. */
  4882. int64 hashCode64() const throw();
  4883. /** Returns a file based on a relative path.
  4884. This will find a child file or directory of the current object.
  4885. e.g.
  4886. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4887. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4888. If the string is actually an absolute path, it will be treated as such, e.g.
  4889. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4890. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4891. */
  4892. const File getChildFile (String relativePath) const throw();
  4893. /** Returns a file which is in the same directory as this one.
  4894. This is equivalent to getParentDirectory().getChildFile (name).
  4895. @see getChildFile, getParentDirectory
  4896. */
  4897. const File getSiblingFile (const String& siblingFileName) const throw();
  4898. /** Returns the directory that contains this file or directory.
  4899. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4900. */
  4901. const File getParentDirectory() const throw();
  4902. /** Checks whether a file is somewhere inside a directory.
  4903. Returns true if this file is somewhere inside a subdirectory of the directory
  4904. that is passed in. Neither file actually has to exist, because the function
  4905. just checks the paths for similarities.
  4906. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4907. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4908. */
  4909. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4910. /** Chooses a filename relative to this one that doesn't already exist.
  4911. If this file is a directory, this will return a child file of this
  4912. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4913. it finds one that isn't already there.
  4914. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4915. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4916. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4917. @param prefix the string to use for the filename before the number
  4918. @param suffix the string to add to the filename after the number
  4919. @param putNumbersInBrackets if true, this will create filenames in the
  4920. format "prefix(number)suffix", if false, it will leave the
  4921. brackets out.
  4922. */
  4923. const File getNonexistentChildFile (const String& prefix,
  4924. const String& suffix,
  4925. bool putNumbersInBrackets = true) const throw();
  4926. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4927. If this file doesn't exist, this will just return itself, otherwise it
  4928. will return an appropriate sibling that doesn't exist, e.g. if a file
  4929. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4930. @param putNumbersInBrackets whether to add brackets around the numbers that
  4931. get appended to the new filename.
  4932. */
  4933. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4934. /** Compares the pathnames for two files. */
  4935. bool operator== (const File& otherFile) const throw();
  4936. /** Compares the pathnames for two files. */
  4937. bool operator!= (const File& otherFile) const throw();
  4938. /** Checks whether a file can be created or written to.
  4939. @returns true if it's possible to create and write to this file. If the file
  4940. doesn't already exist, this will check its parent directory to
  4941. see if writing is allowed.
  4942. @see setReadOnly
  4943. */
  4944. bool hasWriteAccess() const throw();
  4945. /** Changes the write-permission of a file or directory.
  4946. @param shouldBeReadOnly whether to add or remove write-permission
  4947. @param applyRecursively if the file is a directory and this is true, it will
  4948. recurse through all the subfolders changing the permissions
  4949. of all files
  4950. @returns true if it manages to change the file's permissions.
  4951. @see hasWriteAccess
  4952. */
  4953. bool setReadOnly (const bool shouldBeReadOnly,
  4954. const bool applyRecursively = false) const throw();
  4955. /** Returns true if this file is a hidden or system file.
  4956. The criteria for deciding whether a file is hidden are platform-dependent.
  4957. */
  4958. bool isHidden() const throw();
  4959. /** If this file is a link, this returns the file that it points to.
  4960. If this file isn't actually link, it'll just return itself.
  4961. */
  4962. const File getLinkedTarget() const throw();
  4963. /** Returns the last modification time of this file.
  4964. @returns the time, or an invalid time if the file doesn't exist.
  4965. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4966. */
  4967. const Time getLastModificationTime() const throw();
  4968. /** Returns the last time this file was accessed.
  4969. @returns the time, or an invalid time if the file doesn't exist.
  4970. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4971. */
  4972. const Time getLastAccessTime() const throw();
  4973. /** Returns the time that this file was created.
  4974. @returns the time, or an invalid time if the file doesn't exist.
  4975. @see getLastModificationTime, getLastAccessTime
  4976. */
  4977. const Time getCreationTime() const throw();
  4978. /** Changes the modification time for this file.
  4979. @param newTime the time to apply to the file
  4980. @returns true if it manages to change the file's time.
  4981. @see getLastModificationTime, setLastAccessTime, setCreationTime
  4982. */
  4983. bool setLastModificationTime (const Time& newTime) const throw();
  4984. /** Changes the last-access time for this file.
  4985. @param newTime the time to apply to the file
  4986. @returns true if it manages to change the file's time.
  4987. @see getLastAccessTime, setLastModificationTime, setCreationTime
  4988. */
  4989. bool setLastAccessTime (const Time& newTime) const throw();
  4990. /** Changes the creation date for this file.
  4991. @param newTime the time to apply to the file
  4992. @returns true if it manages to change the file's time.
  4993. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4994. */
  4995. bool setCreationTime (const Time& newTime) const throw();
  4996. /** If possible, this will try to create a version string for the given file.
  4997. The OS may be able to look at the file and give a version for it - e.g. with
  4998. executables, bundles, dlls, etc. If no version is available, this will
  4999. return an empty string.
  5000. */
  5001. const String getVersion() const throw();
  5002. /** Creates an empty file if it doesn't already exist.
  5003. If the file that this object refers to doesn't exist, this will create a file
  5004. of zero size.
  5005. If it already exists or is a directory, this method will do nothing.
  5006. @returns true if the file has been created (or if it already existed).
  5007. @see createDirectory
  5008. */
  5009. bool create() const throw();
  5010. /** Creates a new directory for this filename.
  5011. This will try to create the file as a directory, and fill also create
  5012. any parent directories it needs in order to complete the operation.
  5013. @returns true if the directory has been created successfully, (or if it
  5014. already existed beforehand).
  5015. @see create
  5016. */
  5017. bool createDirectory() const throw();
  5018. /** Deletes a file.
  5019. If this file is actually a directory, it may not be deleted correctly if it
  5020. contains files. See deleteRecursively() as a better way of deleting directories.
  5021. @returns true if the file has been successfully deleted (or if it didn't exist to
  5022. begin with).
  5023. @see deleteRecursively
  5024. */
  5025. bool deleteFile() const throw();
  5026. /** Deletes a file or directory and all its subdirectories.
  5027. If this file is a directory, this will try to delete it and all its subfolders. If
  5028. it's just a file, it will just try to delete the file.
  5029. @returns true if the file and all its subfolders have been successfully deleted
  5030. (or if it didn't exist to begin with).
  5031. @see deleteFile
  5032. */
  5033. bool deleteRecursively() const throw();
  5034. /** Moves this file or folder to the trash.
  5035. @returns true if the operation succeeded. It could fail if the trash is full, or
  5036. if the file is write-protected, so you should check the return value
  5037. and act appropriately.
  5038. */
  5039. bool moveToTrash() const throw();
  5040. /** Moves or renames a file.
  5041. Tries to move a file to a different location.
  5042. If the target file already exists, this will attempt to delete it first, and
  5043. will fail if this can't be done.
  5044. Note that the destination file isn't the directory to put it in, it's the actual
  5045. filename that you want the new file to have.
  5046. @returns true if the operation succeeds
  5047. */
  5048. bool moveFileTo (const File& targetLocation) const throw();
  5049. /** Copies a file.
  5050. Tries to copy a file to a different location.
  5051. If the target file already exists, this will attempt to delete it first, and
  5052. will fail if this can't be done.
  5053. @returns true if the operation succeeds
  5054. */
  5055. bool copyFileTo (const File& targetLocation) const throw();
  5056. /** Copies a directory.
  5057. Tries to copy an entire directory, recursively.
  5058. If this file isn't a directory or if any target files can't be created, this
  5059. will return false.
  5060. @param newDirectory the directory that this one should be copied to. Note that this
  5061. is the name of the actual directory to create, not the directory
  5062. into which the new one should be placed, so there must be enough
  5063. write privileges to create it if it doesn't exist. Any files inside
  5064. it will be overwritten by similarly named ones that are copied.
  5065. */
  5066. bool copyDirectoryTo (const File& newDirectory) const throw();
  5067. /** Used in file searching, to specify whether to return files, directories, or both.
  5068. */
  5069. enum TypesOfFileToFind
  5070. {
  5071. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5072. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5073. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5074. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5075. };
  5076. /** Searches inside a directory for files matching a wildcard pattern.
  5077. Assuming that this file is a directory, this method will search it
  5078. for either files or subdirectories whose names match a filename pattern.
  5079. @param results an array to which File objects will be added for the
  5080. files that the search comes up with
  5081. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5082. return files, directories, or both. If the ignoreHiddenFiles flag
  5083. is also added to this value, hidden files won't be returned
  5084. @param searchRecursively if true, all subdirectories will be recursed into to do
  5085. an exhaustive search
  5086. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5087. @returns the number of results that have been found
  5088. @see getNumberOfChildFiles, DirectoryIterator
  5089. */
  5090. int findChildFiles (OwnedArray<File>& results,
  5091. const int whatToLookFor,
  5092. const bool searchRecursively,
  5093. const String& wildCardPattern = JUCE_T("*")) const throw();
  5094. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5095. Assuming that this file is a directory, this method will search it
  5096. for either files or subdirectories whose names match a filename pattern,
  5097. and will return the number of matches found.
  5098. This isn't a recursive call, and will only search this directory, not
  5099. its children.
  5100. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5101. count files, directories, or both. If the ignoreHiddenFiles flag
  5102. is also added to this value, hidden files won't be counted
  5103. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5104. @returns the number of matches found
  5105. @see findChildFiles, DirectoryIterator
  5106. */
  5107. int getNumberOfChildFiles (const int whatToLookFor,
  5108. const String& wildCardPattern = JUCE_T("*")) const throw();
  5109. /** Returns true if this file is a directory that contains one or more subdirectories.
  5110. @see isDirectory, findChildFiles
  5111. */
  5112. bool containsSubDirectories() const throw();
  5113. /** Creates a stream to read from this file.
  5114. @returns a stream that will read from this file (initially positioned at the
  5115. start of the file), or 0 if the file can't be opened for some reason
  5116. @see createOutputStream, loadFileAsData
  5117. */
  5118. FileInputStream* createInputStream() const throw();
  5119. /** Creates a stream to write to this file.
  5120. If the file exists, the stream that is returned will be positioned ready for
  5121. writing at the end of the file, so you might want to use deleteFile() first
  5122. to write to an empty file.
  5123. @returns a stream that will write to this file (initially positioned at the
  5124. end of the file), or 0 if the file can't be opened for some reason
  5125. @see createInputStream, printf, appendData, appendText
  5126. */
  5127. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5128. /** Loads a file's contents into memory as a block of binary data.
  5129. Of course, trying to load a very large file into memory will blow up, so
  5130. it's better to check first.
  5131. @param result the data block to which the file's contents should be appended - note
  5132. that if the memory block might already contain some data, you
  5133. might want to clear it first
  5134. @returns true if the file could all be read into memory
  5135. */
  5136. bool loadFileAsData (MemoryBlock& result) const throw();
  5137. /** Reads a file into memory as a string.
  5138. Attempts to load the entire file as a zero-terminated string.
  5139. This makes use of InputStream::readEntireStreamAsString, which should
  5140. automatically cope with unicode/acsii file formats.
  5141. */
  5142. const String loadFileAsString() const throw();
  5143. /** Writes text to the end of the file.
  5144. This will try to do a printf to the file.
  5145. @returns false if it can't write to the file for some reason
  5146. */
  5147. bool printf (const tchar* format, ...) const throw();
  5148. /** Appends a block of binary data to the end of the file.
  5149. This will try to write the given buffer to the end of the file.
  5150. @returns false if it can't write to the file for some reason
  5151. */
  5152. bool appendData (const void* const dataToAppend,
  5153. const int numberOfBytes) const throw();
  5154. /** Replaces this file's contents with a given block of data.
  5155. This will delete the file and replace it with the given data.
  5156. A nice feature of this method is that it's safe - instead of deleting
  5157. the file first and then re-writing it, it creates a new temporary file,
  5158. writes the data to that, and then moves the new file to replace the existing
  5159. file. This means that if the power gets pulled out or something crashes,
  5160. you're a lot less likely to end up with an empty file..
  5161. Returns true if the operation succeeds, or false if it fails.
  5162. @see appendText
  5163. */
  5164. bool replaceWithData (const void* const dataToWrite,
  5165. const int numberOfBytes) const throw();
  5166. /** Appends a string to the end of the file.
  5167. This will try to append a text string to the file, as either 16-bit unicode
  5168. or 8-bit characters in the default system encoding.
  5169. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5170. the endianness of the file.
  5171. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5172. @see replaceWithText
  5173. */
  5174. bool appendText (const String& textToAppend,
  5175. const bool asUnicode = false,
  5176. const bool writeUnicodeHeaderBytes = false) const throw();
  5177. /** Replaces this file's contents with a given text string.
  5178. This will delete the file and replace it with the given text.
  5179. A nice feature of this method is that it's safe - instead of deleting
  5180. the file first and then re-writing it, it creates a new temporary file,
  5181. writes the text to that, and then moves the new file to replace the existing
  5182. file. This means that if the power gets pulled out or something crashes,
  5183. you're a lot less likely to end up with an empty file..
  5184. For an explanation of the parameters here, see the appendText() method.
  5185. Returns true if the operation succeeds, or false if it fails.
  5186. @see appendText
  5187. */
  5188. bool replaceWithText (const String& textToWrite,
  5189. const bool asUnicode = false,
  5190. const bool writeUnicodeHeaderBytes = false) const throw();
  5191. /** Creates a set of files to represent each file root.
  5192. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5193. to which ones are available. On the Mac/Linux, this will probably
  5194. just add a single entry for "/".
  5195. */
  5196. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5197. /** Finds the name of the drive on which this file lives.
  5198. @returns the volume label of the drive, or an empty string if this isn't possible
  5199. */
  5200. const String getVolumeLabel() const throw();
  5201. /** Returns the serial number of the volume on which this file lives.
  5202. @returns the serial number, or zero if there's a problem doing this
  5203. */
  5204. int getVolumeSerialNumber() const throw();
  5205. /** Returns the number of bytes free on the drive that this file lives on.
  5206. @returns the number of bytes free, or 0 if there's a problem finding this out
  5207. @see getVolumeTotalSize
  5208. */
  5209. int64 getBytesFreeOnVolume() const throw();
  5210. /** Returns the total size of the drive that contains this file.
  5211. @returns the total number of bytes that the volume can hold
  5212. @see getBytesFreeOnVolume
  5213. */
  5214. int64 getVolumeTotalSize() const throw();
  5215. /** Returns true if this file is on a CD or DVD drive. */
  5216. bool isOnCDRomDrive() const throw();
  5217. /** Returns true if this file is on a hard disk.
  5218. This will fail if it's a network drive, but will still be true for
  5219. removable hard-disks.
  5220. */
  5221. bool isOnHardDisk() const throw();
  5222. /** Returns true if this file is on a removable disk drive.
  5223. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5224. */
  5225. bool isOnRemovableDrive() const throw();
  5226. /** Launches the file as a process.
  5227. - if the file is executable, this will run it.
  5228. - if it's a document of some kind, it will launch the document with its
  5229. default viewer application.
  5230. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5231. */
  5232. bool startAsProcess (const String& parameters = String::empty) const throw();
  5233. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5234. */
  5235. enum SpecialLocationType
  5236. {
  5237. /** The user's home folder. This is the same as using File ("~"). */
  5238. userHomeDirectory,
  5239. /** The user's default documents folder. On Windows, this might be the user's
  5240. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5241. doesn't tend to have one of these, so it might just return their home folder.
  5242. */
  5243. userDocumentsDirectory,
  5244. /** The folder that contains the user's desktop objects. */
  5245. userDesktopDirectory,
  5246. /** The folder in which applications store their persistent user-specific settings.
  5247. On Windows, this might be "\Documents and Settings\username\Application Data".
  5248. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5249. always create your own sub-folder to put them in, to avoid making a mess.
  5250. */
  5251. userApplicationDataDirectory,
  5252. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5253. of the computer, rather than just the current user.
  5254. On the Mac it'll be "/Library", on Windows, it could be something like
  5255. "\Documents and Settings\All Users\Application Data".
  5256. Depending on the setup, this folder may be read-only.
  5257. */
  5258. commonApplicationDataDirectory,
  5259. /** The folder that should be used for temporary files.
  5260. Always delete them when you're finished, to keep the user's computer tidy!
  5261. */
  5262. tempDirectory,
  5263. /** Returns this application's executable file.
  5264. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5265. host app.
  5266. On the mac this will return the unix binary, not the package folder - see
  5267. currentApplicationFile for that.
  5268. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  5269. file link, invokedExecutableFile will return the name of the link.
  5270. */
  5271. currentExecutableFile,
  5272. /** Returns this application's location.
  5273. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5274. host app.
  5275. On the mac this will return the package folder (if it's in one), not the unix binary
  5276. that's inside it - compare with currentExecutableFile.
  5277. */
  5278. currentApplicationFile,
  5279. /** Returns the file that was invoked to launch this executable.
  5280. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  5281. will return the name of the link that was used, whereas currentExecutableFile will return
  5282. the actual location of the target executable.
  5283. */
  5284. invokedExecutableFile,
  5285. /** The directory in which applications normally get installed.
  5286. So on windows, this would be something like "c:\program files", on the
  5287. Mac "/Applications", or "/usr" on linux.
  5288. */
  5289. globalApplicationsDirectory,
  5290. /** The most likely place where a user might store their music files.
  5291. */
  5292. userMusicDirectory,
  5293. /** The most likely place where a user might store their movie files.
  5294. */
  5295. userMoviesDirectory,
  5296. };
  5297. /** Finds the location of a special type of file or directory, such as a home folder or
  5298. documents folder.
  5299. @see SpecialLocationType
  5300. */
  5301. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5302. /** Returns a temporary file in the system's temp directory.
  5303. This will try to return the name of a non-existent temp file.
  5304. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5305. */
  5306. static const File createTempFile (const String& fileNameEnding) throw();
  5307. /** Returns the current working directory.
  5308. @see setAsCurrentWorkingDirectory
  5309. */
  5310. static const File getCurrentWorkingDirectory() throw();
  5311. /** Sets the current working directory to be this file.
  5312. For this to work the file must point to a valid directory.
  5313. @returns true if the current directory has been changed.
  5314. @see getCurrentWorkingDirectory
  5315. */
  5316. bool setAsCurrentWorkingDirectory() const throw();
  5317. /** The system-specific file separator character.
  5318. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5319. */
  5320. static const tchar separator;
  5321. /** The system-specific file separator character, as a string.
  5322. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5323. */
  5324. static const tchar* separatorString;
  5325. /** Removes illegal characters from a filename.
  5326. This will return a copy of the given string after removing characters
  5327. that are not allowed in a legal filename, and possibly shortening the
  5328. string if it's too long.
  5329. Because this will remove slashes, don't use it on an absolute pathname.
  5330. @see createLegalPathName
  5331. */
  5332. static const String createLegalFileName (const String& fileNameToFix) throw();
  5333. /** Removes illegal characters from a pathname.
  5334. Similar to createLegalFileName(), but this won't remove slashes, so can
  5335. be used on a complete pathname.
  5336. @see createLegalFileName
  5337. */
  5338. static const String createLegalPathName (const String& pathNameToFix) throw();
  5339. /** Indicates whether filenames are case-sensitive on the current operating system.
  5340. */
  5341. static bool areFileNamesCaseSensitive();
  5342. /** Returns true if the string seems to be a fully-specified absolute path.
  5343. */
  5344. static bool isAbsolutePath (const String& path) throw();
  5345. juce_UseDebuggingNewOperator
  5346. private:
  5347. String fullPath;
  5348. // internal way of contructing a file without checking the path
  5349. friend class DirectoryIterator;
  5350. File (const String&, int) throw();
  5351. const String getPathUpToLastSlash() const throw();
  5352. };
  5353. #endif // __JUCE_FILE_JUCEHEADER__
  5354. /********* End of inlined file: juce_File.h *********/
  5355. /**
  5356. A simple implemenation of a Logger that writes to a file.
  5357. @see Logger
  5358. */
  5359. class JUCE_API FileLogger : public Logger
  5360. {
  5361. public:
  5362. /** Creates a FileLogger for a given file.
  5363. @param fileToWriteTo the file that to use - new messages will be appended
  5364. to the file. If the file doesn't exist, it will be created,
  5365. along with any parent directories that are needed.
  5366. @param welcomeMessage when opened, the logger will write a header to the log, along
  5367. with the current date and time, and this welcome message
  5368. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5369. but is larger than this number of bytes, then the start of the
  5370. file will be truncated to keep the size down. This prevents a log
  5371. file getting ridiculously large over time. The file will be truncated
  5372. at a new-line boundary. If this value is less than zero, no size limit
  5373. will be imposed; if it's zero, the file will always be deleted. Note that
  5374. the size is only checked once when this object is created - any logging
  5375. that is done later will be appended without any checking
  5376. */
  5377. FileLogger (const File& fileToWriteTo,
  5378. const String& welcomeMessage,
  5379. const int maxInitialFileSizeBytes = 128 * 1024);
  5380. /** Destructor. */
  5381. ~FileLogger();
  5382. void logMessage (const String& message);
  5383. /** Helper function to create a log file in the correct place for this platform.
  5384. On Windows this will return a logger with a path such as:
  5385. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5386. On the Mac it'll create something like:
  5387. ~/Library/Logs/[logFileName]
  5388. The method might return 0 if the file can't be created for some reason.
  5389. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5390. it's best to use the something like the name of your application here.
  5391. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5392. call it "log.txt" because if it goes in a directory with logs
  5393. from other applications (as it will do on the Mac) then no-one
  5394. will know which one is yours!
  5395. @param welcomeMessage a message that will be written to the log when it's opened.
  5396. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5397. */
  5398. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5399. const String& logFileName,
  5400. const String& welcomeMessage,
  5401. const int maxInitialFileSizeBytes = 128 * 1024);
  5402. juce_UseDebuggingNewOperator
  5403. private:
  5404. File logFile;
  5405. CriticalSection logLock;
  5406. FileOutputStream* logStream;
  5407. void trimFileSize (int maxFileSizeBytes) const;
  5408. FileLogger (const FileLogger&);
  5409. const FileLogger& operator= (const FileLogger&);
  5410. };
  5411. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5412. /********* End of inlined file: juce_FileLogger.h *********/
  5413. #endif
  5414. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5415. /********* Start of inlined file: juce_Initialisation.h *********/
  5416. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5417. #define __JUCE_INITIALISATION_JUCEHEADER__
  5418. /** Initialises Juce's GUI classes.
  5419. If you're embedding Juce into an application that uses its own event-loop rather
  5420. than using the START_JUCE_APPLICATION macro, call this function before making any
  5421. Juce calls, to make sure things are initialised correctly.
  5422. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5423. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5424. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5425. */
  5426. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5427. /** Clears up any static data being used by Juce's GUI classes.
  5428. If you're embedding Juce into an application that uses its own event-loop rather
  5429. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5430. code to clean up any juce objects that might be lying around.
  5431. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5432. */
  5433. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5434. /** Initialises the core parts of Juce.
  5435. If you're embedding Juce into either a command-line program, call this function
  5436. at the start of your main() function to make sure that Juce is initialised correctly.
  5437. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5438. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5439. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5440. */
  5441. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5442. /** Clears up any static data being used by Juce's non-gui core classes.
  5443. If you're embedding Juce into either a command-line program, call this function
  5444. at the end of your main() function if you want to make sure any Juce objects are
  5445. cleaned up correctly.
  5446. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5447. */
  5448. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5449. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5450. /********* End of inlined file: juce_Initialisation.h *********/
  5451. #endif
  5452. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5453. #endif
  5454. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5455. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  5456. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5457. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5458. /**
  5459. A collection of miscellaneous platform-specific utilities.
  5460. */
  5461. class JUCE_API PlatformUtilities
  5462. {
  5463. public:
  5464. /** Plays the operating system's default alert 'beep' sound. */
  5465. static void beep();
  5466. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  5467. const String& emailSubject,
  5468. const String& bodyText,
  5469. const StringArray& filesToAttach);
  5470. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  5471. /** MAC ONLY - Turns a Core CF String into a juce one. */
  5472. static const String cfStringToJuceString (CFStringRef cfString);
  5473. /** MAC ONLY - Turns a juce string into a Core CF one. */
  5474. static CFStringRef juceStringToCFString (const String& s);
  5475. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  5476. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  5477. /** MAC ONLY - Turns an FSRef into a juce string path. */
  5478. static const String makePathFromFSRef (FSRef* file);
  5479. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  5480. their precomposed equivalents.
  5481. */
  5482. static const String convertToPrecomposedUnicode (const String& s);
  5483. /** MAC ONLY - Gets the type of a file from the file's resources. */
  5484. static OSType getTypeOfFile (const String& filename);
  5485. /** MAC ONLY - Returns true if this file is actually a bundle. */
  5486. static bool isBundle (const String& filename);
  5487. /** MAC ONLY - Adds an item to the dock */
  5488. static void addItemToDock (const File& file);
  5489. /** MAC ONLY - Returns the current OS version number.
  5490. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  5491. */
  5492. static int getOSXMinorVersionNumber() throw();
  5493. #endif
  5494. #if JUCE_WINDOWS || DOXYGEN
  5495. // Some registry helper functions:
  5496. /** WIN32 ONLY - Returns a string from the registry.
  5497. The path is a string for the entire path of a value in the registry,
  5498. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  5499. */
  5500. static const String getRegistryValue (const String& regValuePath,
  5501. const String& defaultValue = String::empty);
  5502. /** WIN32 ONLY - Sets a registry value as a string.
  5503. This will take care of creating any groups needed to get to the given
  5504. registry value.
  5505. */
  5506. static void setRegistryValue (const String& regValuePath,
  5507. const String& value);
  5508. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  5509. static bool registryValueExists (const String& regValuePath);
  5510. /** WIN32 ONLY - Deletes a registry value. */
  5511. static void deleteRegistryValue (const String& regValuePath);
  5512. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  5513. static void deleteRegistryKey (const String& regKeyPath);
  5514. /** WIN32 ONLY - Creates a file association in the registry.
  5515. This lets you set the exe that should be launched by a given file extension.
  5516. @param fileExtension the file extension to associate, including the
  5517. initial dot, e.g. ".txt"
  5518. @param symbolicDescription a space-free short token to identify the file type
  5519. @param fullDescription a human-readable description of the file type
  5520. @param targetExecutable the executable that should be launched
  5521. @param iconResourceNumber the icon that gets displayed for the file type will be
  5522. found by looking up this resource number in the
  5523. executable. Pass 0 here to not use an icon
  5524. */
  5525. static void registerFileAssociation (const String& fileExtension,
  5526. const String& symbolicDescription,
  5527. const String& fullDescription,
  5528. const File& targetExecutable,
  5529. int iconResourceNumber);
  5530. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  5531. In a normal Juce application this will be set to the module handle
  5532. of the application executable.
  5533. If you're writing a DLL using Juce and plan to use any Juce messaging or
  5534. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  5535. to set the correct module handle in your DllMain() function, because
  5536. the win32 system relies on the correct instance handle when opening windows.
  5537. */
  5538. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  5539. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  5540. @see getCurrentModuleInstanceHandle()
  5541. */
  5542. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  5543. /** WIN32 ONLY - Gets the command-line params as a string.
  5544. This is needed to avoid unicode problems with the argc type params.
  5545. */
  5546. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  5547. #endif
  5548. /** Clears the floating point unit's flags.
  5549. Only has an effect under win32, currently.
  5550. */
  5551. static void fpuReset();
  5552. #if JUCE_LINUX || JUCE_WINDOWS
  5553. /** Loads a dynamically-linked library into the process's address space.
  5554. @param pathOrFilename the platform-dependent name and search path
  5555. @returns a handle which can be used by getProcedureEntryPoint(), or
  5556. zero if it fails.
  5557. @see freeDynamicLibrary, getProcedureEntryPoint
  5558. */
  5559. static void* loadDynamicLibrary (const String& pathOrFilename);
  5560. /** Frees a dynamically-linked library.
  5561. @param libraryHandle a handle created by loadDynamicLibrary
  5562. @see loadDynamicLibrary, getProcedureEntryPoint
  5563. */
  5564. static void freeDynamicLibrary (void* libraryHandle);
  5565. /** Finds a procedure call in a dynamically-linked library.
  5566. @param libraryHandle a library handle returned by loadDynamicLibrary
  5567. @param procedureName the name of the procedure call to try to load
  5568. @returns a pointer to the function if found, or 0 if it fails
  5569. @see loadDynamicLibrary
  5570. */
  5571. static void* getProcedureEntryPoint (void* libraryHandle,
  5572. const String& procedureName);
  5573. #endif
  5574. #if JUCE_LINUX || DOXYGEN
  5575. #endif
  5576. };
  5577. #if JUCE_MAC || JUCE_IPHONE
  5578. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  5579. using RAII.
  5580. */
  5581. class ScopedAutoReleasePool
  5582. {
  5583. public:
  5584. ScopedAutoReleasePool();
  5585. ~ScopedAutoReleasePool();
  5586. private:
  5587. void* pool;
  5588. };
  5589. #endif
  5590. #if JUCE_MAC
  5591. /**
  5592. A wrapper class for picking up events from an Apple IR remote control device.
  5593. To use it, just create a subclass of this class, implementing the buttonPressed()
  5594. callback, then call start() and stop() to start or stop receiving events.
  5595. */
  5596. class JUCE_API AppleRemoteDevice
  5597. {
  5598. public:
  5599. AppleRemoteDevice();
  5600. virtual ~AppleRemoteDevice();
  5601. /** The set of buttons that may be pressed.
  5602. @see buttonPressed
  5603. */
  5604. enum ButtonType
  5605. {
  5606. menuButton = 0, /**< The menu button (if it's held for a short time). */
  5607. playButton, /**< The play button. */
  5608. plusButton, /**< The plus or volume-up button. */
  5609. minusButton, /**< The minus or volume-down button. */
  5610. rightButton, /**< The right button (if it's held for a short time). */
  5611. leftButton, /**< The left button (if it's held for a short time). */
  5612. rightButton_Long, /**< The right button (if it's held for a long time). */
  5613. leftButton_Long, /**< The menu button (if it's held for a long time). */
  5614. menuButton_Long, /**< The menu button (if it's held for a long time). */
  5615. playButtonSleepMode,
  5616. switched
  5617. };
  5618. /** Override this method to receive the callback about a button press.
  5619. The callback will happen on the application's message thread.
  5620. Some buttons trigger matching up and down events, in which the isDown parameter
  5621. will be true and then false. Others only send a single event when the
  5622. button is pressed.
  5623. */
  5624. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  5625. /** Starts the device running and responding to events.
  5626. Returns true if it managed to open the device.
  5627. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  5628. and will not be available to any other part of the system. If
  5629. false, it will be shared with other apps.
  5630. @see stop
  5631. */
  5632. bool start (const bool inExclusiveMode) throw();
  5633. /** Stops the device running.
  5634. @see start
  5635. */
  5636. void stop() throw();
  5637. /** Returns true if the device has been started successfully.
  5638. */
  5639. bool isActive() const throw();
  5640. /** Returns the ID number of the remote, if it has sent one.
  5641. */
  5642. int getRemoteId() const throw() { return remoteId; }
  5643. juce_UseDebuggingNewOperator
  5644. /** @internal */
  5645. void handleCallbackInternal();
  5646. private:
  5647. void* device;
  5648. void* queue;
  5649. int remoteId;
  5650. bool open (const bool openInExclusiveMode) throw();
  5651. };
  5652. #endif
  5653. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5654. /********* End of inlined file: juce_PlatformUtilities.h *********/
  5655. #endif
  5656. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5657. #endif
  5658. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5659. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  5660. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5661. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5662. /** A timer for measuring performance of code and dumping the results to a file.
  5663. e.g. @code
  5664. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  5665. for (;;)
  5666. {
  5667. pc.start();
  5668. doSomethingFishy();
  5669. pc.stop();
  5670. }
  5671. @endcode
  5672. In this example, the time of each period between calling start/stop will be
  5673. measured and averaged over 50 runs, and the results printed to a file
  5674. every 50 times round the loop.
  5675. */
  5676. class JUCE_API PerformanceCounter
  5677. {
  5678. public:
  5679. /** Creates a PerformanceCounter object.
  5680. @param counterName the name used when printing out the statistics
  5681. @param runsPerPrintout the number of start/stop iterations before calling
  5682. printStatistics()
  5683. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  5684. the results are just written to the debugger output
  5685. */
  5686. PerformanceCounter (const String& counterName,
  5687. int runsPerPrintout = 100,
  5688. const File& loggingFile = File::nonexistent);
  5689. /** Destructor. */
  5690. ~PerformanceCounter();
  5691. /** Starts timing.
  5692. @see stop
  5693. */
  5694. void start();
  5695. /** Stops timing and prints out the results.
  5696. The number of iterations before doing a printout of the
  5697. results is set in the constructor.
  5698. @see start
  5699. */
  5700. void stop();
  5701. /** Dumps the current metrics to the debugger output and to a file.
  5702. As well as using Logger::outputDebugString to print the results,
  5703. this will write then to the file specified in the constructor (if
  5704. this was valid).
  5705. */
  5706. void printStatistics();
  5707. juce_UseDebuggingNewOperator
  5708. private:
  5709. String name;
  5710. int numRuns, runsPerPrint;
  5711. double totalTime;
  5712. int64 started;
  5713. File outputFile;
  5714. };
  5715. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5716. /********* End of inlined file: juce_PerformanceCounter.h *********/
  5717. #endif
  5718. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5719. #endif
  5720. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5721. /********* Start of inlined file: juce_Singleton.h *********/
  5722. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5723. #define __JUCE_SINGLETON_JUCEHEADER__
  5724. /********* Start of inlined file: juce_ScopedLock.h *********/
  5725. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5726. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5727. /**
  5728. Automatically locks and unlocks a CriticalSection object.
  5729. Use one of these as a local variable to control access to a CriticalSection.
  5730. e.g. @code
  5731. CriticalSection myCriticalSection;
  5732. for (;;)
  5733. {
  5734. const ScopedLock myScopedLock (myCriticalSection);
  5735. // myCriticalSection is now locked
  5736. ...do some stuff...
  5737. // myCriticalSection gets unlocked here.
  5738. }
  5739. @endcode
  5740. @see CriticalSection, ScopedUnlock
  5741. */
  5742. class JUCE_API ScopedLock
  5743. {
  5744. public:
  5745. /** Creates a ScopedLock.
  5746. As soon as it is created, this will lock the CriticalSection, and
  5747. when the ScopedLock object is deleted, the CriticalSection will
  5748. be unlocked.
  5749. Make sure this object is created and deleted by the same thread,
  5750. otherwise there are no guarantees what will happen! Best just to use it
  5751. as a local stack object, rather than creating one with the new() operator.
  5752. */
  5753. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5754. /** Destructor.
  5755. The CriticalSection will be unlocked when the destructor is called.
  5756. Make sure this object is created and deleted by the same thread,
  5757. otherwise there are no guarantees what will happen!
  5758. */
  5759. inline ~ScopedLock() throw() { lock_.exit(); }
  5760. private:
  5761. const CriticalSection& lock_;
  5762. ScopedLock (const ScopedLock&);
  5763. const ScopedLock& operator= (const ScopedLock&);
  5764. };
  5765. /**
  5766. Automatically unlocks and re-locks a CriticalSection object.
  5767. This is the reverse of a ScopedLock object - instead of locking the critical
  5768. section for the lifetime of this object, it unlocks it.
  5769. Make sure you don't try to unlock critical sections that aren't actually locked!
  5770. e.g. @code
  5771. CriticalSection myCriticalSection;
  5772. for (;;)
  5773. {
  5774. const ScopedLock myScopedLock (myCriticalSection);
  5775. // myCriticalSection is now locked
  5776. ... do some stuff with it locked ..
  5777. while (xyz)
  5778. {
  5779. ... do some stuff with it locked ..
  5780. const ScopedUnlock unlocker (myCriticalSection);
  5781. // myCriticalSection is now unlocked for the remainder of this block,
  5782. // and re-locked at the end.
  5783. ...do some stuff with it unlocked ...
  5784. }
  5785. // myCriticalSection gets unlocked here.
  5786. }
  5787. @endcode
  5788. @see CriticalSection, ScopedLock
  5789. */
  5790. class ScopedUnlock
  5791. {
  5792. public:
  5793. /** Creates a ScopedUnlock.
  5794. As soon as it is created, this will unlock the CriticalSection, and
  5795. when the ScopedLock object is deleted, the CriticalSection will
  5796. be re-locked.
  5797. Make sure this object is created and deleted by the same thread,
  5798. otherwise there are no guarantees what will happen! Best just to use it
  5799. as a local stack object, rather than creating one with the new() operator.
  5800. */
  5801. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5802. /** Destructor.
  5803. The CriticalSection will be unlocked when the destructor is called.
  5804. Make sure this object is created and deleted by the same thread,
  5805. otherwise there are no guarantees what will happen!
  5806. */
  5807. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5808. private:
  5809. const CriticalSection& lock_;
  5810. ScopedUnlock (const ScopedLock&);
  5811. const ScopedUnlock& operator= (const ScopedUnlock&);
  5812. };
  5813. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5814. /********* End of inlined file: juce_ScopedLock.h *********/
  5815. /**
  5816. Macro to declare member variables and methods for a singleton class.
  5817. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  5818. to the class's definition.
  5819. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5820. implementation code.
  5821. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  5822. destructor, in case it is deleted by other means than deleteInstance()
  5823. Clients can then call the static method MyClass::getInstance() to get a pointer
  5824. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  5825. no instance currently exists.
  5826. e.g. @code
  5827. class MySingleton
  5828. {
  5829. public:
  5830. MySingleton()
  5831. {
  5832. }
  5833. ~MySingleton()
  5834. {
  5835. // this ensures that no dangling pointers are left when the
  5836. // singleton is deleted.
  5837. clearSingletonInstance();
  5838. }
  5839. juce_DeclareSingleton (MySingleton, false)
  5840. };
  5841. juce_ImplementSingleton (MySingleton)
  5842. // example of usage:
  5843. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5844. ...
  5845. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5846. @endcode
  5847. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  5848. than once during the process's lifetime - i.e. after you've created and deleted the
  5849. object, getInstance() will refuse to create another one. This can be useful to stop
  5850. objects being accidentally re-created during your app's shutdown code.
  5851. If you know that your object will only be created and deleted by a single thread, you
  5852. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5853. of this one.
  5854. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5855. */
  5856. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  5857. \
  5858. static classname* _singletonInstance; \
  5859. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5860. \
  5861. static classname* getInstance() \
  5862. { \
  5863. if (_singletonInstance == 0) \
  5864. {\
  5865. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5866. \
  5867. if (_singletonInstance == 0) \
  5868. { \
  5869. static bool alreadyInside = false; \
  5870. static bool createdOnceAlready = false; \
  5871. \
  5872. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  5873. jassert (! problem); \
  5874. if (! problem) \
  5875. { \
  5876. createdOnceAlready = true; \
  5877. alreadyInside = true; \
  5878. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5879. alreadyInside = false; \
  5880. \
  5881. _singletonInstance = newObject; \
  5882. } \
  5883. } \
  5884. } \
  5885. \
  5886. return _singletonInstance; \
  5887. } \
  5888. \
  5889. static inline classname* getInstanceWithoutCreating() throw() \
  5890. { \
  5891. return _singletonInstance; \
  5892. } \
  5893. \
  5894. static void deleteInstance() \
  5895. { \
  5896. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5897. if (_singletonInstance != 0) \
  5898. { \
  5899. classname* const old = _singletonInstance; \
  5900. _singletonInstance = 0; \
  5901. delete old; \
  5902. } \
  5903. } \
  5904. \
  5905. void clearSingletonInstance() throw() \
  5906. { \
  5907. if (_singletonInstance == this) \
  5908. _singletonInstance = 0; \
  5909. }
  5910. /** This is a counterpart to the juce_DeclareSingleton macro.
  5911. After adding the juce_DeclareSingleton to the class definition, this macro has
  5912. to be used in the cpp file.
  5913. */
  5914. #define juce_ImplementSingleton(classname) \
  5915. \
  5916. classname* classname::_singletonInstance = 0; \
  5917. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5918. /**
  5919. Macro to declare member variables and methods for a singleton class.
  5920. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5921. section to make access to it thread-safe. If you know that your object will
  5922. only ever be created or deleted by a single thread, then this is a
  5923. more efficient version to use.
  5924. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  5925. than once during the process's lifetime - i.e. after you've created and deleted the
  5926. object, getInstance() will refuse to create another one. This can be useful to stop
  5927. objects being accidentally re-created during your app's shutdown code.
  5928. See the documentation for juce_DeclareSingleton for more information about
  5929. how to use it, the only difference being that you have to use
  5930. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5931. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5932. */
  5933. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  5934. \
  5935. static classname* _singletonInstance; \
  5936. \
  5937. static classname* getInstance() \
  5938. { \
  5939. if (_singletonInstance == 0) \
  5940. { \
  5941. static bool alreadyInside = false; \
  5942. static bool createdOnceAlready = false; \
  5943. \
  5944. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  5945. jassert (! problem); \
  5946. if (! problem) \
  5947. { \
  5948. createdOnceAlready = true; \
  5949. alreadyInside = true; \
  5950. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5951. alreadyInside = false; \
  5952. \
  5953. _singletonInstance = newObject; \
  5954. } \
  5955. } \
  5956. \
  5957. return _singletonInstance; \
  5958. } \
  5959. \
  5960. static inline classname* getInstanceWithoutCreating() throw() \
  5961. { \
  5962. return _singletonInstance; \
  5963. } \
  5964. \
  5965. static void deleteInstance() \
  5966. { \
  5967. if (_singletonInstance != 0) \
  5968. { \
  5969. classname* const old = _singletonInstance; \
  5970. _singletonInstance = 0; \
  5971. delete old; \
  5972. } \
  5973. } \
  5974. \
  5975. void clearSingletonInstance() throw() \
  5976. { \
  5977. if (_singletonInstance == this) \
  5978. _singletonInstance = 0; \
  5979. }
  5980. /**
  5981. Macro to declare member variables and methods for a singleton class.
  5982. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5983. for recursion or repeated instantiation. It's intended for use as a lightweight
  5984. version of a singleton, where you're using it in very straightforward
  5985. circumstances and don't need the extra checking.
  5986. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  5987. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  5988. See the documentation for juce_DeclareSingleton for more information about
  5989. how to use it, the only difference being that you have to use
  5990. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5991. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  5992. */
  5993. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  5994. \
  5995. static classname* _singletonInstance; \
  5996. \
  5997. static classname* getInstance() \
  5998. { \
  5999. if (_singletonInstance == 0) \
  6000. _singletonInstance = new classname(); \
  6001. \
  6002. return _singletonInstance; \
  6003. } \
  6004. \
  6005. static inline classname* getInstanceWithoutCreating() throw() \
  6006. { \
  6007. return _singletonInstance; \
  6008. } \
  6009. \
  6010. static void deleteInstance() \
  6011. { \
  6012. if (_singletonInstance != 0) \
  6013. { \
  6014. classname* const old = _singletonInstance; \
  6015. _singletonInstance = 0; \
  6016. delete old; \
  6017. } \
  6018. } \
  6019. \
  6020. void clearSingletonInstance() throw() \
  6021. { \
  6022. if (_singletonInstance == this) \
  6023. _singletonInstance = 0; \
  6024. }
  6025. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  6026. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  6027. to the class definition, this macro has to be used somewhere in the cpp file.
  6028. */
  6029. #define juce_ImplementSingleton_SingleThreaded(classname) \
  6030. \
  6031. classname* classname::_singletonInstance = 0;
  6032. #endif // __JUCE_SINGLETON_JUCEHEADER__
  6033. /********* End of inlined file: juce_Singleton.h *********/
  6034. #endif
  6035. #ifndef __JUCE_RANDOM_JUCEHEADER__
  6036. /********* Start of inlined file: juce_Random.h *********/
  6037. #ifndef __JUCE_RANDOM_JUCEHEADER__
  6038. #define __JUCE_RANDOM_JUCEHEADER__
  6039. /********* Start of inlined file: juce_BitArray.h *********/
  6040. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6041. #define __JUCE_BITARRAY_JUCEHEADER__
  6042. class MemoryBlock;
  6043. /**
  6044. An array of on/off bits, also usable to store large binary integers.
  6045. A BitArray acts like an arbitrarily large integer whose bits can be set or
  6046. cleared, and some basic mathematical operations can be done on the number as
  6047. a whole.
  6048. */
  6049. class JUCE_API BitArray
  6050. {
  6051. public:
  6052. /** Creates an empty BitArray */
  6053. BitArray() throw();
  6054. /** Creates a BitArray containing an integer value in its low bits.
  6055. The low 32 bits of the array are initialised with this value.
  6056. */
  6057. BitArray (const unsigned int value) throw();
  6058. /** Creates a BitArray containing an integer value in its low bits.
  6059. The low 32 bits of the array are initialised with the absolute value
  6060. passed in, and its sign is set to reflect the sign of the number.
  6061. */
  6062. BitArray (const int value) throw();
  6063. /** Creates a BitArray containing an integer value in its low bits.
  6064. The low 64 bits of the array are initialised with the absolute value
  6065. passed in, and its sign is set to reflect the sign of the number.
  6066. */
  6067. BitArray (int64 value) throw();
  6068. /** Creates a copy of another BitArray. */
  6069. BitArray (const BitArray& other) throw();
  6070. /** Destructor. */
  6071. ~BitArray() throw();
  6072. /** Copies another BitArray onto this one. */
  6073. const BitArray& operator= (const BitArray& other) throw();
  6074. /** Two arrays are the same if the same bits are set. */
  6075. bool operator== (const BitArray& other) const throw();
  6076. /** Two arrays are the same if the same bits are set. */
  6077. bool operator!= (const BitArray& other) const throw();
  6078. /** Clears all bits in the BitArray to 0. */
  6079. void clear() throw();
  6080. /** Clears a particular bit in the array. */
  6081. void clearBit (const int bitNumber) throw();
  6082. /** Sets a specified bit to 1.
  6083. If the bit number is high, this will grow the array to accomodate it.
  6084. */
  6085. void setBit (const int bitNumber) throw();
  6086. /** Sets or clears a specified bit. */
  6087. void setBit (const int bitNumber,
  6088. const bool shouldBeSet) throw();
  6089. /** Sets a range of bits to be either on or off.
  6090. @param startBit the first bit to change
  6091. @param numBits the number of bits to change
  6092. @param shouldBeSet whether to turn these bits on or off
  6093. */
  6094. void setRange (int startBit,
  6095. int numBits,
  6096. const bool shouldBeSet) throw();
  6097. /** Inserts a bit an a given position, shifting up any bits above it. */
  6098. void insertBit (const int bitNumber,
  6099. const bool shouldBeSet) throw();
  6100. /** Returns the value of a specified bit in the array.
  6101. If the index is out-of-range, the result will be false.
  6102. */
  6103. bool operator[] (const int bit) const throw();
  6104. /** Returns true if no bits are set. */
  6105. bool isEmpty() const throw();
  6106. /** Returns a range of bits in the array as a new BitArray.
  6107. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  6108. @see getBitRangeAsInt
  6109. */
  6110. const BitArray getBitRange (int startBit, int numBits) const throw();
  6111. /** Returns a range of bits in the array as an integer value.
  6112. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  6113. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  6114. getBitRange().
  6115. */
  6116. int getBitRangeAsInt (int startBit, int numBits) const throw();
  6117. /** Sets a range of bits in the array based on an integer value.
  6118. Copies the given integer into the array, starting at startBit,
  6119. and only using up to numBits of the available bits.
  6120. */
  6121. void setBitRangeAsInt (int startBit, int numBits,
  6122. unsigned int valueToSet) throw();
  6123. /** Performs a bitwise OR with another BitArray.
  6124. The result ends up in this array.
  6125. */
  6126. void orWith (const BitArray& other) throw();
  6127. /** Performs a bitwise AND with another BitArray.
  6128. The result ends up in this array.
  6129. */
  6130. void andWith (const BitArray& other) throw();
  6131. /** Performs a bitwise XOR with another BitArray.
  6132. The result ends up in this array.
  6133. */
  6134. void xorWith (const BitArray& other) throw();
  6135. /** Adds another BitArray's value to this one.
  6136. Treating the two arrays as large positive integers, this
  6137. adds them up and puts the result in this array.
  6138. */
  6139. void add (const BitArray& other) throw();
  6140. /** Subtracts another BitArray's value from this one.
  6141. Treating the two arrays as large positive integers, this
  6142. subtracts them and puts the result in this array.
  6143. Note that if the result should be negative, this won't be
  6144. handled correctly.
  6145. */
  6146. void subtract (const BitArray& other) throw();
  6147. /** Multiplies another BitArray's value with this one.
  6148. Treating the two arrays as large positive integers, this
  6149. multiplies them and puts the result in this array.
  6150. */
  6151. void multiplyBy (const BitArray& other) throw();
  6152. /** Divides another BitArray's value into this one and also produces a remainder.
  6153. Treating the two arrays as large positive integers, this
  6154. divides this value by the other, leaving the quotient in this
  6155. array, and the remainder is copied into the other BitArray passed in.
  6156. */
  6157. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  6158. /** Returns the largest value that will divide both this value and the one
  6159. passed-in.
  6160. */
  6161. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  6162. /** Performs a modulo operation on this value.
  6163. The result is stored in this value.
  6164. */
  6165. void modulo (const BitArray& divisor) throw();
  6166. /** Performs a combined exponent and modulo operation.
  6167. This BitArray's value becomes (this ^ exponent) % modulus.
  6168. */
  6169. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  6170. /** Performs an inverse modulo on the value.
  6171. i.e. the result is (this ^ -1) mod (modulus).
  6172. */
  6173. void inverseModulo (const BitArray& modulus) throw();
  6174. /** Shifts a section of bits left or right.
  6175. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  6176. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  6177. */
  6178. void shiftBits (int howManyBitsLeft,
  6179. int startBit = 0) throw();
  6180. /** Does a signed comparison of two BitArrays.
  6181. Return values are:
  6182. - 0 if the numbers are the same
  6183. - < 0 if this number is smaller than the other
  6184. - > 0 if this number is bigger than the other
  6185. */
  6186. int compare (const BitArray& other) const throw();
  6187. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  6188. Return values are:
  6189. - 0 if the numbers are the same
  6190. - < 0 if this number is smaller than the other
  6191. - > 0 if this number is bigger than the other
  6192. */
  6193. int compareAbsolute (const BitArray& other) const throw();
  6194. /** Returns true if the value is less than zero.
  6195. @see setNegative, negate
  6196. */
  6197. bool isNegative() const throw();
  6198. /** Changes the sign of the number to be positive or negative.
  6199. @see isNegative, negate
  6200. */
  6201. void setNegative (const bool shouldBeNegative) throw();
  6202. /** Inverts the sign of the number.
  6203. @see isNegative, setNegative
  6204. */
  6205. void negate() throw();
  6206. /** Counts the total number of set bits in the array. */
  6207. int countNumberOfSetBits() const throw();
  6208. /** Looks for the index of the next set bit after a given starting point.
  6209. searches from startIndex (inclusive) upwards for the first set bit,
  6210. and returns its index.
  6211. If no set bits are found, it returns -1.
  6212. */
  6213. int findNextSetBit (int startIndex = 0) const throw();
  6214. /** Looks for the index of the next clear bit after a given starting point.
  6215. searches from startIndex (inclusive) upwards for the first clear bit,
  6216. and returns its index.
  6217. */
  6218. int findNextClearBit (int startIndex = 0) const throw();
  6219. /** Returns the index of the highest set bit in the array.
  6220. If the array is empty, this will return -1.
  6221. */
  6222. int getHighestBit() const throw();
  6223. /** Converts the array to a number string.
  6224. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  6225. If minuimumNumCharacters is greater than 0, the returned string will be
  6226. padded with leading zeros to reach at least that length.
  6227. */
  6228. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  6229. /** Converts a number string to an array.
  6230. Any non-valid characters will be ignored.
  6231. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  6232. */
  6233. void parseString (const String& text,
  6234. const int base) throw();
  6235. /** Turns the array into a block of binary data.
  6236. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  6237. of the array, and so on.
  6238. @see loadFromMemoryBlock
  6239. */
  6240. const MemoryBlock toMemoryBlock() const throw();
  6241. /** Copies a block of raw data onto this array.
  6242. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  6243. of the array, and so on.
  6244. @see toMemoryBlock
  6245. */
  6246. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  6247. juce_UseDebuggingNewOperator
  6248. private:
  6249. void ensureSize (const int numVals) throw();
  6250. unsigned int* values;
  6251. int numValues, highestBit;
  6252. bool negative;
  6253. };
  6254. #endif // __JUCE_BITARRAY_JUCEHEADER__
  6255. /********* End of inlined file: juce_BitArray.h *********/
  6256. /**
  6257. A simple pseudo-random number generator.
  6258. */
  6259. class JUCE_API Random
  6260. {
  6261. public:
  6262. /** Creates a Random object based on a seed value.
  6263. For a given seed value, the subsequent numbers generated by this object
  6264. will be predictable, so a good idea is to set this value based
  6265. on the time, e.g.
  6266. new Random (Time::currentTimeMillis())
  6267. */
  6268. Random (const int64 seedValue) throw();
  6269. /** Destructor. */
  6270. ~Random() throw();
  6271. /** Returns the next random 32 bit integer.
  6272. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  6273. */
  6274. int nextInt() throw();
  6275. /** Returns the next random number, limited to a given range.
  6276. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  6277. */
  6278. int nextInt (const int maxValue) throw();
  6279. /** Returns the next 64-bit random number.
  6280. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  6281. */
  6282. int64 nextInt64() throw();
  6283. /** Returns the next random floating-point number.
  6284. @returns a random value in the range 0 to 1.0
  6285. */
  6286. float nextFloat() throw();
  6287. /** Returns the next random floating-point number.
  6288. @returns a random value in the range 0 to 1.0
  6289. */
  6290. double nextDouble() throw();
  6291. /** Returns the next random boolean value.
  6292. */
  6293. bool nextBool() throw();
  6294. /** Returns a BitArray containing a random number.
  6295. @returns a random value in the range 0 to (maximumValue - 1).
  6296. */
  6297. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  6298. /** Sets a range of bits in a BitArray to random values. */
  6299. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  6300. /** To avoid the overhead of having to create a new Random object whenever
  6301. you need a number, this is a shared application-wide object that
  6302. can be used.
  6303. It's not thread-safe though, so threads should use their own Random object.
  6304. */
  6305. static Random& getSystemRandom() throw();
  6306. /** Resets this Random object to a given seed value. */
  6307. void setSeed (const int64 newSeed) throw();
  6308. /** Reseeds this generator using a value generated from various semi-random system
  6309. properties like the current time, etc.
  6310. Because this function convolves the time with the last seed value, calling
  6311. it repeatedly will increase the randomness of the final result.
  6312. */
  6313. void setSeedRandomly();
  6314. juce_UseDebuggingNewOperator
  6315. private:
  6316. int64 seed;
  6317. };
  6318. #endif // __JUCE_RANDOM_JUCEHEADER__
  6319. /********* End of inlined file: juce_Random.h *********/
  6320. #endif
  6321. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  6322. #endif
  6323. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6324. /********* Start of inlined file: juce_SystemStats.h *********/
  6325. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6326. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  6327. /**
  6328. Contains methods for finding out about the current hardware and OS configuration.
  6329. */
  6330. class JUCE_API SystemStats
  6331. {
  6332. public:
  6333. /** Returns the current version of JUCE,
  6334. (just in case you didn't already know at compile-time.)
  6335. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  6336. */
  6337. static const String getJUCEVersion() throw();
  6338. /** The set of possible results of the getOperatingSystemType() method.
  6339. */
  6340. enum OperatingSystemType
  6341. {
  6342. UnknownOS = 0,
  6343. MacOSX = 0x1000,
  6344. Linux = 0x2000,
  6345. Win95 = 0x4001,
  6346. Win98 = 0x4002,
  6347. WinNT351 = 0x4103,
  6348. WinNT40 = 0x4104,
  6349. Win2000 = 0x4105,
  6350. WinXP = 0x4106,
  6351. WinVista = 0x4107,
  6352. Windows7 = 0x4108,
  6353. Windows = 0x4000, /**< To test whether any version of Windows is running,
  6354. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  6355. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  6356. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  6357. };
  6358. /** Returns the type of operating system we're running on.
  6359. @returns one of the values from the OperatingSystemType enum.
  6360. @see getOperatingSystemName
  6361. */
  6362. static OperatingSystemType getOperatingSystemType() throw();
  6363. /** Returns the name of the type of operating system we're running on.
  6364. @returns a string describing the OS type.
  6365. @see getOperatingSystemType
  6366. */
  6367. static const String getOperatingSystemName() throw();
  6368. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  6369. */
  6370. static bool isOperatingSystem64Bit() throw();
  6371. // CPU and memory information..
  6372. /** Returns the approximate CPU speed.
  6373. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6374. what year you're reading this...)
  6375. */
  6376. static int getCpuSpeedInMegaherz() throw();
  6377. /** Returns a string to indicate the CPU vendor.
  6378. Might not be known on some systems.
  6379. */
  6380. static const String getCpuVendor() throw();
  6381. /** Checks whether Intel MMX instructions are available. */
  6382. static bool hasMMX() throw();
  6383. /** Checks whether Intel SSE instructions are available. */
  6384. static bool hasSSE() throw();
  6385. /** Checks whether Intel SSE2 instructions are available. */
  6386. static bool hasSSE2() throw();
  6387. /** Checks whether AMD 3DNOW instructions are available. */
  6388. static bool has3DNow() throw();
  6389. /** Returns the number of CPUs.
  6390. */
  6391. static int getNumCpus() throw();
  6392. /** Returns a clock-cycle tick counter, if available.
  6393. If the machine can do it, this will return a tick-count
  6394. where each tick is one cpu clock cycle - used for profiling
  6395. code.
  6396. @returns the tick count, or zero if not available.
  6397. */
  6398. static int64 getClockCycleCounter() throw();
  6399. /** Finds out how much RAM is in the machine.
  6400. @returns the approximate number of megabytes of memory, or zero if
  6401. something goes wrong when finding out.
  6402. */
  6403. static int getMemorySizeInMegabytes() throw();
  6404. /** Returns the system page-size.
  6405. This is only used by programmers with beards.
  6406. */
  6407. static int getPageSize() throw();
  6408. /** Returns a list of MAC addresses found on this machine.
  6409. @param addresses an array into which the MAC addresses should be copied
  6410. @param maxNum the number of elements in this array
  6411. @param littleEndian the endianness of the numbers to return. If this is true,
  6412. the least-significant byte of each number is the first byte
  6413. of the mac address. If false, the least significant byte is
  6414. the last number. Note that the default values of this parameter
  6415. are different on Mac/PC to avoid breaking old software that was
  6416. written before this parameter was added (when the two systems
  6417. defaulted to using different endiannesses). In newer
  6418. software you probably want to specify an explicit value
  6419. for this.
  6420. @returns the number of MAC addresses that were found
  6421. */
  6422. static int getMACAddresses (int64* addresses, int maxNum,
  6423. #if JUCE_MAC
  6424. const bool littleEndian = true) throw();
  6425. #else
  6426. const bool littleEndian = false) throw();
  6427. #endif
  6428. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6429. static void initialiseStats() throw();
  6430. };
  6431. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6432. /********* End of inlined file: juce_SystemStats.h *********/
  6433. #endif
  6434. #ifndef __JUCE_TIME_JUCEHEADER__
  6435. #endif
  6436. #ifndef __JUCE_UUID_JUCEHEADER__
  6437. /********* Start of inlined file: juce_Uuid.h *********/
  6438. #ifndef __JUCE_UUID_JUCEHEADER__
  6439. #define __JUCE_UUID_JUCEHEADER__
  6440. /**
  6441. A universally unique 128-bit identifier.
  6442. This class generates very random unique numbers based on the system time
  6443. and MAC addresses if any are available. It's extremely unlikely that two identical
  6444. UUIDs would ever be created by chance.
  6445. The class includes methods for saving the ID as a string or as raw binary data.
  6446. */
  6447. class JUCE_API Uuid
  6448. {
  6449. public:
  6450. /** Creates a new unique ID. */
  6451. Uuid();
  6452. /** Destructor. */
  6453. ~Uuid() throw();
  6454. /** Creates a copy of another UUID. */
  6455. Uuid (const Uuid& other);
  6456. /** Copies another UUID. */
  6457. Uuid& operator= (const Uuid& other);
  6458. /** Returns true if the ID is zero. */
  6459. bool isNull() const throw();
  6460. /** Compares two UUIDs. */
  6461. bool operator== (const Uuid& other) const;
  6462. /** Compares two UUIDs. */
  6463. bool operator!= (const Uuid& other) const;
  6464. /** Returns a stringified version of this UUID.
  6465. A Uuid object can later be reconstructed from this string using operator= or
  6466. the constructor that takes a string parameter.
  6467. @returns a 32 character hex string.
  6468. */
  6469. const String toString() const;
  6470. /** Creates an ID from an encoded string version.
  6471. @see toString
  6472. */
  6473. Uuid (const String& uuidString);
  6474. /** Copies from a stringified UUID.
  6475. The string passed in should be one that was created with the toString() method.
  6476. */
  6477. Uuid& operator= (const String& uuidString);
  6478. /** Returns a pointer to the internal binary representation of the ID.
  6479. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  6480. the constructor or operator= method that takes an array of uint8s.
  6481. */
  6482. const uint8* getRawData() const throw() { return value.asBytes; }
  6483. /** Creates a UUID from a 16-byte array.
  6484. @see getRawData
  6485. */
  6486. Uuid (const uint8* const rawData);
  6487. /** Sets this UUID from 16-bytes of raw data. */
  6488. Uuid& operator= (const uint8* const rawData);
  6489. juce_UseDebuggingNewOperator
  6490. private:
  6491. union
  6492. {
  6493. uint8 asBytes [16];
  6494. int asInt[4];
  6495. int64 asInt64[2];
  6496. } value;
  6497. };
  6498. #endif // __JUCE_UUID_JUCEHEADER__
  6499. /********* End of inlined file: juce_Uuid.h *********/
  6500. #endif
  6501. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  6502. #endif
  6503. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  6504. #endif
  6505. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  6506. #endif
  6507. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6508. #endif
  6509. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6510. #endif
  6511. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6512. #endif
  6513. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6514. #endif
  6515. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6516. #endif
  6517. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6518. #endif
  6519. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6520. /********* Start of inlined file: juce_PropertySet.h *********/
  6521. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6522. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6523. /********* Start of inlined file: juce_StringPairArray.h *********/
  6524. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6525. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6526. /**
  6527. A container for holding a set of strings which are keyed by another string.
  6528. @see StringArray
  6529. */
  6530. class JUCE_API StringPairArray
  6531. {
  6532. public:
  6533. /** Creates an empty array */
  6534. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6535. /** Creates a copy of another array */
  6536. StringPairArray (const StringPairArray& other) throw();
  6537. /** Destructor. */
  6538. ~StringPairArray() throw();
  6539. /** Copies the contents of another string array into this one */
  6540. const StringPairArray& operator= (const StringPairArray& other) throw();
  6541. /** Compares two arrays.
  6542. Comparisons are case-sensitive.
  6543. @returns true only if the other array contains exactly the same strings with the same keys
  6544. */
  6545. bool operator== (const StringPairArray& other) const throw();
  6546. /** Compares two arrays.
  6547. Comparisons are case-sensitive.
  6548. @returns false if the other array contains exactly the same strings with the same keys
  6549. */
  6550. bool operator!= (const StringPairArray& other) const throw();
  6551. /** Finds the value corresponding to a key string.
  6552. If no such key is found, this will just return an empty string. To check whether
  6553. a given key actually exists (because it might actually be paired with an empty string), use
  6554. the getAllKeys() method to obtain a list.
  6555. Obviously the reference returned shouldn't be stored for later use, as the
  6556. string it refers to may disappear when the array changes.
  6557. @see getValue
  6558. */
  6559. const String& operator[] (const String& key) const throw();
  6560. /** Finds the value corresponding to a key string.
  6561. If no such key is found, this will just return the value provided as a default.
  6562. @see operator[]
  6563. */
  6564. const String getValue (const String& key, const String& defaultReturnValue) const;
  6565. /** Returns a list of all keys in the array. */
  6566. const StringArray& getAllKeys() const throw() { return keys; }
  6567. /** Returns a list of all values in the array. */
  6568. const StringArray& getAllValues() const throw() { return values; }
  6569. /** Returns the number of strings in the array */
  6570. inline int size() const throw() { return keys.size(); };
  6571. /** Adds or amends a key/value pair.
  6572. If a value already exists with this key, its value will be overwritten,
  6573. otherwise the key/value pair will be added to the array.
  6574. */
  6575. void set (const String& key,
  6576. const String& value) throw();
  6577. /** Adds the items from another array to this one.
  6578. This is equivalent to using set() to add each of the pairs from the other array.
  6579. */
  6580. void addArray (const StringPairArray& other);
  6581. /** Removes all elements from the array. */
  6582. void clear() throw();
  6583. /** Removes a string from the array based on its key.
  6584. If the key isn't found, nothing will happen.
  6585. */
  6586. void remove (const String& key) throw();
  6587. /** Removes a string from the array based on its index.
  6588. If the index is out-of-range, no action will be taken.
  6589. */
  6590. void remove (const int index) throw();
  6591. /** Indicates whether to use a case-insensitive search when looking up a key string.
  6592. */
  6593. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  6594. /** Returns a descriptive string containing the items.
  6595. This is handy for dumping the contents of an array.
  6596. */
  6597. const String getDescription() const;
  6598. /** Reduces the amount of storage being used by the array.
  6599. Arrays typically allocate slightly more storage than they need, and after
  6600. removing elements, they may have quite a lot of unused space allocated.
  6601. This method will reduce the amount of allocated storage to a minimum.
  6602. */
  6603. void minimiseStorageOverheads() throw();
  6604. juce_UseDebuggingNewOperator
  6605. private:
  6606. StringArray keys, values;
  6607. bool ignoreCase;
  6608. };
  6609. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6610. /********* End of inlined file: juce_StringPairArray.h *********/
  6611. /********* Start of inlined file: juce_XmlElement.h *********/
  6612. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6613. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6614. /********* Start of inlined file: juce_OutputStream.h *********/
  6615. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6616. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6617. /********* Start of inlined file: juce_InputStream.h *********/
  6618. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6619. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6620. /** The base class for streams that read data.
  6621. Input and output streams are used throughout the library - subclasses can override
  6622. some or all of the virtual functions to implement their behaviour.
  6623. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6624. */
  6625. class JUCE_API InputStream
  6626. {
  6627. public:
  6628. /** Destructor. */
  6629. virtual ~InputStream() {}
  6630. /** Returns the total number of bytes available for reading in this stream.
  6631. Note that this is the number of bytes available from the start of the
  6632. stream, not from the current position.
  6633. If the size of the stream isn't actually known, this may return -1.
  6634. */
  6635. virtual int64 getTotalLength() = 0;
  6636. /** Returns true if the stream has no more data to read. */
  6637. virtual bool isExhausted() = 0;
  6638. /** Reads a set of bytes from the stream into a memory buffer.
  6639. This is the only read method that subclasses actually need to implement, as the
  6640. InputStream base class implements the other read methods in terms of this one (although
  6641. it's often more efficient for subclasses to implement them directly).
  6642. @param destBuffer the destination buffer for the data
  6643. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6644. memory block passed in is big enough to contain this
  6645. many bytes.
  6646. @returns the actual number of bytes that were read, which may be less than
  6647. maxBytesToRead if the stream is exhausted before it gets that far
  6648. */
  6649. virtual int read (void* destBuffer,
  6650. int maxBytesToRead) = 0;
  6651. /** Reads a byte from the stream.
  6652. If the stream is exhausted, this will return zero.
  6653. @see OutputStream::writeByte
  6654. */
  6655. virtual char readByte();
  6656. /** Reads a boolean from the stream.
  6657. The bool is encoded as a single byte - 1 for true, 0 for false.
  6658. If the stream is exhausted, this will return false.
  6659. @see OutputStream::writeBool
  6660. */
  6661. virtual bool readBool();
  6662. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6663. If the next two bytes read are byte1 and byte2, this returns
  6664. (byte1 | (byte2 << 8)).
  6665. If the stream is exhausted partway through reading the bytes, this will return zero.
  6666. @see OutputStream::writeShort, readShortBigEndian
  6667. */
  6668. virtual short readShort();
  6669. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6670. If the next two bytes read are byte1 and byte2, this returns
  6671. (byte2 | (byte1 << 8)).
  6672. If the stream is exhausted partway through reading the bytes, this will return zero.
  6673. @see OutputStream::writeShortBigEndian, readShort
  6674. */
  6675. virtual short readShortBigEndian();
  6676. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6677. If the next four bytes are byte1 to byte4, this returns
  6678. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6679. If the stream is exhausted partway through reading the bytes, this will return zero.
  6680. @see OutputStream::writeInt, readIntBigEndian
  6681. */
  6682. virtual int readInt();
  6683. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6684. If the next four bytes are byte1 to byte4, this returns
  6685. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6686. If the stream is exhausted partway through reading the bytes, this will return zero.
  6687. @see OutputStream::writeIntBigEndian, readInt
  6688. */
  6689. virtual int readIntBigEndian();
  6690. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6691. If the next eight bytes are byte1 to byte8, this returns
  6692. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6693. If the stream is exhausted partway through reading the bytes, this will return zero.
  6694. @see OutputStream::writeInt64, readInt64BigEndian
  6695. */
  6696. virtual int64 readInt64();
  6697. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6698. If the next eight bytes are byte1 to byte8, this returns
  6699. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6700. If the stream is exhausted partway through reading the bytes, this will return zero.
  6701. @see OutputStream::writeInt64BigEndian, readInt64
  6702. */
  6703. virtual int64 readInt64BigEndian();
  6704. /** Reads four bytes as a 32-bit floating point value.
  6705. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6706. If the stream is exhausted partway through reading the bytes, this will return zero.
  6707. @see OutputStream::writeFloat, readDouble
  6708. */
  6709. virtual float readFloat();
  6710. /** Reads four bytes as a 32-bit floating point value.
  6711. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6712. If the stream is exhausted partway through reading the bytes, this will return zero.
  6713. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6714. */
  6715. virtual float readFloatBigEndian();
  6716. /** Reads eight bytes as a 64-bit floating point value.
  6717. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6718. If the stream is exhausted partway through reading the bytes, this will return zero.
  6719. @see OutputStream::writeDouble, readFloat
  6720. */
  6721. virtual double readDouble();
  6722. /** Reads eight bytes as a 64-bit floating point value.
  6723. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6724. If the stream is exhausted partway through reading the bytes, this will return zero.
  6725. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6726. */
  6727. virtual double readDoubleBigEndian();
  6728. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6729. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6730. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6731. @see OutputStream::writeCompressedInt()
  6732. */
  6733. virtual int readCompressedInt();
  6734. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6735. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6736. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6737. After this call, the stream's position will be left pointing to the character
  6738. following the line-feed, but the linefeeds aren't included in the string that
  6739. is returned.
  6740. */
  6741. virtual const String readNextLine();
  6742. /** Reads a zero-terminated string from the stream.
  6743. This will read characters from the stream until it hits a zero character or
  6744. end-of-stream.
  6745. @see OutputStream::writeString, readEntireStreamAsString
  6746. */
  6747. virtual const String readString();
  6748. /** Tries to read the whole stream and turn it into a string.
  6749. This will read from the stream's current position until the end-of-stream, and
  6750. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6751. */
  6752. virtual const String readEntireStreamAsString();
  6753. /** Reads from the stream and appends the data to a MemoryBlock.
  6754. @param destBlock the block to append the data onto
  6755. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6756. of bytes that will be read - if it's negative, data
  6757. will be read until the stream is exhausted.
  6758. @returns the number of bytes that were added to the memory block
  6759. */
  6760. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6761. int maxNumBytesToRead = -1);
  6762. /** Returns the offset of the next byte that will be read from the stream.
  6763. @see setPosition
  6764. */
  6765. virtual int64 getPosition() = 0;
  6766. /** Tries to move the current read position of the stream.
  6767. The position is an absolute number of bytes from the stream's start.
  6768. Some streams might not be able to do this, in which case they should do
  6769. nothing and return false. Others might be able to manage it by resetting
  6770. themselves and skipping to the correct position, although this is
  6771. obviously a bit slow.
  6772. @returns true if the stream manages to reposition itself correctly
  6773. @see getPosition
  6774. */
  6775. virtual bool setPosition (int64 newPosition) = 0;
  6776. /** Reads and discards a number of bytes from the stream.
  6777. Some input streams might implement this efficiently, but the base
  6778. class will just keep reading data until the requisite number of bytes
  6779. have been done.
  6780. */
  6781. virtual void skipNextBytes (int64 numBytesToSkip);
  6782. juce_UseDebuggingNewOperator
  6783. protected:
  6784. InputStream() throw() {}
  6785. };
  6786. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6787. /********* End of inlined file: juce_InputStream.h *********/
  6788. /**
  6789. The base class for streams that write data to some kind of destination.
  6790. Input and output streams are used throughout the library - subclasses can override
  6791. some or all of the virtual functions to implement their behaviour.
  6792. @see InputStream, MemoryOutputStream, FileOutputStream
  6793. */
  6794. class JUCE_API OutputStream
  6795. {
  6796. public:
  6797. /** Destructor.
  6798. Some subclasses might want to do things like call flush() during their
  6799. destructors.
  6800. */
  6801. virtual ~OutputStream();
  6802. /** If the stream is using a buffer, this will ensure it gets written
  6803. out to the destination. */
  6804. virtual void flush() = 0;
  6805. /** Tries to move the stream's output position.
  6806. Not all streams will be able to seek to a new position - this will return
  6807. false if it fails to work.
  6808. @see getPosition
  6809. */
  6810. virtual bool setPosition (int64 newPosition) = 0;
  6811. /** Returns the stream's current position.
  6812. @see setPosition
  6813. */
  6814. virtual int64 getPosition() = 0;
  6815. /** Writes a block of data to the stream.
  6816. When creating a subclass of OutputStream, this is the only write method
  6817. that needs to be overloaded - the base class has methods for writing other
  6818. types of data which use this to do the work.
  6819. @returns false if the write operation fails for some reason
  6820. */
  6821. virtual bool write (const void* dataToWrite,
  6822. int howManyBytes) = 0;
  6823. /** Writes a single byte to the stream.
  6824. @see InputStream::readByte
  6825. */
  6826. virtual void writeByte (char byte);
  6827. /** Writes a boolean to the stream.
  6828. This is encoded as a byte - either 1 or 0.
  6829. @see InputStream::readBool
  6830. */
  6831. virtual void writeBool (bool boolValue);
  6832. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6833. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6834. @see InputStream::readShort
  6835. */
  6836. virtual void writeShort (short value);
  6837. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6838. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6839. @see InputStream::readShortBigEndian
  6840. */
  6841. virtual void writeShortBigEndian (short value);
  6842. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6843. @see InputStream::readInt
  6844. */
  6845. virtual void writeInt (int value);
  6846. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6847. @see InputStream::readIntBigEndian
  6848. */
  6849. virtual void writeIntBigEndian (int value);
  6850. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6851. @see InputStream::readInt64
  6852. */
  6853. virtual void writeInt64 (int64 value);
  6854. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6855. @see InputStream::readInt64BigEndian
  6856. */
  6857. virtual void writeInt64BigEndian (int64 value);
  6858. /** Writes a 32-bit floating point value to the stream.
  6859. The binary 32-bit encoding of the float is written as a little-endian int.
  6860. @see InputStream::readFloat
  6861. */
  6862. virtual void writeFloat (float value);
  6863. /** Writes a 32-bit floating point value to the stream.
  6864. The binary 32-bit encoding of the float is written as a big-endian int.
  6865. @see InputStream::readFloatBigEndian
  6866. */
  6867. virtual void writeFloatBigEndian (float value);
  6868. /** Writes a 64-bit floating point value to the stream.
  6869. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6870. @see InputStream::readDouble
  6871. */
  6872. virtual void writeDouble (double value);
  6873. /** Writes a 64-bit floating point value to the stream.
  6874. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6875. @see InputStream::readDoubleBigEndian
  6876. */
  6877. virtual void writeDoubleBigEndian (double value);
  6878. /** Writes a condensed encoding of a 32-bit integer.
  6879. If you're storing a lot of integers which are unlikely to have very large values,
  6880. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6881. under 0xffff only 3 bytes, etc.
  6882. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6883. @see InputStream::readCompressedInt
  6884. */
  6885. virtual void writeCompressedInt (int value);
  6886. /** Stores a string in the stream.
  6887. This isn't the method to use if you're trying to append text to the end of a
  6888. text-file! It's intended for storing a string for later retrieval
  6889. by InputStream::readString.
  6890. For appending text to a file, instead use writeText, printf, or operator<<
  6891. @see InputStream::readString, writeText, printf, operator<<
  6892. */
  6893. virtual void writeString (const String& text);
  6894. /** Writes a string of text to the stream.
  6895. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6896. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6897. should only be done at the start of a file).
  6898. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6899. */
  6900. virtual void writeText (const String& text,
  6901. const bool asUnicode,
  6902. const bool writeUnicodeHeaderBytes);
  6903. /** Writes a string of text to the stream.
  6904. @see writeText
  6905. */
  6906. virtual void printf (const char* format, ...);
  6907. /** Reads data from an input stream and writes it to this stream.
  6908. @param source the stream to read from
  6909. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6910. less than zero, it will keep reading until the input
  6911. is exhausted)
  6912. */
  6913. virtual int writeFromInputStream (InputStream& source,
  6914. int maxNumBytesToWrite);
  6915. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6916. virtual OutputStream& operator<< (const int number);
  6917. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6918. virtual OutputStream& operator<< (const double number);
  6919. /** Writes a character to the stream. */
  6920. virtual OutputStream& operator<< (const char character);
  6921. /** Writes a null-terminated string to the stream. */
  6922. virtual OutputStream& operator<< (const char* const text);
  6923. /** Writes a null-terminated unicode text string to the stream, converting it
  6924. to 8-bit characters in the default system encoding. */
  6925. virtual OutputStream& operator<< (const juce_wchar* const text);
  6926. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6927. virtual OutputStream& operator<< (const String& text);
  6928. juce_UseDebuggingNewOperator
  6929. protected:
  6930. OutputStream() throw();
  6931. };
  6932. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6933. /********* End of inlined file: juce_OutputStream.h *********/
  6934. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6935. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6936. will be the name of a pointer to each child element.
  6937. E.g. @code
  6938. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6939. forEachXmlChildElement (*myParentXml, child)
  6940. {
  6941. if (child->hasTagName ("FOO"))
  6942. doSomethingWithXmlElement (child);
  6943. }
  6944. @endcode
  6945. @see forEachXmlChildElementWithTagName
  6946. */
  6947. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6948. \
  6949. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6950. childElementVariableName != 0; \
  6951. childElementVariableName = childElementVariableName->getNextElement())
  6952. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6953. which have a specified tag.
  6954. This does the same job as the forEachXmlChildElement macro, but only for those
  6955. elements that have a particular tag name.
  6956. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6957. will be the name of a pointer to each child element. The requiredTagName is the
  6958. tag name to match.
  6959. E.g. @code
  6960. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6961. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6962. {
  6963. // the child object is now guaranteed to be a <MYTAG> element..
  6964. doSomethingWithMYTAGElement (child);
  6965. }
  6966. @endcode
  6967. @see forEachXmlChildElement
  6968. */
  6969. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6970. \
  6971. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6972. childElementVariableName != 0; \
  6973. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6974. /** Used to build a tree of elements representing an XML document.
  6975. An XML document can be parsed into a tree of XmlElements, each of which
  6976. represents an XML tag structure, and which may itself contain other
  6977. nested elements.
  6978. An XmlElement can also be converted back into a text document, and has
  6979. lots of useful methods for manipulating its attributes and sub-elements,
  6980. so XmlElements can actually be used as a handy general-purpose data
  6981. structure.
  6982. Here's an example of parsing some elements: @code
  6983. // check we're looking at the right kind of document..
  6984. if (myElement->hasTagName ("ANIMALS"))
  6985. {
  6986. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6987. forEachXmlChildElement (*myElement, e)
  6988. {
  6989. if (e->hasTagName ("GIRAFFE"))
  6990. {
  6991. // found a giraffe, so use some of its attributes..
  6992. String giraffeName = e->getStringAttribute ("name");
  6993. int giraffeAge = e->getIntAttribute ("age");
  6994. bool isFriendly = e->getBoolAttribute ("friendly");
  6995. }
  6996. }
  6997. }
  6998. @endcode
  6999. And here's an example of how to create an XML document from scratch: @code
  7000. // create an outer node called "ANIMALS"
  7001. XmlElement animalsList ("ANIMALS");
  7002. for (int i = 0; i < numAnimals; ++i)
  7003. {
  7004. // create an inner element..
  7005. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7006. giraffe->setAttribute ("name", "nigel");
  7007. giraffe->setAttribute ("age", 10);
  7008. giraffe->setAttribute ("friendly", true);
  7009. // ..and add our new element to the parent node
  7010. animalsList.addChildElement (giraffe);
  7011. }
  7012. // now we can turn the whole thing into a text document..
  7013. String myXmlDoc = animalsList.createDocument (String::empty);
  7014. @endcode
  7015. @see XmlDocument
  7016. */
  7017. class JUCE_API XmlElement
  7018. {
  7019. public:
  7020. /** Creates an XmlElement with this tag name. */
  7021. XmlElement (const String& tagName) throw();
  7022. /** Creates a (deep) copy of another element. */
  7023. XmlElement (const XmlElement& other) throw();
  7024. /** Creates a (deep) copy of another element. */
  7025. const XmlElement& operator= (const XmlElement& other) throw();
  7026. /** Deleting an XmlElement will also delete all its child elements. */
  7027. ~XmlElement() throw();
  7028. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7029. The elements are only considered equivalent if they contain the same attiributes
  7030. with the same values, and have the same sub-nodes.
  7031. @param other the other element to compare to
  7032. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7033. same attributes in a different order will be
  7034. considered the same; if false, the attributes must
  7035. be in the same order as well
  7036. */
  7037. bool isEquivalentTo (const XmlElement* const other,
  7038. const bool ignoreOrderOfAttributes) const throw();
  7039. /** Returns an XML text document that represents this element.
  7040. The string returned can be parsed to recreate the same XmlElement that
  7041. was used to create it.
  7042. @param dtdToUse the DTD to add to the document
  7043. @param allOnOneLine if true, this means that the document will not contain any
  7044. linefeeds, so it'll be smaller but not very easy to read.
  7045. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7046. document
  7047. @param encodingType the character encoding format string to put into the xml
  7048. header
  7049. @param lineWrapLength the line length that will be used before items get placed on
  7050. a new line. This isn't an absolute maximum length, it just
  7051. determines how lists of attributes get broken up
  7052. @see writeToFile
  7053. */
  7054. const String createDocument (const String& dtdToUse,
  7055. const bool allOnOneLine = false,
  7056. const bool includeXmlHeader = true,
  7057. const tchar* const encodingType = JUCE_T("UTF-8"),
  7058. const int lineWrapLength = 60) const throw();
  7059. /** Writes the element to a file as an XML document.
  7060. To improve safety in case something goes wrong while writing the file, this
  7061. will actually write the document to a new temporary file in the same
  7062. directory as the destination file, and if this succeeds, it will rename this
  7063. new file as the destination file (overwriting any existing file that was there).
  7064. @param destinationFile the file to write to. If this already exists, it will be
  7065. overwritten.
  7066. @param dtdToUse the DTD to add to the document
  7067. @param encodingType the character encoding format string to put into the xml
  7068. header
  7069. @param lineWrapLength the line length that will be used before items get placed on
  7070. a new line. This isn't an absolute maximum length, it just
  7071. determines how lists of attributes get broken up
  7072. @returns true if the file is written successfully; false if something goes wrong
  7073. in the process
  7074. @see createDocument
  7075. */
  7076. bool writeToFile (const File& destinationFile,
  7077. const String& dtdToUse,
  7078. const tchar* const encodingType = JUCE_T("UTF-8"),
  7079. const int lineWrapLength = 60) const throw();
  7080. /** Returns this element's tag type name.
  7081. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7082. "MOOSE".
  7083. @see hasTagName
  7084. */
  7085. inline const String& getTagName() const throw() { return tagName; }
  7086. /** Tests whether this element has a particular tag name.
  7087. @param possibleTagName the tag name you're comparing it with
  7088. @see getTagName
  7089. */
  7090. bool hasTagName (const tchar* const possibleTagName) const throw();
  7091. /** Returns the number of XML attributes this element contains.
  7092. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7093. return 2.
  7094. */
  7095. int getNumAttributes() const throw();
  7096. /** Returns the name of one of the elements attributes.
  7097. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7098. getAttributeName(1) would return "antlers".
  7099. @see getAttributeValue, getStringAttribute
  7100. */
  7101. const String& getAttributeName (const int attributeIndex) const throw();
  7102. /** Returns the value of one of the elements attributes.
  7103. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7104. getAttributeName(1) would return "2".
  7105. @see getAttributeName, getStringAttribute
  7106. */
  7107. const String& getAttributeValue (const int attributeIndex) const throw();
  7108. // Attribute-handling methods..
  7109. /** Checks whether the element contains an attribute with a certain name. */
  7110. bool hasAttribute (const tchar* const attributeName) const throw();
  7111. /** Returns the value of a named attribute.
  7112. @param attributeName the name of the attribute to look up
  7113. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7114. with this name
  7115. */
  7116. const String getStringAttribute (const tchar* const attributeName,
  7117. const tchar* const defaultReturnValue = 0) const throw();
  7118. /** Compares the value of a named attribute with a value passed-in.
  7119. @param attributeName the name of the attribute to look up
  7120. @param stringToCompareAgainst the value to compare it with
  7121. @param ignoreCase whether the comparison should be case-insensitive
  7122. @returns true if the value of the attribute is the same as the string passed-in;
  7123. false if it's different (or if no such attribute exists)
  7124. */
  7125. bool compareAttribute (const tchar* const attributeName,
  7126. const tchar* const stringToCompareAgainst,
  7127. const bool ignoreCase = false) const throw();
  7128. /** Returns the value of a named attribute as an integer.
  7129. This will try to find the attribute and convert it to an integer (using
  7130. the String::getIntValue() method).
  7131. @param attributeName the name of the attribute to look up
  7132. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7133. with this name
  7134. @see setAttribute (const tchar* const, int)
  7135. */
  7136. int getIntAttribute (const tchar* const attributeName,
  7137. const int defaultReturnValue = 0) const throw();
  7138. /** Returns the value of a named attribute as floating-point.
  7139. This will try to find the attribute and convert it to an integer (using
  7140. the String::getDoubleValue() method).
  7141. @param attributeName the name of the attribute to look up
  7142. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7143. with this name
  7144. @see setAttribute (const tchar* const, double)
  7145. */
  7146. double getDoubleAttribute (const tchar* const attributeName,
  7147. const double defaultReturnValue = 0.0) const throw();
  7148. /** Returns the value of a named attribute as a boolean.
  7149. This will try to find the attribute and interpret it as a boolean. To do this,
  7150. it'll return true if the value is "1", "true", "y", etc, or false for other
  7151. values.
  7152. @param attributeName the name of the attribute to look up
  7153. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7154. with this name
  7155. */
  7156. bool getBoolAttribute (const tchar* const attributeName,
  7157. const bool defaultReturnValue = false) const throw();
  7158. /** Adds a named attribute to the element.
  7159. If the element already contains an attribute with this name, it's value will
  7160. be updated to the new value. If there's no such attribute yet, a new one will
  7161. be added.
  7162. Note that there are other setAttribute() methods that take integers,
  7163. doubles, etc. to make it easy to store numbers.
  7164. @param attributeName the name of the attribute to set
  7165. @param newValue the value to set it to
  7166. @see removeAttribute
  7167. */
  7168. void setAttribute (const tchar* const attributeName,
  7169. const String& newValue) throw();
  7170. /** Adds a named attribute to the element.
  7171. If the element already contains an attribute with this name, it's value will
  7172. be updated to the new value. If there's no such attribute yet, a new one will
  7173. be added.
  7174. Note that there are other setAttribute() methods that take integers,
  7175. doubles, etc. to make it easy to store numbers.
  7176. @param attributeName the name of the attribute to set
  7177. @param newValue the value to set it to
  7178. */
  7179. void setAttribute (const tchar* const attributeName,
  7180. const tchar* const newValue) throw();
  7181. /** Adds a named attribute to the element, setting it to an integer value.
  7182. If the element already contains an attribute with this name, it's value will
  7183. be updated to the new value. If there's no such attribute yet, a new one will
  7184. be added.
  7185. Note that there are other setAttribute() methods that take integers,
  7186. doubles, etc. to make it easy to store numbers.
  7187. @param attributeName the name of the attribute to set
  7188. @param newValue the value to set it to
  7189. */
  7190. void setAttribute (const tchar* const attributeName,
  7191. const int newValue) throw();
  7192. /** Adds a named attribute to the element, setting it to a floating-point value.
  7193. If the element already contains an attribute with this name, it's value will
  7194. be updated to the new value. If there's no such attribute yet, a new one will
  7195. be added.
  7196. Note that there are other setAttribute() methods that take integers,
  7197. doubles, etc. to make it easy to store numbers.
  7198. @param attributeName the name of the attribute to set
  7199. @param newValue the value to set it to
  7200. */
  7201. void setAttribute (const tchar* const attributeName,
  7202. const double newValue) throw();
  7203. /** Removes a named attribute from the element.
  7204. @param attributeName the name of the attribute to remove
  7205. @see removeAllAttributes
  7206. */
  7207. void removeAttribute (const tchar* const attributeName) throw();
  7208. /** Removes all attributes from this element.
  7209. */
  7210. void removeAllAttributes() throw();
  7211. // Child element methods..
  7212. /** Returns the first of this element's sub-elements.
  7213. see getNextElement() for an example of how to iterate the sub-elements.
  7214. @see forEachXmlChildElement
  7215. */
  7216. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7217. /** Returns the next of this element's siblings.
  7218. This can be used for iterating an element's sub-elements, e.g.
  7219. @code
  7220. XmlElement* child = myXmlDocument->getFirstChildElement();
  7221. while (child != 0)
  7222. {
  7223. ...do stuff with this child..
  7224. child = child->getNextElement();
  7225. }
  7226. @endcode
  7227. Note that when iterating the child elements, some of them might be
  7228. text elements as well as XML tags - use isTextElement() to work this
  7229. out.
  7230. Also, it's much easier and neater to use this method indirectly via the
  7231. forEachXmlChildElement macro.
  7232. @returns the sibling element that follows this one, or zero if this is the last
  7233. element in its parent
  7234. @see getNextElement, isTextElement, forEachXmlChildElement
  7235. */
  7236. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7237. /** Returns the next of this element's siblings which has the specified tag
  7238. name.
  7239. This is like getNextElement(), but will scan through the list until it
  7240. finds an element with the given tag name.
  7241. @see getNextElement, forEachXmlChildElementWithTagName
  7242. */
  7243. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  7244. /** Returns the number of sub-elements in this element.
  7245. @see getChildElement
  7246. */
  7247. int getNumChildElements() const throw();
  7248. /** Returns the sub-element at a certain index.
  7249. It's not very efficient to iterate the sub-elements by index - see
  7250. getNextElement() for an example of how best to iterate.
  7251. @returns the n'th child of this element, or 0 if the index is out-of-range
  7252. @see getNextElement, isTextElement, getChildByName
  7253. */
  7254. XmlElement* getChildElement (const int index) const throw();
  7255. /** Returns the first sub-element with a given tag-name.
  7256. @param tagNameToLookFor the tag name of the element you want to find
  7257. @returns the first element with this tag name, or 0 if none is found
  7258. @see getNextElement, isTextElement, getChildElement
  7259. */
  7260. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  7261. /** Appends an element to this element's list of children.
  7262. Child elements are deleted automatically when their parent is deleted, so
  7263. make sure the object that you pass in will not be deleted by anything else,
  7264. and make sure it's not already the child of another element.
  7265. @see getFirstChildElement, getNextElement, getNumChildElements,
  7266. getChildElement, removeChildElement
  7267. */
  7268. void addChildElement (XmlElement* const newChildElement) throw();
  7269. /** Inserts an element into this element's list of children.
  7270. Child elements are deleted automatically when their parent is deleted, so
  7271. make sure the object that you pass in will not be deleted by anything else,
  7272. and make sure it's not already the child of another element.
  7273. @param newChildNode the element to add
  7274. @param indexToInsertAt the index at which to insert the new element - if this is
  7275. below zero, it will be added to the end of the list
  7276. @see addChildElement, insertChildElement
  7277. */
  7278. void insertChildElement (XmlElement* const newChildNode,
  7279. int indexToInsertAt) throw();
  7280. /** Replaces one of this element's children with another node.
  7281. If the current element passed-in isn't actually a child of this element,
  7282. this will return false and the new one won't be added. Otherwise, the
  7283. existing element will be deleted, replaced with the new one, and it
  7284. will return true.
  7285. */
  7286. bool replaceChildElement (XmlElement* const currentChildElement,
  7287. XmlElement* const newChildNode) throw();
  7288. /** Removes a child element.
  7289. @param childToRemove the child to look for and remove
  7290. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7291. just remove it
  7292. */
  7293. void removeChildElement (XmlElement* const childToRemove,
  7294. const bool shouldDeleteTheChild) throw();
  7295. /** Deletes all the child elements in the element.
  7296. @see removeChildElement, deleteAllChildElementsWithTagName
  7297. */
  7298. void deleteAllChildElements() throw();
  7299. /** Deletes all the child elements with a given tag name.
  7300. @see removeChildElement
  7301. */
  7302. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  7303. /** Returns true if the given element is a child of this one. */
  7304. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7305. /** Recursively searches all sub-elements to find one that contains the specified
  7306. child element.
  7307. */
  7308. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  7309. /** Sorts the child elements using a comparator.
  7310. This will use a comparator object to sort the elements into order. The object
  7311. passed must have a method of the form:
  7312. @code
  7313. int compareElements (const XmlElement* first, const XmlElement* second);
  7314. @endcode
  7315. ..and this method must return:
  7316. - a value of < 0 if the first comes before the second
  7317. - a value of 0 if the two objects are equivalent
  7318. - a value of > 0 if the second comes before the first
  7319. To improve performance, the compareElements() method can be declared as static or const.
  7320. @param comparator the comparator to use for comparing elements.
  7321. @param retainOrderOfEquivalentItems if this is true, then items
  7322. which the comparator says are equivalent will be
  7323. kept in the order in which they currently appear
  7324. in the array. This is slower to perform, but may
  7325. be important in some cases. If it's false, a faster
  7326. algorithm is used, but equivalent elements may be
  7327. rearranged.
  7328. */
  7329. template <class ElementComparator>
  7330. void sortChildElements (ElementComparator& comparator,
  7331. const bool retainOrderOfEquivalentItems = false) throw()
  7332. {
  7333. const int num = getNumChildElements();
  7334. if (num > 1)
  7335. {
  7336. XmlElement** const elems = getChildElementsAsArray (num);
  7337. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  7338. reorderChildElements (elems, num);
  7339. delete[] elems;
  7340. }
  7341. }
  7342. /** Returns true if this element is a section of text.
  7343. Elements can either be an XML tag element or a secton of text, so this
  7344. is used to find out what kind of element this one is.
  7345. @see getAllText, addTextElement, deleteAllTextElements
  7346. */
  7347. bool isTextElement() const throw();
  7348. /** Returns the text for a text element.
  7349. Note that if you have an element like this:
  7350. @code<xyz>hello</xyz>@endcode
  7351. then calling getText on the "xyz" element won't return "hello", because that is
  7352. actually stored in a special text sub-element inside the xyz element. To get the
  7353. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7354. use getAllSubText() to do this automatically.
  7355. @see isTextElement, getAllSubText, getChildElementAllSubText
  7356. */
  7357. const String getText() const throw();
  7358. /** Sets the text in a text element.
  7359. Note that this is only a valid call if this element is a text element. If it's
  7360. not, then no action will be performed.
  7361. */
  7362. void setText (const String& newText) throw();
  7363. /** Returns all the text from this element's child nodes.
  7364. This iterates all the child elements and when it finds text elements,
  7365. it concatenates their text into a big string which it returns.
  7366. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7367. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7368. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7369. */
  7370. const String getAllSubText() const throw();
  7371. /** Returns all the sub-text of a named child element.
  7372. If there is a child element with the given tag name, this will return
  7373. all of its sub-text (by calling getAllSubText() on it). If there is
  7374. no such child element, this will return the default string passed-in.
  7375. @see getAllSubText
  7376. */
  7377. const String getChildElementAllSubText (const tchar* const childTagName,
  7378. const String& defaultReturnValue) const throw();
  7379. /** Appends a section of text to this element.
  7380. @see isTextElement, getText, getAllSubText
  7381. */
  7382. void addTextElement (const String& text) throw();
  7383. /** Removes all the text elements from this element.
  7384. @see isTextElement, getText, getAllSubText, addTextElement
  7385. */
  7386. void deleteAllTextElements() throw();
  7387. /** Creates a text element that can be added to a parent element.
  7388. */
  7389. static XmlElement* createTextElement (const String& text) throw();
  7390. juce_UseDebuggingNewOperator
  7391. private:
  7392. friend class XmlDocument;
  7393. String tagName;
  7394. XmlElement* firstChildElement;
  7395. XmlElement* nextElement;
  7396. struct XmlAttributeNode
  7397. {
  7398. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7399. XmlAttributeNode (const String& name, const String& value) throw();
  7400. String name, value;
  7401. XmlAttributeNode* next;
  7402. };
  7403. XmlAttributeNode* attributes;
  7404. XmlElement (int) throw(); // for internal use
  7405. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  7406. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  7407. void writeElementAsText (OutputStream& out,
  7408. const int indentationLevel,
  7409. const int lineWrapLength) const throw();
  7410. XmlElement** getChildElementsAsArray (const int) const throw();
  7411. void reorderChildElements (XmlElement** const, const int) throw();
  7412. };
  7413. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7414. /********* End of inlined file: juce_XmlElement.h *********/
  7415. /**
  7416. A set of named property values, which can be strings, integers, floating point, etc.
  7417. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7418. to load and save types other than strings.
  7419. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7420. messages and saves/loads the list from a file.
  7421. */
  7422. class JUCE_API PropertySet
  7423. {
  7424. public:
  7425. /** Creates an empty PropertySet.
  7426. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7427. case-insensitive way
  7428. */
  7429. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7430. /** Creates a copy of another PropertySet.
  7431. */
  7432. PropertySet (const PropertySet& other) throw();
  7433. /** Copies another PropertySet over this one.
  7434. */
  7435. const PropertySet& operator= (const PropertySet& other) throw();
  7436. /** Destructor. */
  7437. virtual ~PropertySet();
  7438. /** Returns one of the properties as a string.
  7439. If the value isn't found in this set, then this will look for it in a fallback
  7440. property set (if you've specified one with the setFallbackPropertySet() method),
  7441. and if it can't find one there, it'll return the default value passed-in.
  7442. @param keyName the name of the property to retrieve
  7443. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7444. */
  7445. const String getValue (const String& keyName,
  7446. const String& defaultReturnValue = String::empty) const throw();
  7447. /** Returns one of the properties as an integer.
  7448. If the value isn't found in this set, then this will look for it in a fallback
  7449. property set (if you've specified one with the setFallbackPropertySet() method),
  7450. and if it can't find one there, it'll return the default value passed-in.
  7451. @param keyName the name of the property to retrieve
  7452. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7453. */
  7454. int getIntValue (const String& keyName,
  7455. const int defaultReturnValue = 0) const throw();
  7456. /** Returns one of the properties as an double.
  7457. If the value isn't found in this set, then this will look for it in a fallback
  7458. property set (if you've specified one with the setFallbackPropertySet() method),
  7459. and if it can't find one there, it'll return the default value passed-in.
  7460. @param keyName the name of the property to retrieve
  7461. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7462. */
  7463. double getDoubleValue (const String& keyName,
  7464. const double defaultReturnValue = 0.0) const throw();
  7465. /** Returns one of the properties as an boolean.
  7466. The result will be true if the string found for this key name can be parsed as a non-zero
  7467. integer.
  7468. If the value isn't found in this set, then this will look for it in a fallback
  7469. property set (if you've specified one with the setFallbackPropertySet() method),
  7470. and if it can't find one there, it'll return the default value passed-in.
  7471. @param keyName the name of the property to retrieve
  7472. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7473. */
  7474. bool getBoolValue (const String& keyName,
  7475. const bool defaultReturnValue = false) const throw();
  7476. /** Returns one of the properties as an XML element.
  7477. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7478. key isn't found, or if the entry contains an string that isn't valid XML.
  7479. If the value isn't found in this set, then this will look for it in a fallback
  7480. property set (if you've specified one with the setFallbackPropertySet() method),
  7481. and if it can't find one there, it'll return the default value passed-in.
  7482. @param keyName the name of the property to retrieve
  7483. */
  7484. XmlElement* getXmlValue (const String& keyName) const;
  7485. /** Sets a named property as a string.
  7486. @param keyName the name of the property to set. (This mustn't be an empty string)
  7487. @param value the new value to set it to
  7488. */
  7489. void setValue (const String& keyName, const String& value) throw();
  7490. /** Sets a named property as a string.
  7491. @param keyName the name of the property to set. (This mustn't be an empty string)
  7492. @param value the new value to set it to
  7493. */
  7494. void setValue (const String& keyName, const tchar* const value) throw();
  7495. /** Sets a named property to an integer.
  7496. @param keyName the name of the property to set. (This mustn't be an empty string)
  7497. @param value the new value to set it to
  7498. */
  7499. void setValue (const String& keyName, const int value) throw();
  7500. /** Sets a named property to a double.
  7501. @param keyName the name of the property to set. (This mustn't be an empty string)
  7502. @param value the new value to set it to
  7503. */
  7504. void setValue (const String& keyName, const double value) throw();
  7505. /** Sets a named property to a boolean.
  7506. @param keyName the name of the property to set. (This mustn't be an empty string)
  7507. @param value the new value to set it to
  7508. */
  7509. void setValue (const String& keyName, const bool value) throw();
  7510. /** Sets a named property to an XML element.
  7511. @param keyName the name of the property to set. (This mustn't be an empty string)
  7512. @param xml the new element to set it to. If this is zero, the value will be set to
  7513. an empty string
  7514. @see getXmlValue
  7515. */
  7516. void setValue (const String& keyName, const XmlElement* const xml);
  7517. /** Deletes a property.
  7518. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7519. */
  7520. void removeValue (const String& keyName) throw();
  7521. /** Returns true if the properies include the given key. */
  7522. bool containsKey (const String& keyName) const throw();
  7523. /** Removes all values. */
  7524. void clear();
  7525. /** Returns the keys/value pair array containing all the properties. */
  7526. StringPairArray& getAllProperties() throw() { return properties; }
  7527. /** Returns the lock used when reading or writing to this set */
  7528. const CriticalSection& getLock() const throw() { return lock; }
  7529. /** Returns an XML element which encapsulates all the items in this property set.
  7530. The string parameter is the tag name that should be used for the node.
  7531. @see restoreFromXml
  7532. */
  7533. XmlElement* createXml (const String& nodeName) const throw();
  7534. /** Reloads a set of properties that were previously stored as XML.
  7535. The node passed in must have been created by the createXml() method.
  7536. @see createXml
  7537. */
  7538. void restoreFromXml (const XmlElement& xml) throw();
  7539. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7540. set in this one.
  7541. If you set this up to be a pointer to a second property set, then whenever one
  7542. of the getValue() methods fails to find an entry in this set, it will look up that
  7543. value in the fallback set, and if it finds it, it will return that.
  7544. Make sure that you don't delete the fallback set while it's still being used by
  7545. another set! To remove the fallback set, just call this method with a null pointer.
  7546. @see getFallbackPropertySet
  7547. */
  7548. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7549. /** Returns the fallback property set.
  7550. @see setFallbackPropertySet
  7551. */
  7552. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7553. juce_UseDebuggingNewOperator
  7554. protected:
  7555. /** Subclasses can override this to be told when one of the properies has been changed.
  7556. */
  7557. virtual void propertyChanged();
  7558. private:
  7559. StringPairArray properties;
  7560. PropertySet* fallbackProperties;
  7561. CriticalSection lock;
  7562. bool ignoreCaseOfKeys;
  7563. };
  7564. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7565. /********* End of inlined file: juce_PropertySet.h *********/
  7566. #endif
  7567. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7568. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7569. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7570. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7571. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7572. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7573. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7574. /**
  7575. Adds reference-counting to an object.
  7576. To add reference-counting to a class, derive it from this class, and
  7577. use the ReferenceCountedObjectPtr class to point to it.
  7578. e.g. @code
  7579. class MyClass : public ReferenceCountedObject
  7580. {
  7581. void foo();
  7582. // This is a neat way of declaring a typedef for a pointer class,
  7583. // rather than typing out the full templated name each time..
  7584. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7585. };
  7586. MyClass::Ptr p = new MyClass();
  7587. MyClass::Ptr p2 = p;
  7588. p = 0;
  7589. p2->foo();
  7590. @endcode
  7591. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7592. careful not to delete the object manually.
  7593. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7594. */
  7595. class JUCE_API ReferenceCountedObject
  7596. {
  7597. public:
  7598. /** Increments the object's reference count.
  7599. This is done automatically by the smart pointer, but is public just
  7600. in case it's needed for nefarious purposes.
  7601. */
  7602. inline void incReferenceCount() throw()
  7603. {
  7604. atomicIncrement (refCounts);
  7605. jassert (refCounts > 0);
  7606. }
  7607. /** Decreases the object's reference count.
  7608. If the count gets to zero, the object will be deleted.
  7609. */
  7610. inline void decReferenceCount() throw()
  7611. {
  7612. jassert (refCounts > 0);
  7613. if (atomicDecrementAndReturn (refCounts) == 0)
  7614. delete this;
  7615. }
  7616. /** Returns the object's current reference count. */
  7617. inline int getReferenceCount() const throw()
  7618. {
  7619. return refCounts;
  7620. }
  7621. protected:
  7622. /** Creates the reference-counted object (with an initial ref count of zero). */
  7623. ReferenceCountedObject()
  7624. : refCounts (0)
  7625. {
  7626. }
  7627. /** Destructor. */
  7628. virtual ~ReferenceCountedObject()
  7629. {
  7630. // it's dangerous to delete an object that's still referenced by something else!
  7631. jassert (refCounts == 0);
  7632. }
  7633. private:
  7634. int refCounts;
  7635. };
  7636. /**
  7637. Used to point to an object of type ReferenceCountedObject.
  7638. It's wise to use a typedef instead of typing out the templated name
  7639. each time - e.g.
  7640. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7641. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7642. */
  7643. template <class ReferenceCountedObjectClass>
  7644. class ReferenceCountedObjectPtr
  7645. {
  7646. public:
  7647. /** Creates a pointer to a null object. */
  7648. inline ReferenceCountedObjectPtr() throw()
  7649. : referencedObject (0)
  7650. {
  7651. }
  7652. /** Creates a pointer to an object.
  7653. This will increment the object's reference-count if it is non-null.
  7654. */
  7655. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7656. : referencedObject (refCountedObject)
  7657. {
  7658. if (refCountedObject != 0)
  7659. refCountedObject->incReferenceCount();
  7660. }
  7661. /** Copies another pointer.
  7662. This will increment the object's reference-count (if it is non-null).
  7663. */
  7664. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7665. : referencedObject (other.referencedObject)
  7666. {
  7667. if (referencedObject != 0)
  7668. referencedObject->incReferenceCount();
  7669. }
  7670. /** Changes this pointer to point at a different object.
  7671. The reference count of the old object is decremented, and it might be
  7672. deleted if it hits zero. The new object's count is incremented.
  7673. */
  7674. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7675. {
  7676. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7677. if (newObject != referencedObject)
  7678. {
  7679. if (newObject != 0)
  7680. newObject->incReferenceCount();
  7681. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7682. referencedObject = newObject;
  7683. if (oldObject != 0)
  7684. oldObject->decReferenceCount();
  7685. }
  7686. return *this;
  7687. }
  7688. /** Changes this pointer to point at a different object.
  7689. The reference count of the old object is decremented, and it might be
  7690. deleted if it hits zero. The new object's count is incremented.
  7691. */
  7692. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7693. {
  7694. if (referencedObject != newObject)
  7695. {
  7696. if (newObject != 0)
  7697. newObject->incReferenceCount();
  7698. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7699. referencedObject = newObject;
  7700. if (oldObject != 0)
  7701. oldObject->decReferenceCount();
  7702. }
  7703. return *this;
  7704. }
  7705. /** Destructor.
  7706. This will decrement the object's reference-count, and may delete it if it
  7707. gets to zero.
  7708. */
  7709. inline ~ReferenceCountedObjectPtr()
  7710. {
  7711. if (referencedObject != 0)
  7712. referencedObject->decReferenceCount();
  7713. }
  7714. /** Returns the object that this pointer references.
  7715. The pointer returned may be zero, of course.
  7716. */
  7717. inline operator ReferenceCountedObjectClass*() const throw()
  7718. {
  7719. return referencedObject;
  7720. }
  7721. /** Returns true if this pointer refers to the given object. */
  7722. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7723. {
  7724. return referencedObject == object;
  7725. }
  7726. /** Returns true if this pointer doesn't refer to the given object. */
  7727. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7728. {
  7729. return referencedObject != object;
  7730. }
  7731. // the -> operator is called on the referenced object
  7732. inline ReferenceCountedObjectClass* operator->() const throw()
  7733. {
  7734. return referencedObject;
  7735. }
  7736. private:
  7737. ReferenceCountedObjectClass* referencedObject;
  7738. };
  7739. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7740. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7741. /**
  7742. Holds a list of objects derived from ReferenceCountedObject.
  7743. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7744. and takes care of incrementing and decrementing their ref counts when they
  7745. are added and removed from the array.
  7746. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7747. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7748. @see Array, OwnedArray, StringArray
  7749. */
  7750. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7751. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7752. {
  7753. public:
  7754. /** Creates an empty array.
  7755. @param granularity this is the size of increment by which the internal storage
  7756. used by the array will grow. Only change it from the default if you know the
  7757. array is going to be very big and needs to be able to grow efficiently.
  7758. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7759. */
  7760. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7761. : ArrayAllocationBase <ObjectClass*> (granularity),
  7762. numUsed (0)
  7763. {
  7764. }
  7765. /** Creates a copy of another array */
  7766. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7767. : ArrayAllocationBase <ObjectClass*> (other.granularity)
  7768. {
  7769. other.lockArray();
  7770. numUsed = other.numUsed;
  7771. this->setAllocatedSize (numUsed);
  7772. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7773. for (int i = numUsed; --i >= 0;)
  7774. if (this->elements[i] != 0)
  7775. this->elements[i]->incReferenceCount();
  7776. other.unlockArray();
  7777. }
  7778. /** Copies another array into this one.
  7779. Any existing objects in this array will first be released.
  7780. */
  7781. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7782. {
  7783. if (this != &other)
  7784. {
  7785. other.lockArray();
  7786. lock.enter();
  7787. clear();
  7788. this->granularity = other.granularity;
  7789. this->ensureAllocatedSize (other.numUsed);
  7790. numUsed = other.numUsed;
  7791. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7792. minimiseStorageOverheads();
  7793. for (int i = numUsed; --i >= 0;)
  7794. if (this->elements[i] != 0)
  7795. this->elements[i]->incReferenceCount();
  7796. lock.exit();
  7797. other.unlockArray();
  7798. }
  7799. return *this;
  7800. }
  7801. /** Destructor.
  7802. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7803. */
  7804. ~ReferenceCountedArray()
  7805. {
  7806. clear();
  7807. }
  7808. /** Removes all objects from the array.
  7809. Any objects in the array that are not referenced from elsewhere will be deleted.
  7810. */
  7811. void clear()
  7812. {
  7813. lock.enter();
  7814. while (numUsed > 0)
  7815. if (this->elements [--numUsed] != 0)
  7816. this->elements [numUsed]->decReferenceCount();
  7817. jassert (numUsed == 0);
  7818. this->setAllocatedSize (0);
  7819. lock.exit();
  7820. }
  7821. /** Returns the current number of objects in the array. */
  7822. inline int size() const throw()
  7823. {
  7824. return numUsed;
  7825. }
  7826. /** Returns a pointer to the object at this index in the array.
  7827. If the index is out-of-range, this will return a null pointer, (and
  7828. it could be null anyway, because it's ok for the array to hold null
  7829. pointers as well as objects).
  7830. @see getUnchecked
  7831. */
  7832. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7833. {
  7834. lock.enter();
  7835. const ReferenceCountedObjectPtr<ObjectClass> result ((((unsigned int) index) < (unsigned int) numUsed)
  7836. ? this->elements [index]
  7837. : (ObjectClass*) 0);
  7838. lock.exit();
  7839. return result;
  7840. }
  7841. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7842. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7843. it can be used when you're sure the index if always going to be legal.
  7844. */
  7845. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7846. {
  7847. lock.enter();
  7848. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7849. const ReferenceCountedObjectPtr<ObjectClass> result (this->elements [index]);
  7850. lock.exit();
  7851. return result;
  7852. }
  7853. /** Returns a pointer to the first object in the array.
  7854. This will return a null pointer if the array's empty.
  7855. @see getLast
  7856. */
  7857. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7858. {
  7859. lock.enter();
  7860. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? this->elements [0]
  7861. : (ObjectClass*) 0);
  7862. lock.exit();
  7863. return result;
  7864. }
  7865. /** Returns a pointer to the last object in the array.
  7866. This will return a null pointer if the array's empty.
  7867. @see getFirst
  7868. */
  7869. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7870. {
  7871. lock.enter();
  7872. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? this->elements [numUsed - 1]
  7873. : (ObjectClass*) 0);
  7874. lock.exit();
  7875. return result;
  7876. }
  7877. /** Finds the index of the first occurrence of an object in the array.
  7878. @param objectToLookFor the object to look for
  7879. @returns the index at which the object was found, or -1 if it's not found
  7880. */
  7881. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7882. {
  7883. int result = -1;
  7884. lock.enter();
  7885. ObjectClass** e = this->elements;
  7886. for (int i = numUsed; --i >= 0;)
  7887. {
  7888. if (objectToLookFor == *e)
  7889. {
  7890. result = (int) (e - this->elements);
  7891. break;
  7892. }
  7893. ++e;
  7894. }
  7895. lock.exit();
  7896. return result;
  7897. }
  7898. /** Returns true if the array contains a specified object.
  7899. @param objectToLookFor the object to look for
  7900. @returns true if the object is in the array
  7901. */
  7902. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7903. {
  7904. lock.enter();
  7905. ObjectClass** e = this->elements;
  7906. for (int i = numUsed; --i >= 0;)
  7907. {
  7908. if (objectToLookFor == *e)
  7909. {
  7910. lock.exit();
  7911. return true;
  7912. }
  7913. ++e;
  7914. }
  7915. lock.exit();
  7916. return false;
  7917. }
  7918. /** Appends a new object to the end of the array.
  7919. This will increase the new object's reference count.
  7920. @param newObject the new object to add to the array
  7921. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7922. */
  7923. void add (ObjectClass* const newObject) throw()
  7924. {
  7925. lock.enter();
  7926. this->ensureAllocatedSize (numUsed + 1);
  7927. this->elements [numUsed++] = newObject;
  7928. if (newObject != 0)
  7929. newObject->incReferenceCount();
  7930. lock.exit();
  7931. }
  7932. /** Inserts a new object into the array at the given index.
  7933. If the index is less than 0 or greater than the size of the array, the
  7934. element will be added to the end of the array.
  7935. Otherwise, it will be inserted into the array, moving all the later elements
  7936. along to make room.
  7937. This will increase the new object's reference count.
  7938. @param indexToInsertAt the index at which the new element should be inserted
  7939. @param newObject the new object to add to the array
  7940. @see add, addSorted, addIfNotAlreadyThere, set
  7941. */
  7942. void insert (int indexToInsertAt,
  7943. ObjectClass* const newObject) throw()
  7944. {
  7945. if (indexToInsertAt >= 0)
  7946. {
  7947. lock.enter();
  7948. if (indexToInsertAt > numUsed)
  7949. indexToInsertAt = numUsed;
  7950. this->ensureAllocatedSize (numUsed + 1);
  7951. ObjectClass** const e = this->elements + indexToInsertAt;
  7952. const int numToMove = numUsed - indexToInsertAt;
  7953. if (numToMove > 0)
  7954. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7955. *e = newObject;
  7956. if (newObject != 0)
  7957. newObject->incReferenceCount();
  7958. ++numUsed;
  7959. lock.exit();
  7960. }
  7961. else
  7962. {
  7963. add (newObject);
  7964. }
  7965. }
  7966. /** Appends a new object at the end of the array as long as the array doesn't
  7967. already contain it.
  7968. If the array already contains a matching object, nothing will be done.
  7969. @param newObject the new object to add to the array
  7970. */
  7971. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7972. {
  7973. lock.enter();
  7974. if (! contains (newObject))
  7975. add (newObject);
  7976. lock.exit();
  7977. }
  7978. /** Replaces an object in the array with a different one.
  7979. If the index is less than zero, this method does nothing.
  7980. If the index is beyond the end of the array, the new object is added to the end of the array.
  7981. The object being added has its reference count increased, and if it's replacing
  7982. another object, then that one has its reference count decreased, and may be deleted.
  7983. @param indexToChange the index whose value you want to change
  7984. @param newObject the new value to set for this index.
  7985. @see add, insert, remove
  7986. */
  7987. void set (const int indexToChange,
  7988. ObjectClass* const newObject)
  7989. {
  7990. if (indexToChange >= 0)
  7991. {
  7992. lock.enter();
  7993. if (newObject != 0)
  7994. newObject->incReferenceCount();
  7995. if (indexToChange < numUsed)
  7996. {
  7997. if (this->elements [indexToChange] != 0)
  7998. this->elements [indexToChange]->decReferenceCount();
  7999. this->elements [indexToChange] = newObject;
  8000. }
  8001. else
  8002. {
  8003. this->ensureAllocatedSize (numUsed + 1);
  8004. this->elements [numUsed++] = newObject;
  8005. }
  8006. lock.exit();
  8007. }
  8008. }
  8009. /** Adds elements from another array to the end of this array.
  8010. @param arrayToAddFrom the array from which to copy the elements
  8011. @param startIndex the first element of the other array to start copying from
  8012. @param numElementsToAdd how many elements to add from the other array. If this
  8013. value is negative or greater than the number of available elements,
  8014. all available elements will be copied.
  8015. @see add
  8016. */
  8017. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8018. int startIndex = 0,
  8019. int numElementsToAdd = -1) throw()
  8020. {
  8021. arrayToAddFrom.lockArray();
  8022. lock.enter();
  8023. if (startIndex < 0)
  8024. {
  8025. jassertfalse
  8026. startIndex = 0;
  8027. }
  8028. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8029. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8030. if (numElementsToAdd > 0)
  8031. {
  8032. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  8033. while (--numElementsToAdd >= 0)
  8034. add (arrayToAddFrom.getUnchecked (startIndex++));
  8035. }
  8036. lock.exit();
  8037. arrayToAddFrom.unlockArray();
  8038. }
  8039. /** Inserts a new object into the array assuming that the array is sorted.
  8040. This will use a comparator to find the position at which the new object
  8041. should go. If the array isn't sorted, the behaviour of this
  8042. method will be unpredictable.
  8043. @param comparator the comparator object to use to compare the elements - see the
  8044. sort() method for details about this object's form
  8045. @param newObject the new object to insert to the array
  8046. @see add, sort
  8047. */
  8048. template <class ElementComparator>
  8049. void addSorted (ElementComparator& comparator,
  8050. ObjectClass* newObject) throw()
  8051. {
  8052. lock.enter();
  8053. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  8054. lock.exit();
  8055. }
  8056. /** Inserts or replaces an object in the array, assuming it is sorted.
  8057. This is similar to addSorted, but if a matching element already exists, then it will be
  8058. replaced by the new one, rather than the new one being added as well.
  8059. */
  8060. template <class ElementComparator>
  8061. void addOrReplaceSorted (ElementComparator& comparator,
  8062. ObjectClass* newObject) throw()
  8063. {
  8064. lock.enter();
  8065. const int index = findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed);
  8066. if (index > 0 && comparator.compareElements (newObject, this->elements [index - 1]) == 0)
  8067. set (index - 1, newObject); // replace an existing object that matches
  8068. else
  8069. insert (index, newObject); // no match, so insert the new one
  8070. lock.exit();
  8071. }
  8072. /** Removes an object from the array.
  8073. This will remove the object at a given index and move back all the
  8074. subsequent objects to close the gap.
  8075. If the index passed in is out-of-range, nothing will happen.
  8076. The object that is removed will have its reference count decreased,
  8077. and may be deleted if not referenced from elsewhere.
  8078. @param indexToRemove the index of the element to remove
  8079. @see removeObject, removeRange
  8080. */
  8081. void remove (const int indexToRemove)
  8082. {
  8083. lock.enter();
  8084. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8085. {
  8086. ObjectClass** const e = this->elements + indexToRemove;
  8087. if (*e != 0)
  8088. (*e)->decReferenceCount();
  8089. --numUsed;
  8090. const int numberToShift = numUsed - indexToRemove;
  8091. if (numberToShift > 0)
  8092. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8093. if ((numUsed << 1) < this->numAllocated)
  8094. minimiseStorageOverheads();
  8095. }
  8096. lock.exit();
  8097. }
  8098. /** Removes the first occurrence of a specified object from the array.
  8099. If the item isn't found, no action is taken. If it is found, it is
  8100. removed and has its reference count decreased.
  8101. @param objectToRemove the object to try to remove
  8102. @see remove, removeRange
  8103. */
  8104. void removeObject (ObjectClass* const objectToRemove)
  8105. {
  8106. lock.enter();
  8107. remove (indexOf (objectToRemove));
  8108. lock.exit();
  8109. }
  8110. /** Removes a range of objects from the array.
  8111. This will remove a set of objects, starting from the given index,
  8112. and move any subsequent elements down to close the gap.
  8113. If the range extends beyond the bounds of the array, it will
  8114. be safely clipped to the size of the array.
  8115. The objects that are removed will have their reference counts decreased,
  8116. and may be deleted if not referenced from elsewhere.
  8117. @param startIndex the index of the first object to remove
  8118. @param numberToRemove how many objects should be removed
  8119. @see remove, removeObject
  8120. */
  8121. void removeRange (const int startIndex,
  8122. const int numberToRemove)
  8123. {
  8124. lock.enter();
  8125. const int start = jlimit (0, numUsed, startIndex);
  8126. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8127. if (end > start)
  8128. {
  8129. int i;
  8130. for (i = start; i < end; ++i)
  8131. {
  8132. if (this->elements[i] != 0)
  8133. {
  8134. this->elements[i]->decReferenceCount();
  8135. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8136. }
  8137. }
  8138. const int rangeSize = end - start;
  8139. ObjectClass** e = this->elements + start;
  8140. i = numUsed - end;
  8141. numUsed -= rangeSize;
  8142. while (--i >= 0)
  8143. {
  8144. *e = e [rangeSize];
  8145. ++e;
  8146. }
  8147. if ((numUsed << 1) < this->numAllocated)
  8148. minimiseStorageOverheads();
  8149. }
  8150. lock.exit();
  8151. }
  8152. /** Removes the last n objects from the array.
  8153. The objects that are removed will have their reference counts decreased,
  8154. and may be deleted if not referenced from elsewhere.
  8155. @param howManyToRemove how many objects to remove from the end of the array
  8156. @see remove, removeObject, removeRange
  8157. */
  8158. void removeLast (int howManyToRemove = 1)
  8159. {
  8160. lock.enter();
  8161. if (howManyToRemove > numUsed)
  8162. howManyToRemove = numUsed;
  8163. while (--howManyToRemove >= 0)
  8164. remove (numUsed - 1);
  8165. lock.exit();
  8166. }
  8167. /** Swaps a pair of objects in the array.
  8168. If either of the indexes passed in is out-of-range, nothing will happen,
  8169. otherwise the two objects at these positions will be exchanged.
  8170. */
  8171. void swap (const int index1,
  8172. const int index2) throw()
  8173. {
  8174. lock.enter();
  8175. if (((unsigned int) index1) < (unsigned int) numUsed
  8176. && ((unsigned int) index2) < (unsigned int) numUsed)
  8177. {
  8178. swapVariables (this->elements [index1],
  8179. this->elements [index2]);
  8180. }
  8181. lock.exit();
  8182. }
  8183. /** Moves one of the objects to a different position.
  8184. This will move the object to a specified index, shuffling along
  8185. any intervening elements as required.
  8186. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8187. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8188. @param currentIndex the index of the object to be moved. If this isn't a
  8189. valid index, then nothing will be done
  8190. @param newIndex the index at which you'd like this object to end up. If this
  8191. is less than zero, it will be moved to the end of the array
  8192. */
  8193. void move (const int currentIndex,
  8194. int newIndex) throw()
  8195. {
  8196. if (currentIndex != newIndex)
  8197. {
  8198. lock.enter();
  8199. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8200. {
  8201. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8202. newIndex = numUsed - 1;
  8203. ObjectClass* const value = this->elements [currentIndex];
  8204. if (newIndex > currentIndex)
  8205. {
  8206. memmove (this->elements + currentIndex,
  8207. this->elements + currentIndex + 1,
  8208. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8209. }
  8210. else
  8211. {
  8212. memmove (this->elements + newIndex + 1,
  8213. this->elements + newIndex,
  8214. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8215. }
  8216. this->elements [newIndex] = value;
  8217. }
  8218. lock.exit();
  8219. }
  8220. }
  8221. /** Compares this array to another one.
  8222. @returns true only if the other array contains the same objects in the same order
  8223. */
  8224. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8225. {
  8226. other.lockArray();
  8227. lock.enter();
  8228. bool result = numUsed == other.numUsed;
  8229. if (result)
  8230. {
  8231. for (int i = numUsed; --i >= 0;)
  8232. {
  8233. if (this->elements [i] != other.elements [i])
  8234. {
  8235. result = false;
  8236. break;
  8237. }
  8238. }
  8239. }
  8240. lock.exit();
  8241. other.unlockArray();
  8242. return result;
  8243. }
  8244. /** Compares this array to another one.
  8245. @see operator==
  8246. */
  8247. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8248. {
  8249. return ! operator== (other);
  8250. }
  8251. /** Sorts the elements in the array.
  8252. This will use a comparator object to sort the elements into order. The object
  8253. passed must have a method of the form:
  8254. @code
  8255. int compareElements (ElementType first, ElementType second);
  8256. @endcode
  8257. ..and this method must return:
  8258. - a value of < 0 if the first comes before the second
  8259. - a value of 0 if the two objects are equivalent
  8260. - a value of > 0 if the second comes before the first
  8261. To improve performance, the compareElements() method can be declared as static or const.
  8262. @param comparator the comparator to use for comparing elements.
  8263. @param retainOrderOfEquivalentItems if this is true, then items
  8264. which the comparator says are equivalent will be
  8265. kept in the order in which they currently appear
  8266. in the array. This is slower to perform, but may
  8267. be important in some cases. If it's false, a faster
  8268. algorithm is used, but equivalent elements may be
  8269. rearranged.
  8270. @see sortArray
  8271. */
  8272. template <class ElementComparator>
  8273. void sort (ElementComparator& comparator,
  8274. const bool retainOrderOfEquivalentItems = false) const throw()
  8275. {
  8276. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8277. // avoids getting warning messages about the parameter being unused
  8278. lock.enter();
  8279. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  8280. lock.exit();
  8281. }
  8282. /** Reduces the amount of storage being used by the array.
  8283. Arrays typically allocate slightly more storage than they need, and after
  8284. removing elements, they may have quite a lot of unused space allocated.
  8285. This method will reduce the amount of allocated storage to a minimum.
  8286. */
  8287. void minimiseStorageOverheads() throw()
  8288. {
  8289. lock.enter();
  8290. if (numUsed == 0)
  8291. {
  8292. this->setAllocatedSize (0);
  8293. }
  8294. else
  8295. {
  8296. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8297. if (newAllocation < this->numAllocated)
  8298. this->setAllocatedSize (newAllocation);
  8299. }
  8300. lock.exit();
  8301. }
  8302. /** Locks the array's CriticalSection.
  8303. Of course if the type of section used is a DummyCriticalSection, this won't
  8304. have any effect.
  8305. @see unlockArray
  8306. */
  8307. void lockArray() const throw()
  8308. {
  8309. lock.enter();
  8310. }
  8311. /** Unlocks the array's CriticalSection.
  8312. Of course if the type of section used is a DummyCriticalSection, this won't
  8313. have any effect.
  8314. @see lockArray
  8315. */
  8316. void unlockArray() const throw()
  8317. {
  8318. lock.exit();
  8319. }
  8320. juce_UseDebuggingNewOperator
  8321. private:
  8322. int numUsed;
  8323. TypeOfCriticalSectionToUse lock;
  8324. };
  8325. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8326. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  8327. #endif
  8328. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8329. #endif
  8330. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8331. /********* Start of inlined file: juce_SortedSet.h *********/
  8332. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8333. #define __JUCE_SORTEDSET_JUCEHEADER__
  8334. #if JUCE_MSVC
  8335. #pragma warning (push)
  8336. #pragma warning (disable: 4512)
  8337. #endif
  8338. /**
  8339. Holds a set of unique primitive objects, such as ints or doubles.
  8340. A set can only hold one item with a given value, so if for example it's a
  8341. set of integers, attempting to add the same integer twice will do nothing
  8342. the second time.
  8343. Internally, the list of items is kept sorted (which means that whatever
  8344. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8345. to determine the order), and searching the set for known values is very fast
  8346. because it uses a binary-chop method.
  8347. Note that if you're using a class or struct as the element type, it must be
  8348. capable of being copied or moved with a straightforward memcpy, rather than
  8349. needing construction and destruction code.
  8350. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8351. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8352. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8353. */
  8354. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8355. class SortedSet : private ArrayAllocationBase <ElementType>
  8356. {
  8357. public:
  8358. /** Creates an empty set.
  8359. @param granularity this is the size of increment by which the internal storage
  8360. used by the array will grow. Only change it from the default if you know the
  8361. array is going to be very big and needs to be able to grow efficiently.
  8362. @see ArrayAllocationBase
  8363. */
  8364. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  8365. : ArrayAllocationBase <ElementType> (granularity),
  8366. numUsed (0)
  8367. {
  8368. }
  8369. /** Creates a copy of another set.
  8370. @param other the set to copy
  8371. */
  8372. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8373. : ArrayAllocationBase <ElementType> (other.granularity)
  8374. {
  8375. other.lockSet();
  8376. numUsed = other.numUsed;
  8377. setAllocatedSize (other.numUsed);
  8378. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  8379. other.unlockSet();
  8380. }
  8381. /** Destructor. */
  8382. ~SortedSet() throw()
  8383. {
  8384. }
  8385. /** Copies another set over this one.
  8386. @param other the set to copy
  8387. */
  8388. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8389. {
  8390. if (this != &other)
  8391. {
  8392. other.lockSet();
  8393. lock.enter();
  8394. this->granularity = other.granularity;
  8395. ensureAllocatedSize (other.size());
  8396. numUsed = other.numUsed;
  8397. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  8398. minimiseStorageOverheads();
  8399. lock.exit();
  8400. other.unlockSet();
  8401. }
  8402. return *this;
  8403. }
  8404. /** Compares this set to another one.
  8405. Two sets are considered equal if they both contain the same set of
  8406. elements.
  8407. @param other the other set to compare with
  8408. */
  8409. bool operator== (const SortedSet<ElementType>& other) const throw()
  8410. {
  8411. lock.enter();
  8412. if (numUsed != other.numUsed)
  8413. {
  8414. lock.exit();
  8415. return false;
  8416. }
  8417. for (int i = numUsed; --i >= 0;)
  8418. {
  8419. if (this->elements [i] != other.elements [i])
  8420. {
  8421. lock.exit();
  8422. return false;
  8423. }
  8424. }
  8425. lock.exit();
  8426. return true;
  8427. }
  8428. /** Compares this set to another one.
  8429. Two sets are considered equal if they both contain the same set of
  8430. elements.
  8431. @param other the other set to compare with
  8432. */
  8433. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8434. {
  8435. return ! operator== (other);
  8436. }
  8437. /** Removes all elements from the set.
  8438. This will remove all the elements, and free any storage that the set is
  8439. using. To clear it without freeing the storage, use the clearQuick()
  8440. method instead.
  8441. @see clearQuick
  8442. */
  8443. void clear() throw()
  8444. {
  8445. lock.enter();
  8446. this->setAllocatedSize (0);
  8447. numUsed = 0;
  8448. lock.exit();
  8449. }
  8450. /** Removes all elements from the set without freeing the array's allocated storage.
  8451. @see clear
  8452. */
  8453. void clearQuick() throw()
  8454. {
  8455. lock.enter();
  8456. numUsed = 0;
  8457. lock.exit();
  8458. }
  8459. /** Returns the current number of elements in the set.
  8460. */
  8461. inline int size() const throw()
  8462. {
  8463. return numUsed;
  8464. }
  8465. /** Returns one of the elements in the set.
  8466. If the index passed in is beyond the range of valid elements, this
  8467. will return zero.
  8468. If you're certain that the index will always be a valid element, you
  8469. can call getUnchecked() instead, which is faster.
  8470. @param index the index of the element being requested (0 is the first element in the set)
  8471. @see getUnchecked, getFirst, getLast
  8472. */
  8473. inline ElementType operator[] (const int index) const throw()
  8474. {
  8475. lock.enter();
  8476. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8477. ? this->elements [index]
  8478. : (ElementType) 0;
  8479. lock.exit();
  8480. return result;
  8481. }
  8482. /** Returns one of the elements in the set, without checking the index passed in.
  8483. Unlike the operator[] method, this will try to return an element without
  8484. checking that the index is within the bounds of the set, so should only
  8485. be used when you're confident that it will always be a valid index.
  8486. @param index the index of the element being requested (0 is the first element in the set)
  8487. @see operator[], getFirst, getLast
  8488. */
  8489. inline ElementType getUnchecked (const int index) const throw()
  8490. {
  8491. lock.enter();
  8492. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8493. const ElementType result = this->elements [index];
  8494. lock.exit();
  8495. return result;
  8496. }
  8497. /** Returns the first element in the set, or 0 if the set is empty.
  8498. @see operator[], getUnchecked, getLast
  8499. */
  8500. inline ElementType getFirst() const throw()
  8501. {
  8502. lock.enter();
  8503. const ElementType result = (numUsed > 0) ? this->elements [0]
  8504. : (ElementType) 0;
  8505. lock.exit();
  8506. return result;
  8507. }
  8508. /** Returns the last element in the set, or 0 if the set is empty.
  8509. @see operator[], getUnchecked, getFirst
  8510. */
  8511. inline ElementType getLast() const throw()
  8512. {
  8513. lock.enter();
  8514. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8515. : (ElementType) 0;
  8516. lock.exit();
  8517. return result;
  8518. }
  8519. /** Finds the index of the first element which matches the value passed in.
  8520. This will search the set for the given object, and return the index
  8521. of its first occurrence. If the object isn't found, the method will return -1.
  8522. @param elementToLookFor the value or object to look for
  8523. @returns the index of the object, or -1 if it's not found
  8524. */
  8525. int indexOf (const ElementType elementToLookFor) const throw()
  8526. {
  8527. lock.enter();
  8528. int start = 0;
  8529. int end = numUsed;
  8530. for (;;)
  8531. {
  8532. if (start >= end)
  8533. {
  8534. lock.exit();
  8535. return -1;
  8536. }
  8537. else if (elementToLookFor == this->elements [start])
  8538. {
  8539. lock.exit();
  8540. return start;
  8541. }
  8542. else
  8543. {
  8544. const int halfway = (start + end) >> 1;
  8545. if (halfway == start)
  8546. {
  8547. lock.exit();
  8548. return -1;
  8549. }
  8550. else if (elementToLookFor >= this->elements [halfway])
  8551. start = halfway;
  8552. else
  8553. end = halfway;
  8554. }
  8555. }
  8556. }
  8557. /** Returns true if the set contains at least one occurrence of an object.
  8558. @param elementToLookFor the value or object to look for
  8559. @returns true if the item is found
  8560. */
  8561. bool contains (const ElementType elementToLookFor) const throw()
  8562. {
  8563. lock.enter();
  8564. int start = 0;
  8565. int end = numUsed;
  8566. for (;;)
  8567. {
  8568. if (start >= end)
  8569. {
  8570. lock.exit();
  8571. return false;
  8572. }
  8573. else if (elementToLookFor == this->elements [start])
  8574. {
  8575. lock.exit();
  8576. return true;
  8577. }
  8578. else
  8579. {
  8580. const int halfway = (start + end) >> 1;
  8581. if (halfway == start)
  8582. {
  8583. lock.exit();
  8584. return false;
  8585. }
  8586. else if (elementToLookFor >= this->elements [halfway])
  8587. start = halfway;
  8588. else
  8589. end = halfway;
  8590. }
  8591. }
  8592. }
  8593. /** Adds a new element to the set, (as long as it's not already in there).
  8594. @param newElement the new object to add to the set
  8595. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8596. */
  8597. void add (const ElementType newElement) throw()
  8598. {
  8599. lock.enter();
  8600. int start = 0;
  8601. int end = numUsed;
  8602. for (;;)
  8603. {
  8604. if (start >= end)
  8605. {
  8606. jassert (start <= end);
  8607. insertInternal (start, newElement);
  8608. break;
  8609. }
  8610. else if (newElement == this->elements [start])
  8611. {
  8612. break;
  8613. }
  8614. else
  8615. {
  8616. const int halfway = (start + end) >> 1;
  8617. if (halfway == start)
  8618. {
  8619. if (newElement >= this->elements [halfway])
  8620. insertInternal (start + 1, newElement);
  8621. else
  8622. insertInternal (start, newElement);
  8623. break;
  8624. }
  8625. else if (newElement >= this->elements [halfway])
  8626. start = halfway;
  8627. else
  8628. end = halfway;
  8629. }
  8630. }
  8631. lock.exit();
  8632. }
  8633. /** Adds elements from an array to this set.
  8634. @param elementsToAdd the array of elements to add
  8635. @param numElementsToAdd how many elements are in this other array
  8636. @see add
  8637. */
  8638. void addArray (const ElementType* elementsToAdd,
  8639. int numElementsToAdd) throw()
  8640. {
  8641. lock.enter();
  8642. while (--numElementsToAdd >= 0)
  8643. add (*elementsToAdd++);
  8644. lock.exit();
  8645. }
  8646. /** Adds elements from another set to this one.
  8647. @param setToAddFrom the set from which to copy the elements
  8648. @param startIndex the first element of the other set to start copying from
  8649. @param numElementsToAdd how many elements to add from the other set. If this
  8650. value is negative or greater than the number of available elements,
  8651. all available elements will be copied.
  8652. @see add
  8653. */
  8654. template <class OtherSetType>
  8655. void addSet (const OtherSetType& setToAddFrom,
  8656. int startIndex = 0,
  8657. int numElementsToAdd = -1) throw()
  8658. {
  8659. setToAddFrom.lockSet();
  8660. lock.enter();
  8661. jassert (this != &setToAddFrom);
  8662. if (this != &setToAddFrom)
  8663. {
  8664. if (startIndex < 0)
  8665. {
  8666. jassertfalse
  8667. startIndex = 0;
  8668. }
  8669. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8670. numElementsToAdd = setToAddFrom.size() - startIndex;
  8671. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8672. }
  8673. lock.exit();
  8674. setToAddFrom.unlockSet();
  8675. }
  8676. /** Removes an element from the set.
  8677. This will remove the element at a given index.
  8678. If the index passed in is out-of-range, nothing will happen.
  8679. @param indexToRemove the index of the element to remove
  8680. @returns the element that has been removed
  8681. @see removeValue, removeRange
  8682. */
  8683. ElementType remove (const int indexToRemove) throw()
  8684. {
  8685. lock.enter();
  8686. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8687. {
  8688. --numUsed;
  8689. ElementType* const e = this->elements + indexToRemove;
  8690. ElementType const removed = *e;
  8691. const int numberToShift = numUsed - indexToRemove;
  8692. if (numberToShift > 0)
  8693. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8694. if ((numUsed << 1) < this->numAllocated)
  8695. minimiseStorageOverheads();
  8696. lock.exit();
  8697. return removed;
  8698. }
  8699. else
  8700. {
  8701. lock.exit();
  8702. return 0;
  8703. }
  8704. }
  8705. /** Removes an item from the set.
  8706. This will remove the given element from the set, if it's there.
  8707. @param valueToRemove the object to try to remove
  8708. @see remove, removeRange
  8709. */
  8710. void removeValue (const ElementType valueToRemove) throw()
  8711. {
  8712. lock.enter();
  8713. remove (indexOf (valueToRemove));
  8714. lock.exit();
  8715. }
  8716. /** Removes any elements which are also in another set.
  8717. @param otherSet the other set in which to look for elements to remove
  8718. @see removeValuesNotIn, remove, removeValue, removeRange
  8719. */
  8720. template <class OtherSetType>
  8721. void removeValuesIn (const OtherSetType& otherSet) throw()
  8722. {
  8723. otherSet.lockSet();
  8724. lock.enter();
  8725. if (this == &otherSet)
  8726. {
  8727. clear();
  8728. }
  8729. else
  8730. {
  8731. if (otherSet.size() > 0)
  8732. {
  8733. for (int i = numUsed; --i >= 0;)
  8734. if (otherSet.contains (this->elements [i]))
  8735. remove (i);
  8736. }
  8737. }
  8738. lock.exit();
  8739. otherSet.unlockSet();
  8740. }
  8741. /** Removes any elements which are not found in another set.
  8742. Only elements which occur in this other set will be retained.
  8743. @param otherSet the set in which to look for elements NOT to remove
  8744. @see removeValuesIn, remove, removeValue, removeRange
  8745. */
  8746. template <class OtherSetType>
  8747. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8748. {
  8749. otherSet.lockSet();
  8750. lock.enter();
  8751. if (this != &otherSet)
  8752. {
  8753. if (otherSet.size() <= 0)
  8754. {
  8755. clear();
  8756. }
  8757. else
  8758. {
  8759. for (int i = numUsed; --i >= 0;)
  8760. if (! otherSet.contains (this->elements [i]))
  8761. remove (i);
  8762. }
  8763. }
  8764. lock.exit();
  8765. otherSet.lockSet();
  8766. }
  8767. /** Reduces the amount of storage being used by the set.
  8768. Sets typically allocate slightly more storage than they need, and after
  8769. removing elements, they may have quite a lot of unused space allocated.
  8770. This method will reduce the amount of allocated storage to a minimum.
  8771. */
  8772. void minimiseStorageOverheads() throw()
  8773. {
  8774. lock.enter();
  8775. if (numUsed == 0)
  8776. {
  8777. this->setAllocatedSize (0);
  8778. }
  8779. else
  8780. {
  8781. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8782. if (newAllocation < this->numAllocated)
  8783. this->setAllocatedSize (newAllocation);
  8784. }
  8785. lock.exit();
  8786. }
  8787. /** Locks the set's CriticalSection.
  8788. Of course if the type of section used is a DummyCriticalSection, this won't
  8789. have any effect.
  8790. @see unlockSet
  8791. */
  8792. void lockSet() const throw()
  8793. {
  8794. lock.enter();
  8795. }
  8796. /** Unlocks the set's CriticalSection.
  8797. Of course if the type of section used is a DummyCriticalSection, this won't
  8798. have any effect.
  8799. @see lockSet
  8800. */
  8801. void unlockSet() const throw()
  8802. {
  8803. lock.exit();
  8804. }
  8805. juce_UseDebuggingNewOperator
  8806. private:
  8807. int numUsed;
  8808. TypeOfCriticalSectionToUse lock;
  8809. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8810. {
  8811. this->ensureAllocatedSize (numUsed + 1);
  8812. ElementType* const insertPos = this->elements + indexToInsertAt;
  8813. const int numberToMove = numUsed - indexToInsertAt;
  8814. if (numberToMove > 0)
  8815. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8816. *insertPos = newElement;
  8817. ++numUsed;
  8818. }
  8819. };
  8820. #if JUCE_MSVC
  8821. #pragma warning (pop)
  8822. #endif
  8823. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8824. /********* End of inlined file: juce_SortedSet.h *********/
  8825. #endif
  8826. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8827. /********* Start of inlined file: juce_SparseSet.h *********/
  8828. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8829. #define __JUCE_SPARSESET_JUCEHEADER__
  8830. /**
  8831. Holds a set of primitive values, storing them as a set of ranges.
  8832. This container acts like a simple BitArray, but can efficiently hold large
  8833. continguous ranges of values. It's quite a specialised class, mostly useful
  8834. for things like keeping the set of selected rows in a listbox.
  8835. The type used as a template paramter must be an integer type, such as int, short,
  8836. int64, etc.
  8837. */
  8838. template <class Type>
  8839. class SparseSet
  8840. {
  8841. public:
  8842. /** Creates a new empty set. */
  8843. SparseSet() throw()
  8844. {
  8845. }
  8846. /** Creates a copy of another SparseSet. */
  8847. SparseSet (const SparseSet<Type>& other) throw()
  8848. : values (other.values)
  8849. {
  8850. }
  8851. /** Destructor. */
  8852. ~SparseSet() throw()
  8853. {
  8854. }
  8855. /** Clears the set. */
  8856. void clear() throw()
  8857. {
  8858. values.clear();
  8859. }
  8860. /** Checks whether the set is empty.
  8861. This is much quicker than using (size() == 0).
  8862. */
  8863. bool isEmpty() const throw()
  8864. {
  8865. return values.size() == 0;
  8866. }
  8867. /** Returns the number of values in the set.
  8868. Because of the way the data is stored, this method can take longer if there
  8869. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8870. are any items.
  8871. */
  8872. Type size() const throw()
  8873. {
  8874. Type num = 0;
  8875. for (int i = 0; i < values.size(); i += 2)
  8876. num += values[i + 1] - values[i];
  8877. return num;
  8878. }
  8879. /** Returns one of the values in the set.
  8880. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8881. @returns the value at this index, or 0 if it's out-of-range
  8882. */
  8883. Type operator[] (int index) const throw()
  8884. {
  8885. for (int i = 0; i < values.size(); i += 2)
  8886. {
  8887. const Type s = values.getUnchecked(i);
  8888. const Type e = values.getUnchecked(i + 1);
  8889. if (index < e - s)
  8890. return s + index;
  8891. index -= e - s;
  8892. }
  8893. return (Type) 0;
  8894. }
  8895. /** Checks whether a particular value is in the set. */
  8896. bool contains (const Type valueToLookFor) const throw()
  8897. {
  8898. bool on = false;
  8899. for (int i = 0; i < values.size(); ++i)
  8900. {
  8901. if (values.getUnchecked(i) > valueToLookFor)
  8902. return on;
  8903. on = ! on;
  8904. }
  8905. return false;
  8906. }
  8907. /** Returns the number of contiguous blocks of values.
  8908. @see getRange
  8909. */
  8910. int getNumRanges() const throw()
  8911. {
  8912. return values.size() >> 1;
  8913. }
  8914. /** Returns one of the contiguous ranges of values stored.
  8915. @param rangeIndex the index of the range to look up, between 0
  8916. and (getNumRanges() - 1)
  8917. @param startValue on return, the value at the start of the range
  8918. @param numValues on return, the number of values in the range
  8919. @see getTotalRange
  8920. */
  8921. bool getRange (const int rangeIndex,
  8922. Type& startValue,
  8923. Type& numValues) const throw()
  8924. {
  8925. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8926. {
  8927. startValue = values [rangeIndex << 1];
  8928. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8929. return true;
  8930. }
  8931. return false;
  8932. }
  8933. /** Returns the lowest and highest values in the set.
  8934. @see getRange
  8935. */
  8936. bool getTotalRange (Type& lowestValue,
  8937. Type& highestValue) const throw()
  8938. {
  8939. if (values.size() > 0)
  8940. {
  8941. lowestValue = values.getUnchecked (0);
  8942. highestValue = values.getUnchecked (values.size() - 1);
  8943. return true;
  8944. }
  8945. return false;
  8946. }
  8947. /** Adds a range of contiguous values to the set.
  8948. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8949. @param firstValue the start of the range of values to add
  8950. @param numValuesToAdd how many values to add
  8951. */
  8952. void addRange (const Type firstValue,
  8953. const Type numValuesToAdd) throw()
  8954. {
  8955. jassert (numValuesToAdd >= 0);
  8956. if (numValuesToAdd > 0)
  8957. {
  8958. removeRange (firstValue, numValuesToAdd);
  8959. IntegerElementComparator<Type> sorter;
  8960. values.addSorted (sorter, firstValue);
  8961. values.addSorted (sorter, firstValue + numValuesToAdd);
  8962. simplify();
  8963. }
  8964. }
  8965. /** Removes a range of values from the set.
  8966. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8967. @param firstValue the start of the range of values to remove
  8968. @param numValuesToRemove how many values to remove
  8969. */
  8970. void removeRange (const Type firstValue,
  8971. const Type numValuesToRemove) throw()
  8972. {
  8973. jassert (numValuesToRemove >= 0);
  8974. if (numValuesToRemove >= 0
  8975. && firstValue < values.getLast())
  8976. {
  8977. const bool onAtStart = contains (firstValue - 1);
  8978. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  8979. const bool onAtEnd = contains (lastValue);
  8980. for (int i = values.size(); --i >= 0;)
  8981. {
  8982. if (values.getUnchecked(i) <= lastValue)
  8983. {
  8984. while (values.getUnchecked(i) >= firstValue)
  8985. {
  8986. values.remove (i);
  8987. if (--i < 0)
  8988. break;
  8989. }
  8990. break;
  8991. }
  8992. }
  8993. IntegerElementComparator<Type> sorter;
  8994. if (onAtStart)
  8995. values.addSorted (sorter, firstValue);
  8996. if (onAtEnd)
  8997. values.addSorted (sorter, lastValue);
  8998. simplify();
  8999. }
  9000. }
  9001. /** Does an XOR of the values in a given range. */
  9002. void invertRange (const Type firstValue,
  9003. const Type numValues)
  9004. {
  9005. SparseSet newItems;
  9006. newItems.addRange (firstValue, numValues);
  9007. int i;
  9008. for (i = getNumRanges(); --i >= 0;)
  9009. {
  9010. const int start = values [i << 1];
  9011. const int end = values [(i << 1) + 1];
  9012. newItems.removeRange (start, end);
  9013. }
  9014. removeRange (firstValue, numValues);
  9015. for (i = newItems.getNumRanges(); --i >= 0;)
  9016. {
  9017. const int start = newItems.values [i << 1];
  9018. const int end = newItems.values [(i << 1) + 1];
  9019. addRange (start, end);
  9020. }
  9021. }
  9022. /** Checks whether any part of a given range overlaps any part of this one. */
  9023. bool overlapsRange (const Type firstValue,
  9024. const Type numValues) throw()
  9025. {
  9026. jassert (numValues >= 0);
  9027. if (numValues > 0)
  9028. {
  9029. for (int i = getNumRanges(); --i >= 0;)
  9030. {
  9031. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  9032. return false;
  9033. if (firstValue + numValues > values.getUnchecked (i << 1))
  9034. return true;
  9035. }
  9036. }
  9037. return false;
  9038. }
  9039. /** Checks whether the whole of a given range is contained within this one. */
  9040. bool containsRange (const Type firstValue,
  9041. const Type numValues) throw()
  9042. {
  9043. jassert (numValues >= 0);
  9044. if (numValues > 0)
  9045. {
  9046. for (int i = getNumRanges(); --i >= 0;)
  9047. {
  9048. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  9049. return false;
  9050. if (firstValue >= values.getUnchecked (i << 1)
  9051. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  9052. return true;
  9053. }
  9054. }
  9055. return false;
  9056. }
  9057. bool operator== (const SparseSet<Type>& other) throw()
  9058. {
  9059. return values == other.values;
  9060. }
  9061. bool operator!= (const SparseSet<Type>& other) throw()
  9062. {
  9063. return values != other.values;
  9064. }
  9065. juce_UseDebuggingNewOperator
  9066. private:
  9067. // alternating start/end values of ranges of values that are present.
  9068. Array<Type> values;
  9069. void simplify() throw()
  9070. {
  9071. jassert ((values.size() & 1) == 0);
  9072. for (int i = values.size(); --i > 0;)
  9073. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  9074. values.removeRange (i - 1, 2);
  9075. }
  9076. };
  9077. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9078. /********* End of inlined file: juce_SparseSet.h *********/
  9079. #endif
  9080. #ifndef __JUCE_VARIANT_JUCEHEADER__
  9081. /********* Start of inlined file: juce_Variant.h *********/
  9082. #ifndef __JUCE_VARIANT_JUCEHEADER__
  9083. #define __JUCE_VARIANT_JUCEHEADER__
  9084. class JUCE_API DynamicObject;
  9085. /**
  9086. A variant class, that can be used to hold a range of primitive values.
  9087. A var object can hold a range of simple primitive values, strings, or
  9088. a reference-counted pointer to a DynamicObject. The var class is intended
  9089. to act like the values used in dynamic scripting languages.
  9090. @see DynamicObject
  9091. */
  9092. class JUCE_API var
  9093. {
  9094. public:
  9095. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  9096. /** Creates a void variant. */
  9097. var() throw();
  9098. /** Destructor. */
  9099. ~var();
  9100. var (const var& valueToCopy) throw();
  9101. var (const int value) throw();
  9102. var (const bool value) throw();
  9103. var (const double value) throw();
  9104. var (const char* const value) throw();
  9105. var (const juce_wchar* const value) throw();
  9106. var (const String& value) throw();
  9107. var (DynamicObject* const object) throw();
  9108. var (MethodFunction method) throw();
  9109. const var& operator= (const var& valueToCopy) throw();
  9110. const var& operator= (const int value) throw();
  9111. const var& operator= (const bool value) throw();
  9112. const var& operator= (const double value) throw();
  9113. const var& operator= (const char* const value) throw();
  9114. const var& operator= (const juce_wchar* const value) throw();
  9115. const var& operator= (const String& value) throw();
  9116. const var& operator= (DynamicObject* const object) throw();
  9117. const var& operator= (MethodFunction method) throw();
  9118. operator int() const throw();
  9119. operator bool() const throw();
  9120. operator double() const throw();
  9121. operator const String() const throw();
  9122. const String toString() const throw();
  9123. DynamicObject* getObject() const throw();
  9124. bool isVoid() const throw() { return type == voidType; }
  9125. bool isInt() const throw() { return type == intType; }
  9126. bool isBool() const throw() { return type == boolType; }
  9127. bool isDouble() const throw() { return type == doubleType; }
  9128. bool isString() const throw() { return type == stringType; }
  9129. bool isObject() const throw() { return type == objectType; }
  9130. bool isMethod() const throw() { return type == methodType; }
  9131. class JUCE_API identifier
  9132. {
  9133. public:
  9134. identifier (const char* const name) throw();
  9135. identifier (const String& name) throw();
  9136. ~identifier() throw();
  9137. bool operator== (const identifier& other) const throw() { return hashCode == other.hashCode; }
  9138. String name;
  9139. int hashCode;
  9140. };
  9141. /** If this variant is an object, this returns one of its properties. */
  9142. const var operator[] (const identifier& propertyName) const throw();
  9143. /** If this variant is an object, this invokes one of its methods with no arguments. */
  9144. const var call (const identifier& method) const;
  9145. /** If this variant is an object, this invokes one of its methods with one argument. */
  9146. const var call (const identifier& method, const var& arg1) const;
  9147. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  9148. const var call (const identifier& method, const var& arg1, const var& arg2) const;
  9149. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  9150. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3);
  9151. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  9152. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  9153. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  9154. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  9155. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  9156. const var invoke (const identifier& method, const var* arguments, int numArguments) const;
  9157. /** If this variant is a method pointer, this invokes it on a target object. */
  9158. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  9159. juce_UseDebuggingNewOperator
  9160. private:
  9161. enum Type
  9162. {
  9163. voidType = 0,
  9164. intType,
  9165. boolType,
  9166. doubleType,
  9167. stringType,
  9168. objectType,
  9169. methodType
  9170. };
  9171. Type type;
  9172. union
  9173. {
  9174. int intValue;
  9175. bool boolValue;
  9176. double doubleValue;
  9177. String* stringValue;
  9178. DynamicObject* objectValue;
  9179. MethodFunction methodValue;
  9180. } value;
  9181. void releaseValue() throw();
  9182. };
  9183. /**
  9184. Represents a dynamically implemented object.
  9185. An instance of this class can be used to store named properties, and
  9186. by subclassing hasMethod() and invokeMethod(), you can give your object
  9187. methods.
  9188. This is intended for use as a wrapper for scripting language objects.
  9189. */
  9190. class JUCE_API DynamicObject : public ReferenceCountedObject
  9191. {
  9192. public:
  9193. DynamicObject();
  9194. /** Destructor. */
  9195. virtual ~DynamicObject();
  9196. /** Returns true if the object has a property with this name.
  9197. Note that if the property is actually a method, this will return false.
  9198. */
  9199. virtual bool hasProperty (const var::identifier& propertyName) const;
  9200. /** Returns a named property.
  9201. This returns a void if no such property exists.
  9202. */
  9203. virtual const var getProperty (const var::identifier& propertyName) const;
  9204. /** Sets a named property. */
  9205. virtual void setProperty (const var::identifier& propertyName, const var& newValue);
  9206. /** Removes a named property. */
  9207. virtual void removeProperty (const var::identifier& propertyName);
  9208. /** Checks whether this object has the specified method.
  9209. The default implementation of this just checks whether there's a property
  9210. with this name that's actually a method, but this can be overridden for
  9211. building objects with dynamic invocation.
  9212. */
  9213. virtual bool hasMethod (const var::identifier& methodName) const;
  9214. /** Invokes a named method on this object.
  9215. The default implementation looks up the named property, and if it's a method
  9216. call, then it invokes it.
  9217. This method is virtual to allow more dynamic invocation to used for objects
  9218. where the methods may not already be set as properies.
  9219. */
  9220. virtual const var invokeMethod (const var::identifier& methodName,
  9221. const var* parameters,
  9222. int numParameters);
  9223. /** Sets up a method.
  9224. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  9225. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  9226. the code easier to read,
  9227. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  9228. @code
  9229. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  9230. @endcode
  9231. */
  9232. void setMethod (const var::identifier& methodName,
  9233. var::MethodFunction methodFunction);
  9234. /** Removes all properties and methods from the object. */
  9235. void clear();
  9236. juce_UseDebuggingNewOperator
  9237. private:
  9238. Array <int> propertyIds;
  9239. OwnedArray <var> propertyValues;
  9240. };
  9241. #endif // __JUCE_VARIANT_JUCEHEADER__
  9242. /********* End of inlined file: juce_Variant.h *********/
  9243. #endif
  9244. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9245. #endif
  9246. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9247. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  9248. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9249. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9250. /**
  9251. Searches through a the files in a directory, returning each file that is found.
  9252. A DirectoryIterator will search through a directory and its subdirectories using
  9253. a wildcard filepattern match.
  9254. If you may be finding a large number of files, this is better than
  9255. using File::findChildFiles() because it doesn't block while it finds them
  9256. all, and this is more memory-efficient.
  9257. It can also guess how far it's got using a wildly inaccurate algorithm.
  9258. */
  9259. class JUCE_API DirectoryIterator
  9260. {
  9261. public:
  9262. /** Creates a DirectoryIterator for a given directory.
  9263. After creating one of these, call its next() method to get the
  9264. first file - e.g. @code
  9265. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  9266. while (iter.next())
  9267. {
  9268. File theFileItFound (iter.getFile());
  9269. ... etc
  9270. }
  9271. @endcode
  9272. @param directory the directory to search in
  9273. @param isRecursive whether all the subdirectories should also be searched
  9274. @param wildCard the file pattern to match
  9275. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  9276. whether to look for files, directories, or both.
  9277. */
  9278. DirectoryIterator (const File& directory,
  9279. bool isRecursive,
  9280. const String& wildCard = JUCE_T("*"),
  9281. const int whatToLookFor = File::findFiles) throw();
  9282. /** Destructor. */
  9283. ~DirectoryIterator() throw();
  9284. /** Call this to move the iterator along to the next file.
  9285. @returns true if a file was found (you can then use getFile() to see what it was) - or
  9286. false if there are no more matching files.
  9287. */
  9288. bool next() throw();
  9289. /** Returns the file that the iterator is currently pointing at.
  9290. The result of this call is only valid after a call to next() has returned true.
  9291. */
  9292. const File getFile() const throw();
  9293. /** Returns a guess of how far through the search the iterator has got.
  9294. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  9295. very accurate.
  9296. */
  9297. float getEstimatedProgress() const throw();
  9298. juce_UseDebuggingNewOperator
  9299. private:
  9300. OwnedArray <File> filesFound;
  9301. OwnedArray <File> dirsFound;
  9302. String wildCard;
  9303. int index;
  9304. const int whatToLookFor;
  9305. DirectoryIterator* subIterator;
  9306. DirectoryIterator (const DirectoryIterator&);
  9307. const DirectoryIterator& operator= (const DirectoryIterator&);
  9308. };
  9309. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9310. /********* End of inlined file: juce_DirectoryIterator.h *********/
  9311. #endif
  9312. #ifndef __JUCE_FILE_JUCEHEADER__
  9313. #endif
  9314. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9315. /********* Start of inlined file: juce_FileInputStream.h *********/
  9316. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9317. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9318. /**
  9319. An input stream that reads from a local file.
  9320. @see InputStream, FileOutputStream, File::createInputStream
  9321. */
  9322. class JUCE_API FileInputStream : public InputStream
  9323. {
  9324. public:
  9325. /** Creates a FileInputStream.
  9326. @param fileToRead the file to read from - if the file can't be accessed for some
  9327. reason, then the stream will just contain no data
  9328. */
  9329. FileInputStream (const File& fileToRead);
  9330. /** Destructor. */
  9331. ~FileInputStream();
  9332. const File& getFile() const throw() { return file; }
  9333. int64 getTotalLength();
  9334. int read (void* destBuffer, int maxBytesToRead);
  9335. bool isExhausted();
  9336. int64 getPosition();
  9337. bool setPosition (int64 pos);
  9338. juce_UseDebuggingNewOperator
  9339. private:
  9340. File file;
  9341. void* fileHandle;
  9342. int64 currentPosition, totalSize;
  9343. bool needToSeek;
  9344. };
  9345. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9346. /********* End of inlined file: juce_FileInputStream.h *********/
  9347. #endif
  9348. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9349. /********* Start of inlined file: juce_FileOutputStream.h *********/
  9350. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9351. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9352. /**
  9353. An output stream that writes into a local file.
  9354. @see OutputStream, FileInputStream, File::createOutputStream
  9355. */
  9356. class JUCE_API FileOutputStream : public OutputStream
  9357. {
  9358. public:
  9359. /** Creates a FileOutputStream.
  9360. If the file doesn't exist, it will first be created. If the file can't be
  9361. created or opened, the failedToOpen() method will return
  9362. true.
  9363. If the file already exists when opened, the stream's write-postion will
  9364. be set to the end of the file. To overwrite an existing file,
  9365. use File::deleteFile() before opening the stream, or use setPosition(0)
  9366. after it's opened (although this won't truncate the file).
  9367. It's better to use File::createOutputStream() to create one of these, rather
  9368. than using the class directly.
  9369. */
  9370. FileOutputStream (const File& fileToWriteTo,
  9371. const int bufferSizeToUse = 16384);
  9372. /** Destructor. */
  9373. ~FileOutputStream();
  9374. /** Returns the file that this stream is writing to.
  9375. */
  9376. const File& getFile() const throw() { return file; }
  9377. /** Returns true if the stream couldn't be opened for some reason.
  9378. */
  9379. bool failedToOpen() const throw() { return fileHandle == 0; }
  9380. void flush();
  9381. int64 getPosition();
  9382. bool setPosition (int64 pos);
  9383. bool write (const void* data, int numBytes);
  9384. juce_UseDebuggingNewOperator
  9385. private:
  9386. File file;
  9387. void* fileHandle;
  9388. int64 currentPosition;
  9389. int bufferSize, bytesInBuffer;
  9390. char* buffer;
  9391. };
  9392. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9393. /********* End of inlined file: juce_FileOutputStream.h *********/
  9394. #endif
  9395. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  9396. /********* Start of inlined file: juce_FileSearchPath.h *********/
  9397. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  9398. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  9399. /**
  9400. Encapsulates a set of folders that make up a search path.
  9401. @see File
  9402. */
  9403. class JUCE_API FileSearchPath
  9404. {
  9405. public:
  9406. /** Creates an empty search path. */
  9407. FileSearchPath();
  9408. /** Creates a search path from a string of pathnames.
  9409. The path can be semicolon- or comma-separated, e.g.
  9410. "/foo/bar;/foo/moose;/fish/moose"
  9411. The separate folders are tokenised and added to the search path.
  9412. */
  9413. FileSearchPath (const String& path);
  9414. /** Creates a copy of another search path. */
  9415. FileSearchPath (const FileSearchPath& other);
  9416. /** Destructor. */
  9417. ~FileSearchPath();
  9418. /** Uses a string containing a list of pathnames to re-initialise this list.
  9419. This search path is cleared and the semicolon- or comma-separated folders
  9420. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  9421. */
  9422. const FileSearchPath& operator= (const String& path);
  9423. /** Returns the number of folders in this search path.
  9424. @see operator[]
  9425. */
  9426. int getNumPaths() const;
  9427. /** Returns one of the folders in this search path.
  9428. The file returned isn't guaranteed to actually be a valid directory.
  9429. @see getNumPaths
  9430. */
  9431. const File operator[] (const int index) const;
  9432. /** Returns the search path as a semicolon-separated list of directories. */
  9433. const String toString() const;
  9434. /** Adds a new directory to the search path.
  9435. The new directory is added to the end of the list if the insertIndex parameter is
  9436. less than zero, otherwise it is inserted at the given index.
  9437. */
  9438. void add (const File& directoryToAdd,
  9439. const int insertIndex = -1);
  9440. /** Adds a new directory to the search path if it's not already in there. */
  9441. void addIfNotAlreadyThere (const File& directoryToAdd);
  9442. /** Removes a directory from the search path. */
  9443. void remove (const int indexToRemove);
  9444. /** Merges another search path into this one.
  9445. This will remove any duplicate directories.
  9446. */
  9447. void addPath (const FileSearchPath& other);
  9448. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  9449. If the search is intended to be recursive, there's no point having nested folders in the search
  9450. path, because they'll just get searched twice and you'll get duplicate results.
  9451. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  9452. */
  9453. void removeRedundantPaths();
  9454. /** Removes any directories that don't actually exist. */
  9455. void removeNonExistentPaths();
  9456. /** Searches the path for a wildcard.
  9457. This will search all the directories in the search path in order, adding any
  9458. matching files to the results array.
  9459. @param results an array to append the results to
  9460. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  9461. return files, directories, or both.
  9462. @param searchRecursively whether to recursively search the subdirectories too
  9463. @param wildCardPattern a pattern to match against the filenames
  9464. @returns the number of files added to the array
  9465. @see File::findChildFiles
  9466. */
  9467. int findChildFiles (OwnedArray<File>& results,
  9468. const int whatToLookFor,
  9469. const bool searchRecursively,
  9470. const String& wildCardPattern = JUCE_T("*")) const;
  9471. /** Finds out whether a file is inside one of the path's directories.
  9472. This will return true if the specified file is a child of one of the
  9473. directories specified by this path. Note that this doesn't actually do any
  9474. searching or check that the files exist - it just looks at the pathnames
  9475. to work out whether the file would be inside a directory.
  9476. @param fileToCheck the file to look for
  9477. @param checkRecursively if true, then this will return true if the file is inside a
  9478. subfolder of one of the path's directories (at any depth). If false
  9479. it will only return true if the file is actually a direct child
  9480. of one of the directories.
  9481. @see File::isAChildOf
  9482. */
  9483. bool isFileInPath (const File& fileToCheck,
  9484. const bool checkRecursively) const;
  9485. juce_UseDebuggingNewOperator
  9486. private:
  9487. StringArray directories;
  9488. void init (const String& path);
  9489. };
  9490. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  9491. /********* End of inlined file: juce_FileSearchPath.h *********/
  9492. #endif
  9493. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  9494. /********* Start of inlined file: juce_NamedPipe.h *********/
  9495. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  9496. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  9497. /**
  9498. A cross-process pipe that can have data written to and read from it.
  9499. Two or more processes can use these for inter-process communication.
  9500. @see InterprocessConnection
  9501. */
  9502. class JUCE_API NamedPipe
  9503. {
  9504. public:
  9505. /** Creates a NamedPipe. */
  9506. NamedPipe();
  9507. /** Destructor. */
  9508. ~NamedPipe();
  9509. /** Tries to open a pipe that already exists.
  9510. Returns true if it succeeds.
  9511. */
  9512. bool openExisting (const String& pipeName);
  9513. /** Tries to create a new pipe.
  9514. Returns true if it succeeds.
  9515. */
  9516. bool createNewPipe (const String& pipeName);
  9517. /** Closes the pipe, if it's open. */
  9518. void close();
  9519. /** True if the pipe is currently open. */
  9520. bool isOpen() const throw();
  9521. /** Returns the last name that was used to try to open this pipe. */
  9522. const String getName() const throw();
  9523. /** Reads data from the pipe.
  9524. This will block until another thread has written enough data into the pipe to fill
  9525. the number of bytes specified, or until another thread calls the cancelPendingReads()
  9526. method.
  9527. If the operation fails, it returns -1, otherwise, it will return the number of
  9528. bytes read.
  9529. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  9530. this is a maximum timeout for reading from the pipe.
  9531. */
  9532. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  9533. /** Writes some data to the pipe.
  9534. If the operation fails, it returns -1, otherwise, it will return the number of
  9535. bytes written.
  9536. */
  9537. int write (const void* sourceBuffer, int numBytesToWrite,
  9538. int timeOutMilliseconds = 2000);
  9539. /** If any threads are currently blocked on a read operation, this tells them to abort.
  9540. */
  9541. void cancelPendingReads();
  9542. juce_UseDebuggingNewOperator
  9543. private:
  9544. void* internal;
  9545. String currentPipeName;
  9546. NamedPipe (const NamedPipe&);
  9547. const NamedPipe& operator= (const NamedPipe&);
  9548. bool openInternal (const String& pipeName, const bool createPipe);
  9549. };
  9550. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  9551. /********* End of inlined file: juce_NamedPipe.h *********/
  9552. #endif
  9553. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  9554. /********* Start of inlined file: juce_ZipFile.h *********/
  9555. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  9556. #define __JUCE_ZIPFILE_JUCEHEADER__
  9557. /********* Start of inlined file: juce_InputSource.h *********/
  9558. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9559. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9560. /**
  9561. A lightweight object that can create a stream to read some kind of resource.
  9562. This may be used to refer to a file, or some other kind of source, allowing a
  9563. caller to create an input stream that can read from it when required.
  9564. @see FileInputSource
  9565. */
  9566. class JUCE_API InputSource
  9567. {
  9568. public:
  9569. InputSource() throw() {}
  9570. /** Destructor. */
  9571. virtual ~InputSource() {}
  9572. /** Returns a new InputStream to read this item.
  9573. @returns an inputstream that the caller will delete, or 0 if
  9574. the filename isn't found.
  9575. */
  9576. virtual InputStream* createInputStream() = 0;
  9577. /** Returns a new InputStream to read an item, relative.
  9578. @param relatedItemPath the relative pathname of the resource that is required
  9579. @returns an inputstream that the caller will delete, or 0 if
  9580. the item isn't found.
  9581. */
  9582. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9583. /** Returns a hash code that uniquely represents this item.
  9584. */
  9585. virtual int64 hashCode() const = 0;
  9586. juce_UseDebuggingNewOperator
  9587. };
  9588. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9589. /********* End of inlined file: juce_InputSource.h *********/
  9590. /**
  9591. Decodes a ZIP file from a stream.
  9592. This can enumerate the items in a ZIP file and can create suitable stream objects
  9593. to read each one.
  9594. */
  9595. class JUCE_API ZipFile
  9596. {
  9597. public:
  9598. /** Creates a ZipFile for a given stream.
  9599. @param inputStream the stream to read from
  9600. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  9601. will be deleted when this ZipFile object is deleted
  9602. */
  9603. ZipFile (InputStream* const inputStream,
  9604. const bool deleteStreamWhenDestroyed) throw();
  9605. /** Creates a ZipFile based for a file. */
  9606. ZipFile (const File& file);
  9607. /** Creates a ZipFile for an input source.
  9608. The inputSource object will be owned by the zip file, which will delete
  9609. it later when not needed.
  9610. */
  9611. ZipFile (InputSource* const inputSource);
  9612. /** Destructor. */
  9613. ~ZipFile() throw();
  9614. /**
  9615. Contains information about one of the entries in a ZipFile.
  9616. @see ZipFile::getEntry
  9617. */
  9618. struct ZipEntry
  9619. {
  9620. /** The name of the file, which may also include a partial pathname. */
  9621. String filename;
  9622. /** The file's original size. */
  9623. unsigned int uncompressedSize;
  9624. /** The last time the file was modified. */
  9625. Time fileTime;
  9626. };
  9627. /** Returns the number of items in the zip file. */
  9628. int getNumEntries() const throw();
  9629. /** Returns a structure that describes one of the entries in the zip file.
  9630. This may return zero if the index is out of range.
  9631. @see ZipFile::ZipEntry
  9632. */
  9633. const ZipEntry* getEntry (const int index) const throw();
  9634. /** Returns the index of the first entry with a given filename.
  9635. This uses a case-sensitive comparison to look for a filename in the
  9636. list of entries. It might return -1 if no match is found.
  9637. @see ZipFile::ZipEntry
  9638. */
  9639. int getIndexOfFileName (const String& fileName) const throw();
  9640. /** Returns a structure that describes one of the entries in the zip file.
  9641. This uses a case-sensitive comparison to look for a filename in the
  9642. list of entries. It might return 0 if no match is found.
  9643. @see ZipFile::ZipEntry
  9644. */
  9645. const ZipEntry* getEntry (const String& fileName) const throw();
  9646. /** Sorts the list of entries, based on the filename.
  9647. */
  9648. void sortEntriesByFilename();
  9649. /** Creates a stream that can read from one of the zip file's entries.
  9650. The stream that is returned must be deleted by the caller (and
  9651. zero might be returned if a stream can't be opened for some reason).
  9652. The stream must not be used after the ZipFile object that created
  9653. has been deleted.
  9654. */
  9655. InputStream* createStreamForEntry (const int index);
  9656. /** Uncompresses all of the files in the zip file.
  9657. This will expand all the entires into a target directory. The relative
  9658. paths of the entries are used.
  9659. @param targetDirectory the root folder to uncompress to
  9660. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  9661. */
  9662. void uncompressTo (const File& targetDirectory,
  9663. const bool shouldOverwriteFiles = true);
  9664. juce_UseDebuggingNewOperator
  9665. private:
  9666. VoidArray entries;
  9667. friend class ZipInputStream;
  9668. CriticalSection lock;
  9669. InputStream* inputStream;
  9670. InputSource* inputSource;
  9671. bool deleteStreamWhenDestroyed;
  9672. int numEntries, centralRecStart;
  9673. #ifdef JUCE_DEBUG
  9674. int numOpenStreams;
  9675. #endif
  9676. void init();
  9677. int findEndOfZipEntryTable (InputStream* in);
  9678. ZipFile (const ZipFile&);
  9679. const ZipFile& operator= (const ZipFile&);
  9680. };
  9681. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  9682. /********* End of inlined file: juce_ZipFile.h *********/
  9683. #endif
  9684. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  9685. /********* Start of inlined file: juce_BlowFish.h *********/
  9686. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  9687. #define __JUCE_BLOWFISH_JUCEHEADER__
  9688. /**
  9689. BlowFish encryption class.
  9690. */
  9691. class JUCE_API BlowFish
  9692. {
  9693. public:
  9694. /** Creates an object that can encode/decode based on the specified key.
  9695. The key data can be up to 72 bytes long.
  9696. */
  9697. BlowFish (const uint8* keyData, int keyBytes);
  9698. /** Creates a copy of another blowfish object. */
  9699. BlowFish (const BlowFish& other);
  9700. /** Copies another blowfish object. */
  9701. const BlowFish& operator= (const BlowFish& other);
  9702. /** Destructor. */
  9703. ~BlowFish();
  9704. /** Encrypts a pair of 32-bit integers. */
  9705. void encrypt (uint32& data1, uint32& data2) const;
  9706. /** Decrypts a pair of 32-bit integers. */
  9707. void decrypt (uint32& data1, uint32& data2) const;
  9708. juce_UseDebuggingNewOperator
  9709. private:
  9710. uint32 p[18];
  9711. uint32* s[4];
  9712. uint32 F (uint32 x) const;
  9713. };
  9714. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  9715. /********* End of inlined file: juce_BlowFish.h *********/
  9716. #endif
  9717. #ifndef __JUCE_MD5_JUCEHEADER__
  9718. /********* Start of inlined file: juce_MD5.h *********/
  9719. #ifndef __JUCE_MD5_JUCEHEADER__
  9720. #define __JUCE_MD5_JUCEHEADER__
  9721. /**
  9722. MD5 checksum class.
  9723. Create one of these with a block of source data or a string, and it calculates the
  9724. MD5 checksum of that data.
  9725. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  9726. */
  9727. class JUCE_API MD5
  9728. {
  9729. public:
  9730. /** Creates a null MD5 object. */
  9731. MD5();
  9732. /** Creates a copy of another MD5. */
  9733. MD5 (const MD5& other);
  9734. /** Copies another MD5. */
  9735. const MD5& operator= (const MD5& other);
  9736. /** Creates a checksum for a block of binary data. */
  9737. MD5 (const MemoryBlock& data);
  9738. /** Creates a checksum for a block of binary data. */
  9739. MD5 (const char* data, const int numBytes);
  9740. /** Creates a checksum for a string.
  9741. Note that this operates on the string as a block of unicode characters, so the
  9742. result you get will differ from the value you'd get if the string was treated
  9743. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  9744. of this method with a checksum created by a different framework, which may have
  9745. used a different encoding.
  9746. */
  9747. MD5 (const String& text);
  9748. /** Creates a checksum for the input from a stream.
  9749. This will read up to the given number of bytes from the stream, and produce the
  9750. checksum of that. If the number of bytes to read is negative, it'll read
  9751. until the stream is exhausted.
  9752. */
  9753. MD5 (InputStream& input, int numBytesToRead = -1);
  9754. /** Creates a checksum for a file. */
  9755. MD5 (const File& file);
  9756. /** Destructor. */
  9757. ~MD5();
  9758. /** Returns the checksum as a 16-byte block of data. */
  9759. const MemoryBlock getRawChecksumData() const;
  9760. /** Returns the checksum as a 32-digit hex string. */
  9761. const String toHexString() const;
  9762. /** Compares this to another MD5. */
  9763. bool operator== (const MD5& other) const;
  9764. /** Compares this to another MD5. */
  9765. bool operator!= (const MD5& other) const;
  9766. juce_UseDebuggingNewOperator
  9767. private:
  9768. uint8 result [16];
  9769. struct ProcessContext
  9770. {
  9771. uint8 buffer [64];
  9772. uint32 state [4];
  9773. uint32 count [2];
  9774. ProcessContext();
  9775. void processBlock (const uint8* const data, int dataSize);
  9776. void transform (const uint8* const buffer);
  9777. void finish (uint8* const result);
  9778. };
  9779. void processStream (InputStream& input, int numBytesToRead);
  9780. };
  9781. #endif // __JUCE_MD5_JUCEHEADER__
  9782. /********* End of inlined file: juce_MD5.h *********/
  9783. #endif
  9784. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9785. /********* Start of inlined file: juce_Primes.h *********/
  9786. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9787. #define __JUCE_PRIMES_JUCEHEADER__
  9788. /**
  9789. Prime number creation class.
  9790. This class contains static methods for generating and testing prime numbers.
  9791. @see BitArray
  9792. */
  9793. class JUCE_API Primes
  9794. {
  9795. public:
  9796. /** Creates a random prime number with a given bit-length.
  9797. The certainty parameter specifies how many iterations to use when testing
  9798. for primality. A safe value might be anything over about 20-30.
  9799. The randomSeeds parameter lets you optionally pass it a set of values with
  9800. which to seed the random number generation, improving the security of the
  9801. keys generated.
  9802. */
  9803. static const BitArray createProbablePrime (int bitLength,
  9804. int certainty,
  9805. const int* randomSeeds = 0,
  9806. int numRandomSeeds = 0) throw();
  9807. /** Tests a number to see if it's prime.
  9808. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9809. whether the number is prime.
  9810. The certainty parameter specifies how many iterations to use when testing - a
  9811. safe value might be anything over about 20-30.
  9812. */
  9813. static bool isProbablyPrime (const BitArray& number,
  9814. int certainty) throw();
  9815. };
  9816. #endif // __JUCE_PRIMES_JUCEHEADER__
  9817. /********* End of inlined file: juce_Primes.h *********/
  9818. #endif
  9819. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9820. /********* Start of inlined file: juce_RSAKey.h *********/
  9821. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9822. #define __JUCE_RSAKEY_JUCEHEADER__
  9823. /**
  9824. RSA public/private key-pair encryption class.
  9825. An object of this type makes up one half of a public/private RSA key pair. Use the
  9826. createKeyPair() method to create a matching pair for encoding/decoding.
  9827. */
  9828. class JUCE_API RSAKey
  9829. {
  9830. public:
  9831. /** Creates a null key object.
  9832. Initialise a pair of objects for use with the createKeyPair() method.
  9833. */
  9834. RSAKey() throw();
  9835. /** Loads a key from an encoded string representation.
  9836. This reloads a key from a string created by the toString() method.
  9837. */
  9838. RSAKey (const String& stringRepresentation) throw();
  9839. /** Destructor. */
  9840. ~RSAKey() throw();
  9841. /** Turns the key into a string representation.
  9842. This can be reloaded using the constructor that takes a string.
  9843. */
  9844. const String toString() const throw();
  9845. /** Encodes or decodes a value.
  9846. Call this on the public key object to encode some data, then use the matching
  9847. private key object to decode it.
  9848. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  9849. initialised correctly.
  9850. NOTE: This method dumbly applies this key to this data. If you encode some data
  9851. and then try to decode it with a key that doesn't match, this method will still
  9852. happily do its job and return true, but the result won't be what you were expecting.
  9853. It's your responsibility to check that the result is what you wanted.
  9854. */
  9855. bool applyToValue (BitArray& value) const throw();
  9856. /** Creates a public/private key-pair.
  9857. Each key will perform one-way encryption that can only be reversed by
  9858. using the other key.
  9859. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9860. sizes are more secure, but this method will take longer to execute.
  9861. The randomSeeds parameter lets you optionally pass it a set of values with
  9862. which to seed the random number generation, improving the security of the
  9863. keys generated.
  9864. */
  9865. static void createKeyPair (RSAKey& publicKey,
  9866. RSAKey& privateKey,
  9867. const int numBits,
  9868. const int* randomSeeds = 0,
  9869. const int numRandomSeeds = 0) throw();
  9870. juce_UseDebuggingNewOperator
  9871. protected:
  9872. BitArray part1, part2;
  9873. };
  9874. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9875. /********* End of inlined file: juce_RSAKey.h *********/
  9876. #endif
  9877. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9878. /********* Start of inlined file: juce_Socket.h *********/
  9879. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9880. #define __JUCE_SOCKET_JUCEHEADER__
  9881. /**
  9882. A wrapper for a streaming (TCP) socket.
  9883. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9884. sockets, you could also try the InterprocessConnection class.
  9885. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9886. */
  9887. class JUCE_API StreamingSocket
  9888. {
  9889. public:
  9890. /** Creates an uninitialised socket.
  9891. To connect it, use the connect() method, after which you can read() or write()
  9892. to it.
  9893. To wait for other sockets to connect to this one, the createListener() method
  9894. enters "listener" mode, and can be used to spawn new sockets for each connection
  9895. that comes along.
  9896. */
  9897. StreamingSocket();
  9898. /** Destructor. */
  9899. ~StreamingSocket();
  9900. /** Binds the socket to the specified local port.
  9901. @returns true on success; false may indicate that another socket is already bound
  9902. on the same port
  9903. */
  9904. bool bindToPort (const int localPortNumber);
  9905. /** Tries to connect the socket to hostname:port.
  9906. If timeOutMillisecs is 0, then this method will block until the operating system
  9907. rejects the connection (which could take a long time).
  9908. @returns true if it succeeds.
  9909. @see isConnected
  9910. */
  9911. bool connect (const String& remoteHostname,
  9912. const int remotePortNumber,
  9913. const int timeOutMillisecs = 3000);
  9914. /** True if the socket is currently connected. */
  9915. bool isConnected() const throw() { return connected; }
  9916. /** Closes the connection. */
  9917. void close();
  9918. /** Returns the name of the currently connected host. */
  9919. const String& getHostName() const throw() { return hostName; }
  9920. /** Returns the port number that's currently open. */
  9921. int getPort() const throw() { return portNumber; }
  9922. /** True if the socket is connected to this machine rather than over the network. */
  9923. bool isLocal() const throw();
  9924. /** Waits until the socket is ready for reading or writing.
  9925. If readyForReading is true, it will wait until the socket is ready for
  9926. reading; if false, it will wait until it's ready for writing.
  9927. If the timeout is < 0, it will wait forever, or else will give up after
  9928. the specified time.
  9929. If the socket is ready on return, this returns 1. If it times-out before
  9930. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9931. */
  9932. int waitUntilReady (const bool readyForReading,
  9933. const int timeoutMsecs) const;
  9934. /** Reads bytes from the socket.
  9935. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  9936. maxBytesToRead bytes have been read, (or until an error occurs). If this
  9937. flag is false, the method will return as much data as is currently available
  9938. without blocking.
  9939. @returns the number of bytes read, or -1 if there was an error.
  9940. @see waitUntilReady
  9941. */
  9942. int read (void* destBuffer, const int maxBytesToRead,
  9943. const bool blockUntilSpecifiedAmountHasArrived);
  9944. /** Writes bytes to the socket from a buffer.
  9945. Note that this method will block unless you have checked the socket is ready
  9946. for writing before calling it (see the waitUntilReady() method).
  9947. @returns the number of bytes written, or -1 if there was an error.
  9948. */
  9949. int write (const void* sourceBuffer, const int numBytesToWrite);
  9950. /** Puts this socket into "listener" mode.
  9951. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9952. which will spawn new sockets for each new connection, so that these can
  9953. be handled in parallel by other threads.
  9954. @param portNumber the port number to listen on
  9955. @param localHostName the interface address to listen on - pass an empty
  9956. string to listen on all addresses
  9957. @returns true if it manages to open the socket successfully.
  9958. @see waitForNextConnection
  9959. */
  9960. bool createListener (const int portNumber, const String& localHostName = String::empty);
  9961. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9962. socket.
  9963. The object that gets returned will be owned by the caller.
  9964. This method can only be called after using createListener().
  9965. @see createListener
  9966. */
  9967. StreamingSocket* waitForNextConnection() const;
  9968. juce_UseDebuggingNewOperator
  9969. private:
  9970. String hostName;
  9971. int volatile portNumber, handle;
  9972. bool connected, isListener;
  9973. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9974. StreamingSocket (const StreamingSocket&);
  9975. const StreamingSocket& operator= (const StreamingSocket&);
  9976. };
  9977. /**
  9978. A wrapper for a datagram (UDP) socket.
  9979. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9980. sockets, you could also try the InterprocessConnection class.
  9981. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9982. */
  9983. class JUCE_API DatagramSocket
  9984. {
  9985. public:
  9986. /**
  9987. Creates an (uninitialised) datagram socket.
  9988. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9989. the port number is assigned by the operating system.
  9990. To use the socket for sending, call the connect() method. This will not immediately
  9991. make a connection, but will save the destination you've provided. After this, you can
  9992. call read() or write().
  9993. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  9994. (may require extra privileges on linux)
  9995. To wait for other sockets to connect to this one, call waitForNextConnection().
  9996. */
  9997. DatagramSocket (const int localPortNumber,
  9998. const bool enableBroadcasting = false);
  9999. /** Destructor. */
  10000. ~DatagramSocket();
  10001. /** Binds the socket to the specified local port.
  10002. @returns true on success; false may indicate that another socket is already bound
  10003. on the same port
  10004. */
  10005. bool bindToPort (const int localPortNumber);
  10006. /** Tries to connect the socket to hostname:port.
  10007. If timeOutMillisecs is 0, then this method will block until the operating system
  10008. rejects the connection (which could take a long time).
  10009. @returns true if it succeeds.
  10010. @see isConnected
  10011. */
  10012. bool connect (const String& remoteHostname,
  10013. const int remotePortNumber,
  10014. const int timeOutMillisecs = 3000);
  10015. /** True if the socket is currently connected. */
  10016. bool isConnected() const throw() { return connected; }
  10017. /** Closes the connection. */
  10018. void close();
  10019. /** Returns the name of the currently connected host. */
  10020. const String& getHostName() const throw() { return hostName; }
  10021. /** Returns the port number that's currently open. */
  10022. int getPort() const throw() { return portNumber; }
  10023. /** True if the socket is connected to this machine rather than over the network. */
  10024. bool isLocal() const throw();
  10025. /** Waits until the socket is ready for reading or writing.
  10026. If readyForReading is true, it will wait until the socket is ready for
  10027. reading; if false, it will wait until it's ready for writing.
  10028. If the timeout is < 0, it will wait forever, or else will give up after
  10029. the specified time.
  10030. If the socket is ready on return, this returns 1. If it times-out before
  10031. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  10032. */
  10033. int waitUntilReady (const bool readyForReading,
  10034. const int timeoutMsecs) const;
  10035. /** Reads bytes from the socket.
  10036. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  10037. maxBytesToRead bytes have been read, (or until an error occurs). If this
  10038. flag is false, the method will return as much data as is currently available
  10039. without blocking.
  10040. @returns the number of bytes read, or -1 if there was an error.
  10041. @see waitUntilReady
  10042. */
  10043. int read (void* destBuffer, const int maxBytesToRead,
  10044. const bool blockUntilSpecifiedAmountHasArrived);
  10045. /** Writes bytes to the socket from a buffer.
  10046. Note that this method will block unless you have checked the socket is ready
  10047. for writing before calling it (see the waitUntilReady() method).
  10048. @returns the number of bytes written, or -1 if there was an error.
  10049. */
  10050. int write (const void* sourceBuffer, const int numBytesToWrite);
  10051. /** This waits for incoming data to be sent, and returns a socket that can be used
  10052. to read it.
  10053. The object that gets returned is owned by the caller, and can't be used for
  10054. sending, but can be used to read the data.
  10055. */
  10056. DatagramSocket* waitForNextConnection() const;
  10057. juce_UseDebuggingNewOperator
  10058. private:
  10059. String hostName;
  10060. int volatile portNumber, handle;
  10061. bool connected, allowBroadcast;
  10062. void* serverAddress;
  10063. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  10064. DatagramSocket (const DatagramSocket&);
  10065. const DatagramSocket& operator= (const DatagramSocket&);
  10066. };
  10067. #endif // __JUCE_SOCKET_JUCEHEADER__
  10068. /********* End of inlined file: juce_Socket.h *********/
  10069. #endif
  10070. #ifndef __JUCE_URL_JUCEHEADER__
  10071. /********* Start of inlined file: juce_URL.h *********/
  10072. #ifndef __JUCE_URL_JUCEHEADER__
  10073. #define __JUCE_URL_JUCEHEADER__
  10074. /**
  10075. Represents a URL and has a bunch of useful functions to manipulate it.
  10076. This class can be used to launch URLs in browsers, and also to create
  10077. InputStreams that can read from remote http or ftp sources.
  10078. */
  10079. class JUCE_API URL
  10080. {
  10081. public:
  10082. /** Creates an empty URL. */
  10083. URL() throw();
  10084. /** Creates a URL from a string. */
  10085. URL (const String& url);
  10086. /** Creates a copy of another URL. */
  10087. URL (const URL& other);
  10088. /** Destructor. */
  10089. ~URL() throw();
  10090. /** Copies this URL from another one. */
  10091. const URL& operator= (const URL& other);
  10092. /** Returns a string version of the URL.
  10093. If includeGetParameters is true and any parameters have been set with the
  10094. withParameter() method, then the string will have these appended on the
  10095. end and url-encoded.
  10096. */
  10097. const String toString (const bool includeGetParameters) const;
  10098. /** True if it seems to be valid. */
  10099. bool isWellFormed() const;
  10100. /** Returns just the domain part of the URL.
  10101. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  10102. */
  10103. const String getDomain() const;
  10104. /** Returns the path part of the URL.
  10105. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  10106. */
  10107. const String getSubPath() const;
  10108. /** Returns the scheme of the URL.
  10109. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  10110. include the colon).
  10111. */
  10112. const String getScheme() const;
  10113. /** Returns a new version of this URL that uses a different sub-path.
  10114. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  10115. "bar", it'll return "http://www.xyz.com/bar?x=1".
  10116. */
  10117. const URL withNewSubPath (const String& newPath) const;
  10118. /** Returns a copy of this URL, with a GET parameter added to the end.
  10119. Any control characters in the value will be encoded.
  10120. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  10121. would produce a new url whose toString(true) method would return
  10122. "www.fish.com?amount=some+fish".
  10123. */
  10124. const URL withParameter (const String& parameterName,
  10125. const String& parameterValue) const;
  10126. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  10127. When performing a POST where one of your parameters is a binary file, this
  10128. lets you specify the file.
  10129. Note that the filename is stored, but the file itself won't actually be read
  10130. until this URL is later used to create a network input stream.
  10131. */
  10132. const URL withFileToUpload (const String& parameterName,
  10133. const File& fileToUpload,
  10134. const String& mimeType) const;
  10135. /** Returns a set of all the parameters encoded into the url.
  10136. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  10137. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  10138. The values returned will have been cleaned up to remove any escape characters.
  10139. @see getNamedParameter, withParameter
  10140. */
  10141. const StringPairArray& getParameters() const throw();
  10142. /** Returns the set of files that should be uploaded as part of a POST operation.
  10143. This is the set of files that were added to the URL with the withFileToUpload()
  10144. method.
  10145. */
  10146. const StringPairArray& getFilesToUpload() const throw();
  10147. /** Returns the set of mime types associated with each of the upload files.
  10148. */
  10149. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  10150. /** Returns a copy of this URL, with a block of data to send as the POST data.
  10151. If you're setting the POST data, be careful not to have any parameters set
  10152. as well, otherwise it'll all get thrown in together, and might not have the
  10153. desired effect.
  10154. If the URL already contains some POST data, this will replace it, rather
  10155. than being appended to it.
  10156. This data will only be used if you specify a post operation when you call
  10157. createInputStream().
  10158. */
  10159. const URL withPOSTData (const String& postData) const;
  10160. /** Returns the data that was set using withPOSTData().
  10161. */
  10162. const String getPostData() const throw() { return postData; }
  10163. /** Tries to launch the system's default browser to open the URL.
  10164. Returns true if this seems to have worked.
  10165. */
  10166. bool launchInDefaultBrowser() const;
  10167. /** Takes a guess as to whether a string might be a valid website address.
  10168. This isn't foolproof!
  10169. */
  10170. static bool isProbablyAWebsiteURL (const String& possibleURL);
  10171. /** Takes a guess as to whether a string might be a valid email address.
  10172. This isn't foolproof!
  10173. */
  10174. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  10175. /** This callback function can be used by the createInputStream() method.
  10176. It allows your app to receive progress updates during a lengthy POST operation. If you
  10177. want to continue the operation, this should return true, or false to abort.
  10178. */
  10179. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  10180. /** Attempts to open a stream that can read from this URL.
  10181. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  10182. the paramters, otherwise it'll encode them into the
  10183. URL and do a 'GET'.
  10184. @param progressCallback if this is non-zero, it lets you supply a callback function
  10185. to keep track of the operation's progress. This can be useful
  10186. for lengthy POST operations, so that you can provide user feedback.
  10187. @param progressCallbackContext if a callback is specified, this value will be passed to
  10188. the function
  10189. @param extraHeaders if not empty, this string is appended onto the headers that
  10190. are used for the request. It must therefore be a valid set of HTML
  10191. header directives, separated by newlines.
  10192. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  10193. a negative number, it will be infinite. Otherwise it specifies a
  10194. time in milliseconds.
  10195. */
  10196. InputStream* createInputStream (const bool usePostCommand,
  10197. OpenStreamProgressCallback* const progressCallback = 0,
  10198. void* const progressCallbackContext = 0,
  10199. const String& extraHeaders = String::empty,
  10200. const int connectionTimeOutMs = 0) const;
  10201. /** Tries to download the entire contents of this URL into a binary data block.
  10202. If it succeeds, this will return true and append the data it read onto the end
  10203. of the memory block.
  10204. @param destData the memory block to append the new data to
  10205. @param usePostCommand whether to use a POST command to get the data (uses
  10206. a GET command if this is false)
  10207. @see readEntireTextStream, readEntireXmlStream
  10208. */
  10209. bool readEntireBinaryStream (MemoryBlock& destData,
  10210. const bool usePostCommand = false) const;
  10211. /** Tries to download the entire contents of this URL as a string.
  10212. If it fails, this will return an empty string, otherwise it will return the
  10213. contents of the downloaded file. If you need to distinguish between a read
  10214. operation that fails and one that returns an empty string, you'll need to use
  10215. a different method, such as readEntireBinaryStream().
  10216. @param usePostCommand whether to use a POST command to get the data (uses
  10217. a GET command if this is false)
  10218. @see readEntireBinaryStream, readEntireXmlStream
  10219. */
  10220. const String readEntireTextStream (const bool usePostCommand = false) const;
  10221. /** Tries to download the entire contents of this URL and parse it as XML.
  10222. If it fails, or if the text that it reads can't be parsed as XML, this will
  10223. return 0.
  10224. When it returns a valid XmlElement object, the caller is responsibile for deleting
  10225. this object when no longer needed.
  10226. @param usePostCommand whether to use a POST command to get the data (uses
  10227. a GET command if this is false)
  10228. @see readEntireBinaryStream, readEntireTextStream
  10229. */
  10230. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  10231. /** Adds escape sequences to a string to encode any characters that aren't
  10232. legal in a URL.
  10233. E.g. any spaces will be replaced with "%20".
  10234. This is the opposite of removeEscapeChars().
  10235. If isParameter is true, it means that the string is going to be used
  10236. as a parameter, so it also encodes '$' and ',' (which would otherwise
  10237. be legal in a URL.
  10238. @see removeEscapeChars
  10239. */
  10240. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  10241. const bool isParameter);
  10242. /** Replaces any escape character sequences in a string with their original
  10243. character codes.
  10244. E.g. any instances of "%20" will be replaced by a space.
  10245. This is the opposite of addEscapeChars().
  10246. @see addEscapeChars
  10247. */
  10248. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  10249. juce_UseDebuggingNewOperator
  10250. private:
  10251. String url, postData;
  10252. StringPairArray parameters, filesToUpload, mimeTypes;
  10253. };
  10254. #endif // __JUCE_URL_JUCEHEADER__
  10255. /********* End of inlined file: juce_URL.h *********/
  10256. #endif
  10257. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10258. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  10259. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10260. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10261. /** Wraps another input stream, and reads from it using an intermediate buffer
  10262. If you're using an input stream such as a file input stream, and making lots of
  10263. small read accesses to it, it's probably sensible to wrap it in one of these,
  10264. so that the source stream gets accessed in larger chunk sizes, meaning less
  10265. work for the underlying stream.
  10266. */
  10267. class JUCE_API BufferedInputStream : public InputStream
  10268. {
  10269. public:
  10270. /** Creates a BufferedInputStream from an input source.
  10271. @param sourceStream the source stream to read from
  10272. @param bufferSize the size of reservoir to use to buffer the source
  10273. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  10274. deleted by this object when it is itself deleted.
  10275. */
  10276. BufferedInputStream (InputStream* const sourceStream,
  10277. const int bufferSize,
  10278. const bool deleteSourceWhenDestroyed) throw();
  10279. /** Destructor.
  10280. This may also delete the source stream, if that option was chosen when the
  10281. buffered stream was created.
  10282. */
  10283. ~BufferedInputStream() throw();
  10284. int64 getTotalLength();
  10285. int64 getPosition();
  10286. bool setPosition (int64 newPosition);
  10287. int read (void* destBuffer, int maxBytesToRead);
  10288. const String readString();
  10289. bool isExhausted();
  10290. juce_UseDebuggingNewOperator
  10291. private:
  10292. InputStream* const source;
  10293. const bool deleteSourceWhenDestroyed;
  10294. int bufferSize;
  10295. int64 position, lastReadPos, bufferStart, bufferOverlap;
  10296. char* buffer;
  10297. void ensureBuffered();
  10298. BufferedInputStream (const BufferedInputStream&);
  10299. const BufferedInputStream& operator= (const BufferedInputStream&);
  10300. };
  10301. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10302. /********* End of inlined file: juce_BufferedInputStream.h *********/
  10303. #endif
  10304. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10305. /********* Start of inlined file: juce_FileInputSource.h *********/
  10306. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10307. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10308. /**
  10309. A type of InputSource that represents a normal file.
  10310. @see InputSource
  10311. */
  10312. class JUCE_API FileInputSource : public InputSource
  10313. {
  10314. public:
  10315. FileInputSource (const File& file) throw();
  10316. ~FileInputSource();
  10317. InputStream* createInputStream();
  10318. InputStream* createInputStreamFor (const String& relatedItemPath);
  10319. int64 hashCode() const;
  10320. juce_UseDebuggingNewOperator
  10321. private:
  10322. const File file;
  10323. FileInputSource (const FileInputSource&);
  10324. const FileInputSource& operator= (const FileInputSource&);
  10325. };
  10326. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10327. /********* End of inlined file: juce_FileInputSource.h *********/
  10328. #endif
  10329. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10330. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  10331. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10332. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10333. /**
  10334. A stream which uses zlib to compress the data written into it.
  10335. @see GZIPDecompressorInputStream
  10336. */
  10337. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  10338. {
  10339. public:
  10340. /** Creates a compression stream.
  10341. @param destStream the stream into which the compressed data should
  10342. be written
  10343. @param compressionLevel how much to compress the data, between 1 and 9, where
  10344. 1 is the fastest/lowest compression, and 9 is the
  10345. slowest/highest compression. Any value outside this range
  10346. indicates that a default compression level should be used.
  10347. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  10348. this stream is destroyed
  10349. @param noWrap this is used internally by the ZipFile class
  10350. and should be ignored by user applications
  10351. */
  10352. GZIPCompressorOutputStream (OutputStream* const destStream,
  10353. int compressionLevel = 0,
  10354. const bool deleteDestStreamWhenDestroyed = false,
  10355. const bool noWrap = false);
  10356. /** Destructor. */
  10357. ~GZIPCompressorOutputStream();
  10358. void flush();
  10359. int64 getPosition();
  10360. bool setPosition (int64 newPosition);
  10361. bool write (const void* destBuffer, int howMany);
  10362. juce_UseDebuggingNewOperator
  10363. private:
  10364. OutputStream* const destStream;
  10365. const bool deleteDestStream;
  10366. uint8* buffer;
  10367. void* helper;
  10368. bool doNextBlock();
  10369. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  10370. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  10371. };
  10372. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10373. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  10374. #endif
  10375. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10376. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  10377. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10378. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10379. /**
  10380. This stream will decompress a source-stream using zlib.
  10381. Tip: if you're reading lots of small items from one of these streams, you
  10382. can increase the performance enormously by passing it through a
  10383. BufferedInputStream, so that it has to read larger blocks less often.
  10384. @see GZIPCompressorOutputStream
  10385. */
  10386. class JUCE_API GZIPDecompressorInputStream : public InputStream
  10387. {
  10388. public:
  10389. /** Creates a decompressor stream.
  10390. @param sourceStream the stream to read from
  10391. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  10392. when this object is destroyed
  10393. @param noWrap this is used internally by the ZipFile class
  10394. and should be ignored by user applications
  10395. @param uncompressedStreamLength if the creator knows the length that the
  10396. uncompressed stream will be, then it can supply this
  10397. value, which will be returned by getTotalLength()
  10398. */
  10399. GZIPDecompressorInputStream (InputStream* const sourceStream,
  10400. const bool deleteSourceWhenDestroyed,
  10401. const bool noWrap = false,
  10402. const int64 uncompressedStreamLength = -1);
  10403. /** Destructor. */
  10404. ~GZIPDecompressorInputStream();
  10405. int64 getPosition();
  10406. bool setPosition (int64 pos);
  10407. int64 getTotalLength();
  10408. bool isExhausted();
  10409. int read (void* destBuffer, int maxBytesToRead);
  10410. juce_UseDebuggingNewOperator
  10411. private:
  10412. InputStream* const sourceStream;
  10413. const int64 uncompressedStreamLength;
  10414. const bool deleteSourceWhenDestroyed, noWrap;
  10415. bool isEof;
  10416. int activeBufferSize;
  10417. int64 originalSourcePos, currentPos;
  10418. uint8* buffer;
  10419. void* helper;
  10420. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  10421. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  10422. };
  10423. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10424. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  10425. #endif
  10426. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  10427. #endif
  10428. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  10429. #endif
  10430. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10431. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  10432. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10433. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10434. /**
  10435. Allows a block of data and to be accessed as a stream.
  10436. This can either be used to refer to a shared block of memory, or can make its
  10437. own internal copy of the data when the MemoryInputStream is created.
  10438. */
  10439. class JUCE_API MemoryInputStream : public InputStream
  10440. {
  10441. public:
  10442. /** Creates a MemoryInputStream.
  10443. @param sourceData the block of data to use as the stream's source
  10444. @param sourceDataSize the number of bytes in the source data block
  10445. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  10446. the source data, so this data shouldn't be changed
  10447. for the lifetime of the stream; if this parameter is
  10448. true, the stream will make its own copy of the
  10449. data and use that.
  10450. */
  10451. MemoryInputStream (const void* const sourceData,
  10452. const int sourceDataSize,
  10453. const bool keepInternalCopyOfData) throw();
  10454. /** Destructor. */
  10455. ~MemoryInputStream() throw();
  10456. int64 getPosition();
  10457. bool setPosition (int64 pos);
  10458. int64 getTotalLength();
  10459. bool isExhausted();
  10460. int read (void* destBuffer, int maxBytesToRead);
  10461. juce_UseDebuggingNewOperator
  10462. private:
  10463. const char* data;
  10464. int dataSize, position;
  10465. MemoryBlock internalCopy;
  10466. };
  10467. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10468. /********* End of inlined file: juce_MemoryInputStream.h *********/
  10469. #endif
  10470. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10471. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  10472. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10473. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10474. /** Writes data to an internal memory buffer, which grows as required.
  10475. The data that was written into the stream can then be accessed later as
  10476. a contiguous block of memory.
  10477. */
  10478. class JUCE_API MemoryOutputStream : public OutputStream
  10479. {
  10480. public:
  10481. /** Creates a memory stream ready for writing into.
  10482. @param initialSize the intial amount of space to allocate for writing into
  10483. @param granularity the increments by which the internal storage will be increased
  10484. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  10485. place that the data gets stored. If it's zero, the stream
  10486. will allocate its own storage internally, which you can
  10487. access using getData() and getDataSize()
  10488. */
  10489. MemoryOutputStream (const int initialSize = 256,
  10490. const int granularity = 256,
  10491. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  10492. /** Destructor.
  10493. This will free any data that was written to it.
  10494. */
  10495. ~MemoryOutputStream() throw();
  10496. /** Returns a pointer to the data that has been written to the stream.
  10497. @see getDataSize
  10498. */
  10499. const char* getData() throw();
  10500. /** Returns the number of bytes of data that have been written to the stream.
  10501. @see getData
  10502. */
  10503. int getDataSize() const throw();
  10504. /** Resets the stream, clearing any data that has been written to it so far. */
  10505. void reset() throw();
  10506. void flush();
  10507. bool write (const void* buffer, int howMany);
  10508. int64 getPosition();
  10509. bool setPosition (int64 newPosition);
  10510. juce_UseDebuggingNewOperator
  10511. private:
  10512. MemoryBlock* data;
  10513. int position, size, blockSize;
  10514. bool ownsMemoryBlock;
  10515. };
  10516. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10517. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  10518. #endif
  10519. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  10520. #endif
  10521. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10522. /********* Start of inlined file: juce_SubregionStream.h *********/
  10523. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10524. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10525. /** Wraps another input stream, and reads from a specific part of it.
  10526. This lets you take a subsection of a stream and present it as an entire
  10527. stream in its own right.
  10528. */
  10529. class JUCE_API SubregionStream : public InputStream
  10530. {
  10531. public:
  10532. /** Creates a SubregionStream from an input source.
  10533. @param sourceStream the source stream to read from
  10534. @param startPositionInSourceStream this is the position in the source stream that
  10535. corresponds to position 0 in this stream
  10536. @param lengthOfSourceStream this specifies the maximum number of bytes
  10537. from the source stream that will be passed through
  10538. by this stream. When the position of this stream
  10539. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  10540. If the length passed in here is greater than the length
  10541. of the source stream (as returned by getTotalLength()),
  10542. then the smaller value will be used.
  10543. Passing a negative value for this parameter means it
  10544. will keep reading until the source's end-of-stream.
  10545. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  10546. deleted by this object when it is itself deleted.
  10547. */
  10548. SubregionStream (InputStream* const sourceStream,
  10549. const int64 startPositionInSourceStream,
  10550. const int64 lengthOfSourceStream,
  10551. const bool deleteSourceWhenDestroyed) throw();
  10552. /** Destructor.
  10553. This may also delete the source stream, if that option was chosen when the
  10554. buffered stream was created.
  10555. */
  10556. ~SubregionStream() throw();
  10557. int64 getTotalLength();
  10558. int64 getPosition();
  10559. bool setPosition (int64 newPosition);
  10560. int read (void* destBuffer, int maxBytesToRead);
  10561. bool isExhausted();
  10562. juce_UseDebuggingNewOperator
  10563. private:
  10564. InputStream* const source;
  10565. const bool deleteSourceWhenDestroyed;
  10566. const int64 startPositionInSourceStream, lengthOfSourceStream;
  10567. SubregionStream (const SubregionStream&);
  10568. const SubregionStream& operator= (const SubregionStream&);
  10569. };
  10570. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10571. /********* End of inlined file: juce_SubregionStream.h *********/
  10572. #endif
  10573. #ifndef __JUCE_STRING_JUCEHEADER__
  10574. #endif
  10575. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10576. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10577. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10578. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10579. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10580. string into a localised version using the LocalisedStrings class.
  10581. @see LocalisedStrings
  10582. */
  10583. #define TRANS(stringLiteral) \
  10584. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10585. /**
  10586. Used to convert strings to localised foreign-language versions.
  10587. This is basically a look-up table of strings and their translated equivalents.
  10588. It can be loaded from a text file, so that you can supply a set of localised
  10589. versions of strings that you use in your app.
  10590. To use it in your code, simply call the translate() method on each string that
  10591. might have foreign versions, and if none is found, the method will just return
  10592. the original string.
  10593. The translation file should start with some lines specifying a description of
  10594. the language it contains, and also a list of ISO country codes where it might
  10595. be appropriate to use the file. After that, each line of the file should contain
  10596. a pair of quoted strings with an '=' sign.
  10597. E.g. for a french translation, the file might be:
  10598. @code
  10599. language: French
  10600. countries: fr be mc ch lu
  10601. "hello" = "bonjour"
  10602. "goodbye" = "au revoir"
  10603. @endcode
  10604. If the strings need to contain a quote character, they can use '\"' instead, and
  10605. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10606. (you can use this to add comments).
  10607. Note that this is a singleton class, so don't create or destroy the object directly.
  10608. There's also a TRANS(text) macro defined to make it easy to use the this.
  10609. E.g. @code
  10610. printSomething (TRANS("hello"));
  10611. @endcode
  10612. This macro is used in the Juce classes themselves, so your application has a chance to
  10613. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10614. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10615. code).
  10616. */
  10617. class JUCE_API LocalisedStrings
  10618. {
  10619. public:
  10620. /** Creates a set of translations from the text of a translation file.
  10621. When you create one of these, you can call setCurrentMappings() to make it
  10622. the set of mappings that the system's using.
  10623. */
  10624. LocalisedStrings (const String& fileContents) throw();
  10625. /** Creates a set of translations from a file.
  10626. When you create one of these, you can call setCurrentMappings() to make it
  10627. the set of mappings that the system's using.
  10628. */
  10629. LocalisedStrings (const File& fileToLoad) throw();
  10630. /** Destructor. */
  10631. ~LocalisedStrings() throw();
  10632. /** Selects the current set of mappings to be used by the system.
  10633. The object you pass in will be automatically deleted when no longer needed, so
  10634. don't keep a pointer to it. You can also pass in zero to remove the current
  10635. mappings.
  10636. See also the TRANS() macro, which uses the current set to do its translation.
  10637. @see translateWithCurrentMappings
  10638. */
  10639. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10640. /** Returns the currently selected set of mappings.
  10641. This is the object that was last passed to setCurrentMappings(). It may
  10642. be 0 if none has been created.
  10643. */
  10644. static LocalisedStrings* getCurrentMappings() throw();
  10645. /** Tries to translate a string using the currently selected set of mappings.
  10646. If no mapping has been set, or if the mapping doesn't contain a translation
  10647. for the string, this will just return the original string.
  10648. See also the TRANS() macro, which uses this method to do its translation.
  10649. @see setCurrentMappings, getCurrentMappings
  10650. */
  10651. static const String translateWithCurrentMappings (const String& text) throw();
  10652. /** Tries to translate a string using the currently selected set of mappings.
  10653. If no mapping has been set, or if the mapping doesn't contain a translation
  10654. for the string, this will just return the original string.
  10655. See also the TRANS() macro, which uses this method to do its translation.
  10656. @see setCurrentMappings, getCurrentMappings
  10657. */
  10658. static const String translateWithCurrentMappings (const char* text) throw();
  10659. /** Attempts to look up a string and return its localised version.
  10660. If the string isn't found in the list, the original string will be returned.
  10661. */
  10662. const String translate (const String& text) const throw();
  10663. /** Returns the name of the language specified in the translation file.
  10664. This is specified in the file using a line starting with "language:", e.g.
  10665. @code
  10666. language: german
  10667. @endcode
  10668. */
  10669. const String getLanguageName() const throw() { return languageName; }
  10670. /** Returns the list of suitable country codes listed in the translation file.
  10671. These is specified in the file using a line starting with "countries:", e.g.
  10672. @code
  10673. countries: fr be mc ch lu
  10674. @endcode
  10675. The country codes are supposed to be 2-character ISO complient codes.
  10676. */
  10677. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10678. /** Indicates whether to use a case-insensitive search when looking up a string.
  10679. This defaults to true.
  10680. */
  10681. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  10682. juce_UseDebuggingNewOperator
  10683. private:
  10684. String languageName;
  10685. StringArray countryCodes;
  10686. StringPairArray translations;
  10687. void loadFromText (const String& fileContents) throw();
  10688. };
  10689. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10690. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10691. #endif
  10692. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10693. #endif
  10694. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10695. #endif
  10696. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10697. #endif
  10698. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10699. /********* Start of inlined file: juce_XmlDocument.h *********/
  10700. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10701. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10702. /**
  10703. Parses a text-based XML document and creates an XmlElement object from it.
  10704. The parser will parse DTDs to load external entities but won't
  10705. check the document for validity against the DTD.
  10706. e.g.
  10707. @code
  10708. XmlDocument myDocument (File ("myfile.xml"));
  10709. XmlElement* mainElement = myDocument.getDocumentElement();
  10710. if (mainElement == 0)
  10711. {
  10712. String error = myDocument.getLastParseError();
  10713. }
  10714. else
  10715. {
  10716. ..use the element
  10717. }
  10718. @endcode
  10719. @see XmlElement
  10720. */
  10721. class JUCE_API XmlDocument
  10722. {
  10723. public:
  10724. /** Creates an XmlDocument from the xml text.
  10725. The text doesn't actually get parsed until the getDocumentElement() method is
  10726. called.
  10727. */
  10728. XmlDocument (const String& documentText) throw();
  10729. /** Creates an XmlDocument from a file.
  10730. The text doesn't actually get parsed until the getDocumentElement() method is
  10731. called.
  10732. */
  10733. XmlDocument (const File& file);
  10734. /** Destructor. */
  10735. ~XmlDocument() throw();
  10736. /** Creates an XmlElement object to represent the main document node.
  10737. This method will do the actual parsing of the text, and if there's a
  10738. parse error, it may returns 0 (and you can find out the error using
  10739. the getLastParseError() method).
  10740. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10741. first section of the file, and will only
  10742. return the outer document element - this
  10743. allows quick checking of large files to
  10744. see if they contain the correct type of
  10745. tag, without having to parse the entire file
  10746. @returns a new XmlElement which the caller will need to delete, or null if
  10747. there was an error.
  10748. @see getLastParseError
  10749. */
  10750. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10751. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10752. @returns the error, or an empty string if there was no error.
  10753. */
  10754. const String& getLastParseError() const throw();
  10755. /** Sets an input source object to use for parsing documents that reference external entities.
  10756. If the document has been created from a file, this probably won't be needed, but
  10757. if you're parsing some text and there might be a DTD that references external
  10758. files, you may need to create a custom input source that can retrieve the
  10759. other files it needs.
  10760. The object that is passed-in will be deleted automatically when no longer needed.
  10761. @see InputSource
  10762. */
  10763. void setInputSource (InputSource* const newSource) throw();
  10764. /** Sets a flag to change the treatment of empty text elements.
  10765. If this is true (the default state), then any text elements that contain only
  10766. whitespace characters will be ingored during parsing. If you need to catch
  10767. whitespace-only text, then you should set this to false before calling the
  10768. getDocumentElement() method.
  10769. */
  10770. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  10771. juce_UseDebuggingNewOperator
  10772. private:
  10773. String originalText;
  10774. const tchar* input;
  10775. bool outOfData, errorOccurred;
  10776. bool identifierLookupTable [128];
  10777. String lastError, dtdText;
  10778. StringArray tokenisedDTD;
  10779. bool needToLoadDTD, ignoreEmptyTextElements;
  10780. InputSource* inputSource;
  10781. void setLastError (const String& desc, const bool carryOn) throw();
  10782. void skipHeader() throw();
  10783. void skipNextWhiteSpace() throw();
  10784. tchar readNextChar() throw();
  10785. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10786. void readChildElements (XmlElement* parent) throw();
  10787. int findNextTokenLength() throw();
  10788. void readQuotedString (String& result) throw();
  10789. void readEntity (String& result) throw();
  10790. const String getFileContents (const String& filename) const;
  10791. const String expandEntity (const String& entity);
  10792. const String expandExternalEntity (const String& entity);
  10793. const String getParameterEntity (const String& entity);
  10794. };
  10795. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10796. /********* End of inlined file: juce_XmlDocument.h *********/
  10797. #endif
  10798. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10799. #endif
  10800. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10801. #endif
  10802. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10803. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10804. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10805. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10806. /**
  10807. Acts as a critical section which processes can use to block each other.
  10808. @see CriticalSection
  10809. */
  10810. class JUCE_API InterProcessLock
  10811. {
  10812. public:
  10813. /** Creates a lock object.
  10814. @param name a name that processes will use to identify this lock object
  10815. */
  10816. InterProcessLock (const String& name) throw();
  10817. /** Destructor.
  10818. This will also release the lock if it's currently held by this process.
  10819. */
  10820. ~InterProcessLock() throw();
  10821. /** Attempts to lock the critical section.
  10822. @param timeOutMillisecs how many milliseconds to wait if the lock
  10823. is already held by another process - a value of
  10824. 0 will return immediately, negative values will wait
  10825. forever
  10826. @returns true if the lock could be gained within the timeout period, or
  10827. false if the timeout expired.
  10828. */
  10829. bool enter (int timeOutMillisecs = -1) throw();
  10830. /** Releases the lock if it's currently held by this process.
  10831. */
  10832. void exit() throw();
  10833. juce_UseDebuggingNewOperator
  10834. private:
  10835. void* internal;
  10836. String name;
  10837. int reentrancyLevel;
  10838. InterProcessLock (const InterProcessLock&);
  10839. const InterProcessLock& operator= (const InterProcessLock&);
  10840. };
  10841. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10842. /********* End of inlined file: juce_InterProcessLock.h *********/
  10843. #endif
  10844. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10845. /********* Start of inlined file: juce_Process.h *********/
  10846. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10847. #define __JUCE_PROCESS_JUCEHEADER__
  10848. /** Represents the current executable's process.
  10849. This contains methods for controlling the current application at the
  10850. process-level.
  10851. @see Thread, JUCEApplication
  10852. */
  10853. class JUCE_API Process
  10854. {
  10855. public:
  10856. enum ProcessPriority
  10857. {
  10858. LowPriority = 0,
  10859. NormalPriority = 1,
  10860. HighPriority = 2,
  10861. RealtimePriority = 3
  10862. };
  10863. /** Changes the current process's priority.
  10864. @param priority the process priority, where
  10865. 0=low, 1=normal, 2=high, 3=realtime
  10866. */
  10867. static void setPriority (const ProcessPriority priority);
  10868. /** Kills the current process immediately.
  10869. This is an emergency process terminator that kills the application
  10870. immediately - it's intended only for use only when something goes
  10871. horribly wrong.
  10872. @see JUCEApplication::quit
  10873. */
  10874. static void terminate();
  10875. /** Returns true if this application process is the one that the user is
  10876. currently using.
  10877. */
  10878. static bool isForegroundProcess() throw();
  10879. /** Raises the current process's privilege level.
  10880. Does nothing if this isn't supported by the current OS, or if process
  10881. privilege level is fixed.
  10882. */
  10883. static void raisePrivilege();
  10884. /** Lowers the current process's privilege level.
  10885. Does nothing if this isn't supported by the current OS, or if process
  10886. privilege level is fixed.
  10887. */
  10888. static void lowerPrivilege();
  10889. /** Returns true if this process is being hosted by a debugger.
  10890. */
  10891. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10892. };
  10893. #endif // __JUCE_PROCESS_JUCEHEADER__
  10894. /********* End of inlined file: juce_Process.h *********/
  10895. #endif
  10896. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10897. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10898. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10899. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10900. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10901. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10902. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10903. /**
  10904. Allows threads to wait for events triggered by other threads.
  10905. A thread can call wait() on a WaitableObject, and this will suspend the
  10906. calling thread until another thread wakes it up by calling the signal()
  10907. method.
  10908. */
  10909. class JUCE_API WaitableEvent
  10910. {
  10911. public:
  10912. /** Creates a WaitableEvent object. */
  10913. WaitableEvent() throw();
  10914. /** Destructor.
  10915. If other threads are waiting on this object when it gets deleted, this
  10916. can cause nasty errors, so be careful!
  10917. */
  10918. ~WaitableEvent() throw();
  10919. /** Suspends the calling thread until the event has been signalled.
  10920. This will wait until the object's signal() method is called by another thread,
  10921. or until the timeout expires.
  10922. After the event has been signalled, this method will return true and reset
  10923. the event.
  10924. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10925. value will cause it to wait forever.
  10926. @returns true if the object has been signalled, false if the timeout expires first.
  10927. @see signal, reset
  10928. */
  10929. bool wait (const int timeOutMilliseconds = -1) const throw();
  10930. /** Wakes up any threads that are currently waiting on this object.
  10931. If signal() is called when nothing is waiting, the next thread to call wait()
  10932. will return immediately and reset the signal.
  10933. @see wait, reset
  10934. */
  10935. void signal() const throw();
  10936. /** Resets the event to an unsignalled state.
  10937. If it's not already signalled, this does nothing.
  10938. */
  10939. void reset() const throw();
  10940. juce_UseDebuggingNewOperator
  10941. private:
  10942. void* internal;
  10943. WaitableEvent (const WaitableEvent&);
  10944. const WaitableEvent& operator= (const WaitableEvent&);
  10945. };
  10946. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10947. /********* End of inlined file: juce_WaitableEvent.h *********/
  10948. /********* Start of inlined file: juce_Thread.h *********/
  10949. #ifndef __JUCE_THREAD_JUCEHEADER__
  10950. #define __JUCE_THREAD_JUCEHEADER__
  10951. /**
  10952. Encapsulates a thread.
  10953. Subclasses derive from Thread and implement the run() method, in which they
  10954. do their business. The thread can then be started with the startThread() method
  10955. and controlled with various other methods.
  10956. This class also contains some thread-related static methods, such
  10957. as sleep(), yield(), getCurrentThreadId() etc.
  10958. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10959. MessageManagerLock
  10960. */
  10961. class JUCE_API Thread
  10962. {
  10963. public:
  10964. /**
  10965. Creates a thread.
  10966. When first created, the thread is not running. Use the startThread()
  10967. method to start it.
  10968. */
  10969. Thread (const String& threadName);
  10970. /** Destructor.
  10971. Deleting a Thread object that is running will only give the thread a
  10972. brief opportunity to stop itself cleanly, so it's recommended that you
  10973. should always call stopThread() with a decent timeout before deleting,
  10974. to avoid the thread being forcibly killed (which is a Bad Thing).
  10975. */
  10976. virtual ~Thread();
  10977. /** Must be implemented to perform the thread's actual code.
  10978. Remember that the thread must regularly check the threadShouldExit()
  10979. method whilst running, and if this returns true it should return from
  10980. the run() method as soon as possible to avoid being forcibly killed.
  10981. @see threadShouldExit, startThread
  10982. */
  10983. virtual void run() = 0;
  10984. // Thread control functions..
  10985. /** Starts the thread running.
  10986. This will start the thread's run() method.
  10987. (if it's already started, startThread() won't do anything).
  10988. @see stopThread
  10989. */
  10990. void startThread() throw();
  10991. /** Starts the thread with a given priority.
  10992. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10993. If the thread is already running, its priority will be changed.
  10994. @see startThread, setPriority
  10995. */
  10996. void startThread (const int priority) throw();
  10997. /** Attempts to stop the thread running.
  10998. This method will cause the threadShouldExit() method to return true
  10999. and call notify() in case the thread is currently waiting.
  11000. Hopefully the thread will then respond to this by exiting cleanly, and
  11001. the stopThread method will wait for a given time-period for this to
  11002. happen.
  11003. If the thread is stuck and fails to respond after the time-out, it gets
  11004. forcibly killed, which is a very bad thing to happen, as it could still
  11005. be holding locks, etc. which are needed by other parts of your program.
  11006. @param timeOutMilliseconds The number of milliseconds to wait for the
  11007. thread to finish before killing it by force. A negative
  11008. value in here will wait forever.
  11009. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  11010. */
  11011. void stopThread (const int timeOutMilliseconds) throw();
  11012. /** Returns true if the thread is currently active */
  11013. bool isThreadRunning() const throw();
  11014. /** Sets a flag to tell the thread it should stop.
  11015. Calling this means that the threadShouldExit() method will then return true.
  11016. The thread should be regularly checking this to see whether it should exit.
  11017. @see threadShouldExit
  11018. @see waitForThreadToExit
  11019. */
  11020. void signalThreadShouldExit() throw();
  11021. /** Checks whether the thread has been told to stop running.
  11022. Threads need to check this regularly, and if it returns true, they should
  11023. return from their run() method at the first possible opportunity.
  11024. @see signalThreadShouldExit
  11025. */
  11026. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  11027. /** Waits for the thread to stop.
  11028. This will waits until isThreadRunning() is false or until a timeout expires.
  11029. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  11030. is less than zero, it will wait forever.
  11031. @returns true if the thread exits, or false if the timeout expires first.
  11032. */
  11033. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  11034. /** Changes the thread's priority.
  11035. May return false if for some reason the priority can't be changed.
  11036. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  11037. of 5 is normal.
  11038. */
  11039. bool setPriority (const int priority) throw();
  11040. /** Changes the priority of the caller thread.
  11041. Similar to setPriority(), but this static method acts on the caller thread.
  11042. May return false if for some reason the priority can't be changed.
  11043. @see setPriority
  11044. */
  11045. static bool setCurrentThreadPriority (const int priority) throw();
  11046. /** Sets the affinity mask for the thread.
  11047. This will only have an effect next time the thread is started - i.e. if the
  11048. thread is already running when called, it'll have no effect.
  11049. @see setCurrentThreadAffinityMask
  11050. */
  11051. void setAffinityMask (const uint32 affinityMask) throw();
  11052. /** Changes the affinity mask for the caller thread.
  11053. This will change the affinity mask for the thread that calls this static method.
  11054. @see setAffinityMask
  11055. */
  11056. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  11057. // this can be called from any thread that needs to pause..
  11058. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  11059. /** Yields the calling thread's current time-slot. */
  11060. static void JUCE_CALLTYPE yield() throw();
  11061. /** Makes the thread wait for a notification.
  11062. This puts the thread to sleep until either the timeout period expires, or
  11063. another thread calls the notify() method to wake it up.
  11064. @returns true if the event has been signalled, false if the timeout expires.
  11065. */
  11066. bool wait (const int timeOutMilliseconds) const throw();
  11067. /** Wakes up the thread.
  11068. If the thread has called the wait() method, this will wake it up.
  11069. @see wait
  11070. */
  11071. void notify() const throw();
  11072. /** A value type used for thread IDs.
  11073. @see getCurrentThreadId(), getThreadId()
  11074. */
  11075. typedef void* ThreadID;
  11076. /** Returns an id that identifies the caller thread.
  11077. To find the ID of a particular thread object, use getThreadId().
  11078. @returns a unique identifier that identifies the calling thread.
  11079. @see getThreadId
  11080. */
  11081. static ThreadID getCurrentThreadId() throw();
  11082. /** Finds the thread object that is currently running.
  11083. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  11084. object associated with them, so this will return 0.
  11085. */
  11086. static Thread* getCurrentThread() throw();
  11087. /** Returns the ID of this thread.
  11088. That means the ID of this thread object - not of the thread that's calling the method.
  11089. This can change when the thread is started and stopped, and will be invalid if the
  11090. thread's not actually running.
  11091. @see getCurrentThreadId
  11092. */
  11093. ThreadID getThreadId() const throw();
  11094. /** Returns the name of the thread.
  11095. This is the name that gets set in the constructor.
  11096. */
  11097. const String getThreadName() const throw() { return threadName_; }
  11098. /** Returns the number of currently-running threads.
  11099. @returns the number of Thread objects known to be currently running.
  11100. @see stopAllThreads
  11101. */
  11102. static int getNumRunningThreads() throw();
  11103. /** Tries to stop all currently-running threads.
  11104. This will attempt to stop all the threads known to be running at the moment.
  11105. */
  11106. static void stopAllThreads (const int timeoutInMillisecs) throw();
  11107. juce_UseDebuggingNewOperator
  11108. private:
  11109. const String threadName_;
  11110. void* volatile threadHandle_;
  11111. CriticalSection startStopLock;
  11112. WaitableEvent startSuspensionEvent_, defaultEvent_;
  11113. int threadPriority_;
  11114. ThreadID threadId_;
  11115. uint32 affinityMask_;
  11116. bool volatile threadShouldExit_;
  11117. friend void JUCE_API juce_threadEntryPoint (void*);
  11118. static void threadEntryPoint (Thread* thread) throw();
  11119. Thread (const Thread&);
  11120. const Thread& operator= (const Thread&);
  11121. };
  11122. #endif // __JUCE_THREAD_JUCEHEADER__
  11123. /********* End of inlined file: juce_Thread.h *********/
  11124. /**
  11125. A critical section that allows multiple simultaneous readers.
  11126. Features of this type of lock are:
  11127. - Multiple readers can hold the lock at the same time, but only one writer
  11128. can hold it at once.
  11129. - Writers trying to gain the lock will be blocked until all readers and writers
  11130. have released it
  11131. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  11132. blocked until the writer has obtained and released it
  11133. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  11134. there are no other readers
  11135. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  11136. - Recursive locking is supported.
  11137. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  11138. */
  11139. class JUCE_API ReadWriteLock
  11140. {
  11141. public:
  11142. /**
  11143. Creates a ReadWriteLock object.
  11144. */
  11145. ReadWriteLock() throw();
  11146. /** Destructor.
  11147. If the object is deleted whilst locked, any subsequent behaviour
  11148. is unpredictable.
  11149. */
  11150. ~ReadWriteLock() throw();
  11151. /** Locks this object for reading.
  11152. Multiple threads can simulaneously lock the object for reading, but if another
  11153. thread has it locked for writing, then this will block until it releases the
  11154. lock.
  11155. @see exitRead, ScopedReadLock
  11156. */
  11157. void enterRead() const throw();
  11158. /** Releases the read-lock.
  11159. If the caller thread hasn't got the lock, this can have unpredictable results.
  11160. If the enterRead() method has been called multiple times by the thread, each
  11161. call must be matched by a call to exitRead() before other threads will be allowed
  11162. to take over the lock.
  11163. @see enterRead, ScopedReadLock
  11164. */
  11165. void exitRead() const throw();
  11166. /** Locks this object for writing.
  11167. This will block until any other threads that have it locked for reading or
  11168. writing have released their lock.
  11169. @see exitWrite, ScopedWriteLock
  11170. */
  11171. void enterWrite() const throw();
  11172. /** Tries to lock this object for writing.
  11173. This is like enterWrite(), but doesn't block - it returns true if it manages
  11174. to obtain the lock.
  11175. @see enterWrite
  11176. */
  11177. bool tryEnterWrite() const throw();
  11178. /** Releases the write-lock.
  11179. If the caller thread hasn't got the lock, this can have unpredictable results.
  11180. If the enterWrite() method has been called multiple times by the thread, each
  11181. call must be matched by a call to exit() before other threads will be allowed
  11182. to take over the lock.
  11183. @see enterWrite, ScopedWriteLock
  11184. */
  11185. void exitWrite() const throw();
  11186. juce_UseDebuggingNewOperator
  11187. private:
  11188. CriticalSection accessLock;
  11189. WaitableEvent waitEvent;
  11190. mutable int numWaitingWriters, numWriters;
  11191. mutable Thread::ThreadID writerThreadId;
  11192. mutable Array <Thread::ThreadID> readerThreads;
  11193. ReadWriteLock (const ReadWriteLock&);
  11194. const ReadWriteLock& operator= (const ReadWriteLock&);
  11195. };
  11196. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  11197. /********* End of inlined file: juce_ReadWriteLock.h *********/
  11198. #endif
  11199. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  11200. #endif
  11201. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11202. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  11203. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11204. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11205. /**
  11206. Automatically locks and unlocks a ReadWriteLock object.
  11207. Use one of these as a local variable to control access to a ReadWriteLock.
  11208. e.g. @code
  11209. ReadWriteLock myLock;
  11210. for (;;)
  11211. {
  11212. const ScopedReadLock myScopedLock (myLock);
  11213. // myLock is now locked
  11214. ...do some stuff...
  11215. // myLock gets unlocked here.
  11216. }
  11217. @endcode
  11218. @see ReadWriteLock, ScopedWriteLock
  11219. */
  11220. class JUCE_API ScopedReadLock
  11221. {
  11222. public:
  11223. /** Creates a ScopedReadLock.
  11224. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  11225. when the ScopedReadLock object is deleted, the ReadWriteLock will
  11226. be unlocked.
  11227. Make sure this object is created and deleted by the same thread,
  11228. otherwise there are no guarantees what will happen! Best just to use it
  11229. as a local stack object, rather than creating one with the new() operator.
  11230. */
  11231. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  11232. /** Destructor.
  11233. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  11234. Make sure this object is created and deleted by the same thread,
  11235. otherwise there are no guarantees what will happen!
  11236. */
  11237. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  11238. private:
  11239. const ReadWriteLock& lock_;
  11240. ScopedReadLock (const ScopedReadLock&);
  11241. const ScopedReadLock& operator= (const ScopedReadLock&);
  11242. };
  11243. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11244. /********* End of inlined file: juce_ScopedReadLock.h *********/
  11245. #endif
  11246. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11247. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  11248. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11249. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11250. /**
  11251. Automatically tries to lock and unlock a CriticalSection object.
  11252. Use one of these as a local variable to control access to a CriticalSection.
  11253. e.g. @code
  11254. CriticalSection myCriticalSection;
  11255. for (;;)
  11256. {
  11257. const ScopedTryLock myScopedTryLock (myCriticalSection);
  11258. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  11259. // should test this with the isLocked() method before doing your thread-unsafe
  11260. // action..
  11261. if (myScopedTryLock.isLocked())
  11262. {
  11263. ...do some stuff...
  11264. }
  11265. else
  11266. {
  11267. ..our attempt at locking failed because another thread had already locked it..
  11268. }
  11269. // myCriticalSection gets unlocked here (if it was locked)
  11270. }
  11271. @endcode
  11272. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  11273. */
  11274. class JUCE_API ScopedTryLock
  11275. {
  11276. public:
  11277. /** Creates a ScopedTryLock.
  11278. As soon as it is created, this will try to lock the CriticalSection, and
  11279. when the ScopedTryLock object is deleted, the CriticalSection will
  11280. be unlocked if the lock was successful.
  11281. Make sure this object is created and deleted by the same thread,
  11282. otherwise there are no guarantees what will happen! Best just to use it
  11283. as a local stack object, rather than creating one with the new() operator.
  11284. */
  11285. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  11286. /** Destructor.
  11287. The CriticalSection will be unlocked (if locked) when the destructor is called.
  11288. Make sure this object is created and deleted by the same thread,
  11289. otherwise there are no guarantees what will happen!
  11290. */
  11291. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  11292. /** Lock state
  11293. @return True if the CriticalSection is locked.
  11294. */
  11295. bool isLocked() const throw() { return lockWasSuccessful; }
  11296. private:
  11297. const CriticalSection& lock_;
  11298. const bool lockWasSuccessful;
  11299. ScopedTryLock (const ScopedTryLock&);
  11300. const ScopedTryLock& operator= (const ScopedTryLock&);
  11301. };
  11302. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11303. /********* End of inlined file: juce_ScopedTryLock.h *********/
  11304. #endif
  11305. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11306. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  11307. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11308. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11309. /**
  11310. Automatically locks and unlocks a ReadWriteLock object.
  11311. Use one of these as a local variable to control access to a ReadWriteLock.
  11312. e.g. @code
  11313. ReadWriteLock myLock;
  11314. for (;;)
  11315. {
  11316. const ScopedWriteLock myScopedLock (myLock);
  11317. // myLock is now locked
  11318. ...do some stuff...
  11319. // myLock gets unlocked here.
  11320. }
  11321. @endcode
  11322. @see ReadWriteLock, ScopedReadLock
  11323. */
  11324. class JUCE_API ScopedWriteLock
  11325. {
  11326. public:
  11327. /** Creates a ScopedWriteLock.
  11328. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  11329. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  11330. be unlocked.
  11331. Make sure this object is created and deleted by the same thread,
  11332. otherwise there are no guarantees what will happen! Best just to use it
  11333. as a local stack object, rather than creating one with the new() operator.
  11334. */
  11335. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  11336. /** Destructor.
  11337. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  11338. Make sure this object is created and deleted by the same thread,
  11339. otherwise there are no guarantees what will happen!
  11340. */
  11341. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  11342. private:
  11343. const ReadWriteLock& lock_;
  11344. ScopedWriteLock (const ScopedWriteLock&);
  11345. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  11346. };
  11347. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11348. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  11349. #endif
  11350. #ifndef __JUCE_THREAD_JUCEHEADER__
  11351. #endif
  11352. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11353. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11354. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11355. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11356. /**
  11357. Used by the TimeSliceThread class.
  11358. To register your class with a TimeSliceThread, derive from this class and
  11359. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11360. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11361. deleting your client!
  11362. @see TimeSliceThread
  11363. */
  11364. class JUCE_API TimeSliceClient
  11365. {
  11366. public:
  11367. /** Destructor. */
  11368. virtual ~TimeSliceClient() {}
  11369. /** Called back by a TimeSliceThread.
  11370. When you register this class with it, a TimeSliceThread will repeatedly call
  11371. this method.
  11372. The implementation of this method should use its time-slice to do something that's
  11373. quick - never block for longer than absolutely necessary.
  11374. @returns Your method should return true if it needs more time, or false if it's
  11375. not too busy and doesn't need calling back urgently. If all the thread's
  11376. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11377. up to half a second in between callbacks. You can force the TimeSliceThread
  11378. to wake up and poll again immediately by calling its notify() method.
  11379. */
  11380. virtual bool useTimeSlice() = 0;
  11381. };
  11382. /**
  11383. A thread that keeps a list of clients, and calls each one in turn, giving them
  11384. all a chance to run some sort of short task.
  11385. @see TimeSliceClient, Thread
  11386. */
  11387. class JUCE_API TimeSliceThread : public Thread
  11388. {
  11389. public:
  11390. /**
  11391. Creates a TimeSliceThread.
  11392. When first created, the thread is not running. Use the startThread()
  11393. method to start it.
  11394. */
  11395. TimeSliceThread (const String& threadName);
  11396. /** Destructor.
  11397. Deleting a Thread object that is running will only give the thread a
  11398. brief opportunity to stop itself cleanly, so it's recommended that you
  11399. should always call stopThread() with a decent timeout before deleting,
  11400. to avoid the thread being forcibly killed (which is a Bad Thing).
  11401. */
  11402. ~TimeSliceThread();
  11403. /** Adds a client to the list.
  11404. The client's callbacks will start immediately (possibly before the method
  11405. has returned).
  11406. */
  11407. void addTimeSliceClient (TimeSliceClient* const client);
  11408. /** Removes a client from the list.
  11409. This method will make sure that all callbacks to the client have completely
  11410. finished before the method returns.
  11411. */
  11412. void removeTimeSliceClient (TimeSliceClient* const client);
  11413. /** Returns the number of registered clients. */
  11414. int getNumClients() const throw();
  11415. /** Returns one of the registered clients. */
  11416. TimeSliceClient* getClient (const int index) const throw();
  11417. /** @internal */
  11418. void run();
  11419. juce_UseDebuggingNewOperator
  11420. private:
  11421. CriticalSection callbackLock, listLock;
  11422. Array <TimeSliceClient*> clients;
  11423. int index;
  11424. TimeSliceClient* clientBeingCalled;
  11425. bool clientsChanged;
  11426. TimeSliceThread (const TimeSliceThread&);
  11427. const TimeSliceThread& operator= (const TimeSliceThread&);
  11428. };
  11429. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11430. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11431. #endif
  11432. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11433. #endif
  11434. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11435. /********* Start of inlined file: juce_ThreadPool.h *********/
  11436. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11437. #define __JUCE_THREADPOOL_JUCEHEADER__
  11438. class ThreadPool;
  11439. class ThreadPoolThread;
  11440. /**
  11441. A task that is executed by a ThreadPool object.
  11442. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  11443. its threads.
  11444. The runJob() method needs to be implemented to do the task, and if the code that
  11445. does the work takes a significant time to run, it must keep checking the shouldExit()
  11446. method to see if something is trying to interrupt the job. If shouldExit() returns
  11447. true, the runJob() method must return immediately.
  11448. @see ThreadPool, Thread
  11449. */
  11450. class JUCE_API ThreadPoolJob
  11451. {
  11452. public:
  11453. /** Creates a thread pool job object.
  11454. After creating your job, add it to a thread pool with ThreadPool::addJob().
  11455. */
  11456. ThreadPoolJob (const String& name);
  11457. /** Destructor. */
  11458. virtual ~ThreadPoolJob();
  11459. /** Returns the name of this job.
  11460. @see setJobName
  11461. */
  11462. const String getJobName() const throw();
  11463. /** Changes the job's name.
  11464. @see getJobName
  11465. */
  11466. void setJobName (const String& newName) throw();
  11467. /** These are the values that can be returned by the runJob() method.
  11468. */
  11469. enum JobStatus
  11470. {
  11471. jobHasFinished = 0, /**< indicates that the job has finished and can be
  11472. removed from the pool. */
  11473. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  11474. should be automatically deleted by the pool. */
  11475. jobNeedsRunningAgain /**< indicates that the job would like to be called
  11476. again when a thread is free. */
  11477. };
  11478. /** Peforms the actual work that this job needs to do.
  11479. Your subclass must implement this method, in which is does its work.
  11480. If the code in this method takes a significant time to run, it must repeatedly check
  11481. the shouldExit() method to see if something is trying to interrupt the job.
  11482. If shouldExit() ever returns true, the runJob() method must return immediately.
  11483. If this method returns jobHasFinished, then the job will be removed from the pool
  11484. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  11485. pool and will get a chance to run again as soon as a thread is free.
  11486. @see shouldExit()
  11487. */
  11488. virtual JobStatus runJob() = 0;
  11489. /** Returns true if this job is currently running its runJob() method. */
  11490. bool isRunning() const throw() { return isActive; }
  11491. /** Returns true if something is trying to interrupt this job and make it stop.
  11492. Your runJob() method must call this whenever it gets a chance, and if it ever
  11493. returns true, the runJob() method must return immediately.
  11494. @see signalJobShouldExit()
  11495. */
  11496. bool shouldExit() const throw() { return shouldStop; }
  11497. /** Calling this will cause the shouldExit() method to return true, and the job
  11498. should (if it's been implemented correctly) stop as soon as possible.
  11499. @see shouldExit()
  11500. */
  11501. void signalJobShouldExit() throw();
  11502. juce_UseDebuggingNewOperator
  11503. private:
  11504. friend class ThreadPool;
  11505. friend class ThreadPoolThread;
  11506. String jobName;
  11507. ThreadPool* pool;
  11508. bool shouldStop, isActive, shouldBeDeleted;
  11509. ThreadPoolJob (const ThreadPoolJob&);
  11510. const ThreadPoolJob& operator= (const ThreadPoolJob&);
  11511. };
  11512. /**
  11513. A set of threads that will run a list of jobs.
  11514. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11515. will be called by the next pooled thread that becomes free.
  11516. @see ThreadPoolJob, Thread
  11517. */
  11518. class JUCE_API ThreadPool
  11519. {
  11520. public:
  11521. /** Creates a thread pool.
  11522. Once you've created a pool, you can give it some things to do with the addJob()
  11523. method.
  11524. @param numberOfThreads the maximum number of actual threads to run.
  11525. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11526. until there are some jobs to run. If false, then
  11527. all the threads will be fired-up immediately so that
  11528. they're ready for action
  11529. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11530. inactive for this length of time, they will automatically
  11531. be stopped until more jobs come along and they're needed
  11532. */
  11533. ThreadPool (const int numberOfThreads,
  11534. const bool startThreadsOnlyWhenNeeded = true,
  11535. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11536. /** Destructor.
  11537. This will attempt to remove all the jobs before deleting, but if you want to
  11538. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11539. the pool.
  11540. */
  11541. ~ThreadPool();
  11542. /** Adds a job to the queue.
  11543. Once a job has been added, then the next time a thread is free, it will run
  11544. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11545. runJob() method, the pool will either remove the job from the pool or add it to
  11546. the back of the queue to be run again.
  11547. */
  11548. void addJob (ThreadPoolJob* const job);
  11549. /** Tries to remove a job from the pool.
  11550. If the job isn't yet running, this will simply remove it. If it is running, it
  11551. will wait for it to finish.
  11552. If the timeout period expires before the job finishes running, then the job will be
  11553. left in the pool and this will return false. It returns true if the job is sucessfully
  11554. stopped and removed.
  11555. @param job the job to remove
  11556. @param interruptIfRunning if true, then if the job is currently busy, its
  11557. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11558. to interrupt it. If false, then if the job will be allowed to run
  11559. until it stops normally (or the timeout expires)
  11560. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11561. before giving up and returning false
  11562. */
  11563. bool removeJob (ThreadPoolJob* const job,
  11564. const bool interruptIfRunning,
  11565. const int timeOutMilliseconds);
  11566. /** Tries clear all jobs from the pool.
  11567. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11568. methods called to try to interrupt them
  11569. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11570. before giving up and returning false
  11571. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  11572. they will simply be removed from the pool. Jobs that are already running when
  11573. this method is called can choose whether they should be deleted by
  11574. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  11575. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11576. expires while waiting for them to stop
  11577. */
  11578. bool removeAllJobs (const bool interruptRunningJobs,
  11579. const int timeOutMilliseconds,
  11580. const bool deleteInactiveJobs = false);
  11581. /** Returns the number of jobs currently running or queued.
  11582. */
  11583. int getNumJobs() const throw();
  11584. /** Returns one of the jobs in the queue.
  11585. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11586. around in the list, and this method may return 0 if the index is currently out-of-range.
  11587. */
  11588. ThreadPoolJob* getJob (const int index) const throw();
  11589. /** Returns true if the given job is currently queued or running.
  11590. @see isJobRunning()
  11591. */
  11592. bool contains (const ThreadPoolJob* const job) const throw();
  11593. /** Returns true if the given job is currently being run by a thread.
  11594. */
  11595. bool isJobRunning (const ThreadPoolJob* const job) const;
  11596. /** Waits until a job has finished running and has been removed from the pool.
  11597. This will wait until the job is no longer in the pool - i.e. until its
  11598. runJob() method returns ThreadPoolJob::jobHasFinished.
  11599. If the timeout period expires before the job finishes, this will return false;
  11600. it returns true if the job has finished successfully.
  11601. */
  11602. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11603. const int timeOutMilliseconds) const;
  11604. /** Returns a list of the names of all the jobs currently running or queued.
  11605. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11606. */
  11607. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const throw();
  11608. /** Changes the priority of all the threads.
  11609. This will call Thread::setPriority() for each thread in the pool.
  11610. May return false if for some reason the priority can't be changed.
  11611. */
  11612. bool setThreadPriorities (const int newPriority);
  11613. juce_UseDebuggingNewOperator
  11614. private:
  11615. const int numThreads, threadStopTimeout;
  11616. int priority;
  11617. Thread** threads;
  11618. VoidArray jobs;
  11619. CriticalSection lock;
  11620. uint32 lastJobEndTime;
  11621. WaitableEvent jobFinishedSignal;
  11622. friend class ThreadPoolThread;
  11623. bool runNextJob();
  11624. ThreadPool (const ThreadPool&);
  11625. const ThreadPool& operator= (const ThreadPool&);
  11626. };
  11627. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11628. /********* End of inlined file: juce_ThreadPool.h *********/
  11629. #endif
  11630. #endif
  11631. /********* End of inlined file: juce_core_includes.h *********/
  11632. // if you're compiling a command-line app, you might want to just include the core headers,
  11633. // so you can set this macro before including juce.h
  11634. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11635. /********* Start of inlined file: juce_app_includes.h *********/
  11636. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11637. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11638. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11639. /********* Start of inlined file: juce_Application.h *********/
  11640. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11641. #define __JUCE_APPLICATION_JUCEHEADER__
  11642. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11643. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11644. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11645. /********* Start of inlined file: juce_Component.h *********/
  11646. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11647. #define __JUCE_COMPONENT_JUCEHEADER__
  11648. /********* Start of inlined file: juce_MouseCursor.h *********/
  11649. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11650. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11651. class Image;
  11652. class RefCountedMouseCursor;
  11653. class ComponentPeer;
  11654. class Component;
  11655. /**
  11656. Represents a mouse cursor image.
  11657. This object can either be used to represent one of the standard mouse
  11658. cursor shapes, or a custom one generated from an image.
  11659. */
  11660. class JUCE_API MouseCursor
  11661. {
  11662. public:
  11663. /** The set of available standard mouse cursors. */
  11664. enum StandardCursorType
  11665. {
  11666. NoCursor = 0, /**< An invisible cursor. */
  11667. NormalCursor, /**< The stardard arrow cursor. */
  11668. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11669. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11670. CrosshairCursor, /**< A pair of crosshairs. */
  11671. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11672. that you're dragging a copy of something. */
  11673. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11674. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11675. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11676. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11677. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11678. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11679. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11680. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11681. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11682. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11683. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11684. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11685. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11686. };
  11687. /** Creates the standard arrow cursor. */
  11688. MouseCursor() throw();
  11689. /** Creates one of the standard mouse cursor */
  11690. MouseCursor (const StandardCursorType type) throw();
  11691. /** Creates a custom cursor from an image.
  11692. @param image the image to use for the cursor - if this is bigger than the
  11693. system can manage, it might get scaled down first, and might
  11694. also have to be turned to black-and-white if it can't do colour
  11695. cursors.
  11696. @param hotSpotX the x position of the cursor's hotspot within the image
  11697. @param hotSpotY the y position of the cursor's hotspot within the image
  11698. */
  11699. MouseCursor (Image& image,
  11700. const int hotSpotX,
  11701. const int hotSpotY) throw();
  11702. /** Creates a copy of another cursor object. */
  11703. MouseCursor (const MouseCursor& other) throw();
  11704. /** Copies this cursor from another object. */
  11705. const MouseCursor& operator= (const MouseCursor& other) throw();
  11706. /** Destructor. */
  11707. ~MouseCursor() throw();
  11708. /** Checks whether two mouse cursors are the same.
  11709. For custom cursors, two cursors created from the same image won't be
  11710. recognised as the same, only MouseCursor objects that have been
  11711. copied from the same object.
  11712. */
  11713. bool operator== (const MouseCursor& other) const throw();
  11714. /** Checks whether two mouse cursors are the same.
  11715. For custom cursors, two cursors created from the same image won't be
  11716. recognised as the same, only MouseCursor objects that have been
  11717. copied from the same object.
  11718. */
  11719. bool operator!= (const MouseCursor& other) const throw();
  11720. /** Makes the system show its default 'busy' cursor.
  11721. This will turn the system cursor to an hourglass or spinning beachball
  11722. until the next time the mouse is moved, or hideWaitCursor() is called.
  11723. This is handy if the message loop is about to block for a couple of
  11724. seconds while busy and you want to give the user feedback about this.
  11725. @see MessageManager::setTimeBeforeShowingWaitCursor
  11726. */
  11727. static void showWaitCursor() throw();
  11728. /** If showWaitCursor has been called, this will return the mouse to its
  11729. normal state.
  11730. This will look at what component is under the mouse, and update the
  11731. cursor to be the correct one for that component.
  11732. @see showWaitCursor
  11733. */
  11734. static void hideWaitCursor() throw();
  11735. juce_UseDebuggingNewOperator
  11736. private:
  11737. RefCountedMouseCursor* cursorHandle;
  11738. friend class Component;
  11739. void showInWindow (ComponentPeer* window) const throw();
  11740. void showInAllWindows() const throw();
  11741. void* getHandle() const throw();
  11742. };
  11743. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11744. /********* End of inlined file: juce_MouseCursor.h *********/
  11745. /********* Start of inlined file: juce_MouseListener.h *********/
  11746. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11747. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11748. /********* Start of inlined file: juce_MouseEvent.h *********/
  11749. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11750. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11751. class Component;
  11752. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11753. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11754. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11755. /**
  11756. Represents the state of the mouse buttons and modifier keys.
  11757. This is used both by mouse events and by KeyPress objects to describe
  11758. the state of keys such as shift, control, alt, etc.
  11759. @see KeyPress, MouseEvent::mods
  11760. */
  11761. class JUCE_API ModifierKeys
  11762. {
  11763. public:
  11764. /** Creates a ModifierKeys object from a raw set of flags.
  11765. @param flags to represent the keys that are down
  11766. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11767. rightButtonModifier, commandModifier, popupMenuClickModifier
  11768. */
  11769. ModifierKeys (const int flags = 0) throw();
  11770. /** Creates a copy of another object. */
  11771. ModifierKeys (const ModifierKeys& other) throw();
  11772. /** Copies this object from another one. */
  11773. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11774. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11775. This is a platform-agnostic way of checking for the operating system's
  11776. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11777. Windows/Linux, it's actually checking for the CTRL key.
  11778. */
  11779. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11780. /** Checks whether the user is trying to launch a pop-up menu.
  11781. This checks for platform-specific modifiers that might indicate that the user
  11782. is following the operating system's normal method of showing a pop-up menu.
  11783. So on Windows/Linux, this method is really testing for a right-click.
  11784. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11785. */
  11786. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11787. /** Checks whether the flag is set for the left mouse-button. */
  11788. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11789. /** Checks whether the flag is set for the right mouse-button.
  11790. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11791. this is platform-independent (and makes your code more explanatory too).
  11792. */
  11793. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11794. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11795. /** Tests for any of the mouse-button flags. */
  11796. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11797. /** Tests for any of the modifier key flags. */
  11798. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11799. /** Checks whether the shift key's flag is set. */
  11800. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11801. /** Checks whether the CTRL key's flag is set.
  11802. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11803. popup-menu modifiers.
  11804. @see isCommandDown, isPopupMenu
  11805. */
  11806. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11807. /** Checks whether the shift key's flag is set. */
  11808. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11809. /** Flags that represent the different keys. */
  11810. enum Flags
  11811. {
  11812. /** Shift key flag. */
  11813. shiftModifier = 1,
  11814. /** CTRL key flag. */
  11815. ctrlModifier = 2,
  11816. /** ALT key flag. */
  11817. altModifier = 4,
  11818. /** Left mouse button flag. */
  11819. leftButtonModifier = 16,
  11820. /** Right mouse button flag. */
  11821. rightButtonModifier = 32,
  11822. /** Middle mouse button flag. */
  11823. middleButtonModifier = 64,
  11824. #if JUCE_MAC
  11825. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11826. commandModifier = 8,
  11827. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11828. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11829. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11830. #else
  11831. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11832. commandModifier = ctrlModifier,
  11833. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11834. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11835. popupMenuClickModifier = rightButtonModifier,
  11836. #endif
  11837. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11838. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11839. /** Represents a combination of all the mouse buttons at once. */
  11840. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11841. };
  11842. /** Returns the raw flags for direct testing. */
  11843. inline int getRawFlags() const throw() { return flags; }
  11844. /** Tests a combination of flags and returns true if any of them are set. */
  11845. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11846. /** Creates a ModifierKeys object to represent the last-known state of the
  11847. keyboard and mouse buttons.
  11848. @see getCurrentModifiersRealtime
  11849. */
  11850. static const ModifierKeys getCurrentModifiers() throw();
  11851. /** Creates a ModifierKeys object to represent the current state of the
  11852. keyboard and mouse buttons.
  11853. This isn't often needed and isn't recommended, but will actively check all the
  11854. mouse and key states rather than just returning their last-known state like
  11855. getCurrentModifiers() does.
  11856. This is only needed in special circumstances for up-to-date modifier information
  11857. at times when the app's event loop isn't running normally.
  11858. */
  11859. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11860. private:
  11861. int flags;
  11862. static int currentModifierFlags;
  11863. friend class ComponentPeer;
  11864. static void updateCurrentModifiers() throw();
  11865. };
  11866. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11867. /********* End of inlined file: juce_ModifierKeys.h *********/
  11868. /**
  11869. Contains position and status information about a mouse event.
  11870. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11871. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11872. */
  11873. class JUCE_API MouseEvent
  11874. {
  11875. public:
  11876. /** Creates a MouseEvent.
  11877. Normally an application will never need to use this.
  11878. @param x the x position of the mouse, relative to the component that is passed-in
  11879. @param y the y position of the mouse, relative to the component that is passed-in
  11880. @param modifiers the key modifiers at the time of the event
  11881. @param originator the component that the mouse event applies to
  11882. @param eventTime the time the event happened
  11883. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11884. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11885. the same as the current mouse-x position.
  11886. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11887. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11888. the same as the current mouse-y position.
  11889. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11890. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11891. the same as the current mouse-event time.
  11892. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11893. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11894. */
  11895. MouseEvent (const int x, const int y,
  11896. const ModifierKeys& modifiers,
  11897. Component* const originator,
  11898. const Time& eventTime,
  11899. const int mouseDownX,
  11900. const int mouseDownY,
  11901. const Time& mouseDownTime,
  11902. const int numberOfClicks,
  11903. const bool mouseWasDragged) throw();
  11904. /** Destructor. */
  11905. ~MouseEvent() throw();
  11906. /** The x-position of the mouse when the event occurred.
  11907. This value is relative to the top-left of the component to which the
  11908. event applies (as indicated by the MouseEvent::eventComponent field).
  11909. */
  11910. int x;
  11911. /** The y-position of the mouse when the event occurred.
  11912. This value is relative to the top-left of the component to which the
  11913. event applies (as indicated by the MouseEvent::eventComponent field).
  11914. */
  11915. int y;
  11916. /** The key modifiers associated with the event.
  11917. This will let you find out which mouse buttons were down, as well as which
  11918. modifier keys were held down.
  11919. When used for mouse-up events, this will indicate the state of the mouse buttons
  11920. just before they were released, so that you can tell which button they let go of.
  11921. */
  11922. ModifierKeys mods;
  11923. /** The component that this event applies to.
  11924. This is usually the component that the mouse was over at the time, but for mouse-drag
  11925. events the mouse could actually be over a different component and the events are
  11926. still sent to the component that the button was originally pressed on.
  11927. The x and y member variables are relative to this component's position.
  11928. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11929. component, this pointer will be updated, but originalComponent remains unchanged.
  11930. @see originalComponent
  11931. */
  11932. Component* eventComponent;
  11933. /** The component that the event first occurred on.
  11934. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11935. component, this value remains unchanged to indicate the first component that received it.
  11936. @see eventComponent
  11937. */
  11938. Component* originalComponent;
  11939. /** The time that this mouse-event occurred.
  11940. */
  11941. Time eventTime;
  11942. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11943. The co-ordinate is relative to the component specified in MouseEvent::component.
  11944. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11945. */
  11946. int getMouseDownX() const throw();
  11947. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11948. The co-ordinate is relative to the component specified in MouseEvent::component.
  11949. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11950. */
  11951. int getMouseDownY() const throw();
  11952. /** Returns the straight-line distance between where the mouse is now and where it
  11953. was the last time the button was pressed.
  11954. This is quite handy for things like deciding whether the user has moved far enough
  11955. for it to be considered a drag operation.
  11956. @see getDistanceFromDragStartX
  11957. */
  11958. int getDistanceFromDragStart() const throw();
  11959. /** Returns the difference between the mouse's current x postion and where it was
  11960. when the button was last pressed.
  11961. @see getDistanceFromDragStart
  11962. */
  11963. int getDistanceFromDragStartX() const throw();
  11964. /** Returns the difference between the mouse's current y postion and where it was
  11965. when the button was last pressed.
  11966. @see getDistanceFromDragStart
  11967. */
  11968. int getDistanceFromDragStartY() const throw();
  11969. /** Returns true if the mouse has just been clicked.
  11970. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11971. the user has dragged the mouse more than a few pixels from the place where the
  11972. mouse-down occurred.
  11973. Once they have dragged it far enough for this method to return false, it will continue
  11974. to return false until the mouse-up, even if they move the mouse back to the same
  11975. position where they originally pressed it. This means that it's very handy for
  11976. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11977. callback to ignore any small movements they might make while clicking.
  11978. @returns true if the mouse wasn't dragged by more than a few pixels between
  11979. the last time the button was pressed and released.
  11980. */
  11981. bool mouseWasClicked() const throw();
  11982. /** For a click event, the number of times the mouse was clicked in succession.
  11983. So for example a double-click event will return 2, a triple-click 3, etc.
  11984. */
  11985. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11986. /** Returns the time that the mouse button has been held down for.
  11987. If called from a mouseDrag or mouseUp callback, this will return the
  11988. number of milliseconds since the corresponding mouseDown event occurred.
  11989. If called in other contexts, e.g. a mouseMove, then the returned value
  11990. may be 0 or an undefined value.
  11991. */
  11992. int getLengthOfMousePress() const throw();
  11993. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11994. The co-ordinates are relative to the top-left of the main monitor.
  11995. @see getMouseDownScreenX, Desktop::getMousePosition
  11996. */
  11997. int getScreenX() const throw();
  11998. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11999. The co-ordinates are relative to the top-left of the main monitor.
  12000. @see getMouseDownScreenY, Desktop::getMousePosition
  12001. */
  12002. int getScreenY() const throw();
  12003. /** Returns the x co-ordinate at which the mouse button was last pressed.
  12004. The co-ordinates are relative to the top-left of the main monitor.
  12005. @see getScreenX, Desktop::getMousePosition
  12006. */
  12007. int getMouseDownScreenX() const throw();
  12008. /** Returns the y co-ordinate at which the mouse button was last pressed.
  12009. The co-ordinates are relative to the top-left of the main monitor.
  12010. @see getScreenY, Desktop::getMousePosition
  12011. */
  12012. int getMouseDownScreenY() const throw();
  12013. /** Creates a version of this event that is relative to a different component.
  12014. The x and y positions of the event that is returned will have been
  12015. adjusted to be relative to the new component.
  12016. */
  12017. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  12018. /** Changes the application-wide setting for the double-click time limit.
  12019. This is the maximum length of time between mouse-clicks for it to be
  12020. considered a double-click. It's used by the Component class.
  12021. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  12022. */
  12023. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  12024. /** Returns the application-wide setting for the double-click time limit.
  12025. This is the maximum length of time between mouse-clicks for it to be
  12026. considered a double-click. It's used by the Component class.
  12027. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  12028. */
  12029. static int getDoubleClickTimeout() throw();
  12030. juce_UseDebuggingNewOperator
  12031. private:
  12032. int mouseDownX, mouseDownY;
  12033. Time mouseDownTime;
  12034. int numberOfClicks;
  12035. bool wasMovedSinceMouseDown;
  12036. };
  12037. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  12038. /********* End of inlined file: juce_MouseEvent.h *********/
  12039. /**
  12040. A MouseListener can be registered with a component to receive callbacks
  12041. about mouse events that happen to that component.
  12042. @see Component::addMouseListener, Component::removeMouseListener
  12043. */
  12044. class JUCE_API MouseListener
  12045. {
  12046. public:
  12047. /** Destructor. */
  12048. virtual ~MouseListener() {}
  12049. /** Called when the mouse moves inside a component.
  12050. If the mouse button isn't pressed and the mouse moves over a component,
  12051. this will be called to let the component react to this.
  12052. A component will always get a mouseEnter callback before a mouseMove.
  12053. @param e details about the position and status of the mouse event, including
  12054. the source component in which it occurred
  12055. @see mouseEnter, mouseExit, mouseDrag, contains
  12056. */
  12057. virtual void mouseMove (const MouseEvent& e);
  12058. /** Called when the mouse first enters a component.
  12059. If the mouse button isn't pressed and the mouse moves into a component,
  12060. this will be called to let the component react to this.
  12061. When the mouse button is pressed and held down while being moved in
  12062. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  12063. mouseDrag messages are sent to the component that the mouse was originally
  12064. clicked on, until the button is released.
  12065. @param e details about the position and status of the mouse event, including
  12066. the source component in which it occurred
  12067. @see mouseExit, mouseDrag, mouseMove, contains
  12068. */
  12069. virtual void mouseEnter (const MouseEvent& e);
  12070. /** Called when the mouse moves out of a component.
  12071. This will be called when the mouse moves off the edge of this
  12072. component.
  12073. If the mouse button was pressed, and it was then dragged off the
  12074. edge of the component and released, then this callback will happen
  12075. when the button is released, after the mouseUp callback.
  12076. @param e details about the position and status of the mouse event, including
  12077. the source component in which it occurred
  12078. @see mouseEnter, mouseDrag, mouseMove, contains
  12079. */
  12080. virtual void mouseExit (const MouseEvent& e);
  12081. /** Called when a mouse button is pressed.
  12082. The MouseEvent object passed in contains lots of methods for finding out
  12083. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  12084. were held down at the time.
  12085. Once a button is held down, the mouseDrag method will be called when the
  12086. mouse moves, until the button is released.
  12087. @param e details about the position and status of the mouse event, including
  12088. the source component in which it occurred
  12089. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  12090. */
  12091. virtual void mouseDown (const MouseEvent& e);
  12092. /** Called when the mouse is moved while a button is held down.
  12093. When a mouse button is pressed inside a component, that component
  12094. receives mouseDrag callbacks each time the mouse moves, even if the
  12095. mouse strays outside the component's bounds.
  12096. @param e details about the position and status of the mouse event, including
  12097. the source component in which it occurred
  12098. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  12099. */
  12100. virtual void mouseDrag (const MouseEvent& e);
  12101. /** Called when a mouse button is released.
  12102. A mouseUp callback is sent to the component in which a button was pressed
  12103. even if the mouse is actually over a different component when the
  12104. button is released.
  12105. The MouseEvent object passed in contains lots of methods for finding out
  12106. which buttons were down just before they were released.
  12107. @param e details about the position and status of the mouse event, including
  12108. the source component in which it occurred
  12109. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  12110. */
  12111. virtual void mouseUp (const MouseEvent& e);
  12112. /** Called when a mouse button has been double-clicked on a component.
  12113. The MouseEvent object passed in contains lots of methods for finding out
  12114. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  12115. were held down at the time.
  12116. @param e details about the position and status of the mouse event, including
  12117. the source component in which it occurred
  12118. @see mouseDown, mouseUp
  12119. */
  12120. virtual void mouseDoubleClick (const MouseEvent& e);
  12121. /** Called when the mouse-wheel is moved.
  12122. This callback is sent to the component that the mouse is over when the
  12123. wheel is moved.
  12124. If not overridden, the component will forward this message to its parent, so
  12125. that parent components can collect mouse-wheel messages that happen to
  12126. child components which aren't interested in them.
  12127. @param e details about the position and status of the mouse event, including
  12128. the source component in which it occurred
  12129. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  12130. value means the wheel has been pushed to the right, negative means it
  12131. was pushed to the left
  12132. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  12133. value means the wheel has been pushed upwards, negative means it
  12134. was pushed downwards
  12135. */
  12136. virtual void mouseWheelMove (const MouseEvent& e,
  12137. float wheelIncrementX,
  12138. float wheelIncrementY);
  12139. private:
  12140. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  12141. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  12142. // if that happens, update your code to use the new one above.
  12143. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  12144. };
  12145. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  12146. /********* End of inlined file: juce_MouseListener.h *********/
  12147. /********* Start of inlined file: juce_ComponentListener.h *********/
  12148. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12149. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12150. class Component;
  12151. /**
  12152. Gets informed about changes to a component's hierarchy or position.
  12153. To monitor a component for changes, register a subclass of ComponentListener
  12154. with the component using Component::addComponentListener().
  12155. Be sure to deregister listeners before you delete them!
  12156. @see Component::addComponentListener, Component::removeComponentListener
  12157. */
  12158. class JUCE_API ComponentListener
  12159. {
  12160. public:
  12161. /** Destructor. */
  12162. virtual ~ComponentListener() {}
  12163. /** Called when the component's position or size changes.
  12164. @param component the component that was moved or resized
  12165. @param wasMoved true if the component's top-left corner has just moved
  12166. @param wasResized true if the component's width or height has just changed
  12167. @see Component::setBounds, Component::resized, Component::moved
  12168. */
  12169. virtual void componentMovedOrResized (Component& component,
  12170. bool wasMoved,
  12171. bool wasResized);
  12172. /** Called when the component is brought to the top of the z-order.
  12173. @param component the component that was moved
  12174. @see Component::toFront, Component::broughtToFront
  12175. */
  12176. virtual void componentBroughtToFront (Component& component);
  12177. /** Called when the component is made visible or invisible.
  12178. @param component the component that changed
  12179. @see Component::setVisible
  12180. */
  12181. virtual void componentVisibilityChanged (Component& component);
  12182. /** Called when the component has children added or removed.
  12183. @param component the component whose children were changed
  12184. @see Component::childrenChanged, Component::addChildComponent,
  12185. Component::removeChildComponent
  12186. */
  12187. virtual void componentChildrenChanged (Component& component);
  12188. /** Called to indicate that the component's parents have changed.
  12189. When a component is added or removed from its parent, all of its children
  12190. will produce this notification (recursively - so all children of its
  12191. children will also be called as well).
  12192. @param component the component that this listener is registered with
  12193. @see Component::parentHierarchyChanged
  12194. */
  12195. virtual void componentParentHierarchyChanged (Component& component);
  12196. /** Called when the component's name is changed.
  12197. @see Component::setName, Component::getName
  12198. */
  12199. virtual void componentNameChanged (Component& component);
  12200. };
  12201. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12202. /********* End of inlined file: juce_ComponentListener.h *********/
  12203. /********* Start of inlined file: juce_KeyListener.h *********/
  12204. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  12205. #define __JUCE_KEYLISTENER_JUCEHEADER__
  12206. /********* Start of inlined file: juce_KeyPress.h *********/
  12207. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  12208. #define __JUCE_KEYPRESS_JUCEHEADER__
  12209. /**
  12210. Represents a key press, including any modifier keys that are needed.
  12211. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  12212. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  12213. */
  12214. class JUCE_API KeyPress
  12215. {
  12216. public:
  12217. /** Creates an (invalid) KeyPress.
  12218. @see isValid
  12219. */
  12220. KeyPress() throw();
  12221. /** Creates a KeyPress for a key and some modifiers.
  12222. e.g.
  12223. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  12224. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  12225. @param keyCode a code that represents the key - this value must be
  12226. one of special constants listed in this class, or an
  12227. 8-bit character code such as a letter (case is ignored),
  12228. digit or a simple key like "," or ".". Note that this
  12229. isn't the same as the textCharacter parameter, so for example
  12230. a keyCode of 'a' and a shift-key modifier should have a
  12231. textCharacter value of 'A'.
  12232. @param modifiers the modifiers to associate with the keystroke
  12233. @param textCharacter the character that would be printed if someone typed
  12234. this keypress into a text editor. This value may be
  12235. null if the keypress is a non-printing character
  12236. @see getKeyCode, isKeyCode, getModifiers
  12237. */
  12238. KeyPress (const int keyCode,
  12239. const ModifierKeys& modifiers,
  12240. const juce_wchar textCharacter) throw();
  12241. /** Creates a keypress with a keyCode but no modifiers or text character.
  12242. */
  12243. KeyPress (const int keyCode) throw();
  12244. /** Creates a copy of another KeyPress. */
  12245. KeyPress (const KeyPress& other) throw();
  12246. /** Copies this KeyPress from another one. */
  12247. const KeyPress& operator= (const KeyPress& other) throw();
  12248. /** Compares two KeyPress objects. */
  12249. bool operator== (const KeyPress& other) const throw();
  12250. /** Compares two KeyPress objects. */
  12251. bool operator!= (const KeyPress& other) const throw();
  12252. /** Returns true if this is a valid KeyPress.
  12253. A null keypress can be created by the default constructor, in case it's
  12254. needed.
  12255. */
  12256. bool isValid() const throw() { return keyCode != 0; }
  12257. /** Returns the key code itself.
  12258. This will either be one of the special constants defined in this class,
  12259. or an 8-bit character code.
  12260. */
  12261. int getKeyCode() const throw() { return keyCode; }
  12262. /** Returns the key modifiers.
  12263. @see ModifierKeys
  12264. */
  12265. const ModifierKeys getModifiers() const throw() { return mods; }
  12266. /** Returns the character that is associated with this keypress.
  12267. This is the character that you'd expect to see printed if you press this
  12268. keypress in a text editor or similar component.
  12269. */
  12270. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  12271. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  12272. the modifiers.
  12273. The values for key codes can either be one of the special constants defined in
  12274. this class, or an 8-bit character code.
  12275. @see getKeyCode
  12276. */
  12277. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  12278. /** Converts a textual key description to a KeyPress.
  12279. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  12280. This isn't designed to cope with any kind of input, but should be given the
  12281. strings that are created by the getTextDescription() method.
  12282. If the string can't be parsed, the object returned will be invalid.
  12283. @see getTextDescription
  12284. */
  12285. static const KeyPress createFromDescription (const String& textVersion) throw();
  12286. /** Creates a textual description of the key combination.
  12287. e.g. "CTRL + C" or "DELETE".
  12288. To store a keypress in a file, use this method, along with createFromDescription()
  12289. to retrieve it later.
  12290. */
  12291. const String getTextDescription() const throw();
  12292. /** Checks whether the user is currently holding down the keys that make up this
  12293. KeyPress.
  12294. Note that this will return false if any extra modifier keys are
  12295. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  12296. then it will be false.
  12297. */
  12298. bool isCurrentlyDown() const throw();
  12299. /** Checks whether a particular key is held down, irrespective of modifiers.
  12300. The values for key codes can either be one of the special constants defined in
  12301. this class, or an 8-bit character code.
  12302. */
  12303. static bool isKeyCurrentlyDown (int keyCode) throw();
  12304. // Key codes
  12305. //
  12306. // Note that the actual values of these are platform-specific and may change
  12307. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  12308. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  12309. //
  12310. static const int spaceKey; /**< key-code for the space bar */
  12311. static const int escapeKey; /**< key-code for the escape key */
  12312. static const int returnKey; /**< key-code for the return key*/
  12313. static const int tabKey; /**< key-code for the tab key*/
  12314. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  12315. static const int backspaceKey; /**< key-code for the backspace key */
  12316. static const int insertKey; /**< key-code for the insert key */
  12317. static const int upKey; /**< key-code for the cursor-up key */
  12318. static const int downKey; /**< key-code for the cursor-down key */
  12319. static const int leftKey; /**< key-code for the cursor-left key */
  12320. static const int rightKey; /**< key-code for the cursor-right key */
  12321. static const int pageUpKey; /**< key-code for the page-up key */
  12322. static const int pageDownKey; /**< key-code for the page-down key */
  12323. static const int homeKey; /**< key-code for the home key */
  12324. static const int endKey; /**< key-code for the end key */
  12325. static const int F1Key; /**< key-code for the F1 key */
  12326. static const int F2Key; /**< key-code for the F2 key */
  12327. static const int F3Key; /**< key-code for the F3 key */
  12328. static const int F4Key; /**< key-code for the F4 key */
  12329. static const int F5Key; /**< key-code for the F5 key */
  12330. static const int F6Key; /**< key-code for the F6 key */
  12331. static const int F7Key; /**< key-code for the F7 key */
  12332. static const int F8Key; /**< key-code for the F8 key */
  12333. static const int F9Key; /**< key-code for the F9 key */
  12334. static const int F10Key; /**< key-code for the F10 key */
  12335. static const int F11Key; /**< key-code for the F11 key */
  12336. static const int F12Key; /**< key-code for the F12 key */
  12337. static const int F13Key; /**< key-code for the F13 key */
  12338. static const int F14Key; /**< key-code for the F14 key */
  12339. static const int F15Key; /**< key-code for the F15 key */
  12340. static const int F16Key; /**< key-code for the F16 key */
  12341. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  12342. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  12343. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  12344. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  12345. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  12346. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  12347. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  12348. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  12349. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  12350. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  12351. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  12352. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  12353. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  12354. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  12355. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  12356. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  12357. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  12358. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  12359. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  12360. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  12361. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  12362. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  12363. juce_UseDebuggingNewOperator
  12364. private:
  12365. int keyCode;
  12366. ModifierKeys mods;
  12367. juce_wchar textCharacter;
  12368. };
  12369. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  12370. /********* End of inlined file: juce_KeyPress.h *********/
  12371. class Component;
  12372. /**
  12373. Receives callbacks when keys are pressed.
  12374. You can add a key listener to a component to be informed when that component
  12375. gets key events. See the Component::addListener method for more details.
  12376. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  12377. */
  12378. class JUCE_API KeyListener
  12379. {
  12380. public:
  12381. /** Destructor. */
  12382. virtual ~KeyListener() {}
  12383. /** Called to indicate that a key has been pressed.
  12384. If your implementation returns true, then the key event is considered to have
  12385. been consumed, and will not be passed on to any other components. If it returns
  12386. false, then the key will be passed to other components that might want to use it.
  12387. @param key the keystroke, including modifier keys
  12388. @param originatingComponent the component that received the key event
  12389. @see keyStateChanged, Component::keyPressed
  12390. */
  12391. virtual bool keyPressed (const KeyPress& key,
  12392. Component* originatingComponent) = 0;
  12393. /** Called when any key is pressed or released.
  12394. When this is called, classes that might be interested in
  12395. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  12396. check whether their key has changed.
  12397. If your implementation returns true, then the key event is considered to have
  12398. been consumed, and will not be passed on to any other components. If it returns
  12399. false, then the key will be passed to other components that might want to use it.
  12400. @param originatingComponent the component that received the key event
  12401. @param isKeyDown true if a key is being pressed, false if one is being released
  12402. @see KeyPress, Component::keyStateChanged
  12403. */
  12404. virtual bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  12405. private:
  12406. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  12407. // subclass to use the new parameters to keyStateChanged)
  12408. virtual void keyStateChanged (Component*) {};
  12409. };
  12410. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  12411. /********* End of inlined file: juce_KeyListener.h *********/
  12412. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  12413. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12414. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12415. class Component;
  12416. /**
  12417. Controls the order in which focus moves between components.
  12418. The default algorithm used by this class to work out the order of traversal
  12419. is as follows:
  12420. - if two components both have an explicit focus order specified, then the
  12421. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12422. method).
  12423. - any component with an explicit focus order greater than 0 comes before ones
  12424. that don't have an order specified.
  12425. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12426. order.
  12427. If you need traversal in a more customised way, you can create a subclass
  12428. of KeyboardFocusTraverser that uses your own algorithm, and use
  12429. Component::createFocusTraverser() to create it.
  12430. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12431. */
  12432. class JUCE_API KeyboardFocusTraverser
  12433. {
  12434. public:
  12435. KeyboardFocusTraverser();
  12436. /** Destructor. */
  12437. virtual ~KeyboardFocusTraverser();
  12438. /** Returns the component that should be given focus after the specified one
  12439. when moving "forwards".
  12440. The default implementation will return the next component which is to the
  12441. right of or below this one.
  12442. This may return 0 if there's no suitable candidate.
  12443. */
  12444. virtual Component* getNextComponent (Component* current);
  12445. /** Returns the component that should be given focus after the specified one
  12446. when moving "backwards".
  12447. The default implementation will return the next component which is to the
  12448. left of or above this one.
  12449. This may return 0 if there's no suitable candidate.
  12450. */
  12451. virtual Component* getPreviousComponent (Component* current);
  12452. /** Returns the component that should receive focus be default within the given
  12453. parent component.
  12454. The default implementation will just return the foremost child component that
  12455. wants focus.
  12456. This may return 0 if there's no suitable candidate.
  12457. */
  12458. virtual Component* getDefaultComponent (Component* parentComponent);
  12459. };
  12460. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12461. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12462. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12463. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12464. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12465. /********* Start of inlined file: juce_Graphics.h *********/
  12466. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12467. #define __JUCE_GRAPHICS_JUCEHEADER__
  12468. /********* Start of inlined file: juce_Font.h *********/
  12469. #ifndef __JUCE_FONT_JUCEHEADER__
  12470. #define __JUCE_FONT_JUCEHEADER__
  12471. /********* Start of inlined file: juce_Typeface.h *********/
  12472. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12473. #define __JUCE_TYPEFACE_JUCEHEADER__
  12474. /********* Start of inlined file: juce_Path.h *********/
  12475. #ifndef __JUCE_PATH_JUCEHEADER__
  12476. #define __JUCE_PATH_JUCEHEADER__
  12477. /********* Start of inlined file: juce_AffineTransform.h *********/
  12478. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12479. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12480. /**
  12481. Represents a 2D affine-transformation matrix.
  12482. An affine transformation is a transformation such as a rotation, scale, shear,
  12483. resize or translation.
  12484. These are used for various 2D transformation tasks, e.g. with Path objects.
  12485. @see Path, Point, Line
  12486. */
  12487. class JUCE_API AffineTransform
  12488. {
  12489. public:
  12490. /** Creates an identity transform. */
  12491. AffineTransform() throw();
  12492. /** Creates a copy of another transform. */
  12493. AffineTransform (const AffineTransform& other) throw();
  12494. /** Creates a transform from a set of raw matrix values.
  12495. The resulting matrix is:
  12496. (mat00 mat01 mat02)
  12497. (mat10 mat11 mat12)
  12498. ( 0 0 1 )
  12499. */
  12500. AffineTransform (const float mat00, const float mat01, const float mat02,
  12501. const float mat10, const float mat11, const float mat12) throw();
  12502. /** Copies from another AffineTransform object */
  12503. const AffineTransform& operator= (const AffineTransform& other) throw();
  12504. /** Compares two transforms. */
  12505. bool operator== (const AffineTransform& other) const throw();
  12506. /** Compares two transforms. */
  12507. bool operator!= (const AffineTransform& other) const throw();
  12508. /** A ready-to-use identity transform, which you can use to append other
  12509. transformations to.
  12510. e.g. @code
  12511. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12512. .scaled (2.0f);
  12513. @endcode
  12514. */
  12515. static const AffineTransform identity;
  12516. /** Transforms a 2D co-ordinate using this matrix. */
  12517. void transformPoint (float& x,
  12518. float& y) const throw();
  12519. /** Transforms a 2D co-ordinate using this matrix. */
  12520. void transformPoint (double& x,
  12521. double& y) const throw();
  12522. /** Returns a new transform which is the same as this one followed by a translation. */
  12523. const AffineTransform translated (const float deltaX,
  12524. const float deltaY) const throw();
  12525. /** Returns a new transform which is a translation. */
  12526. static const AffineTransform translation (const float deltaX,
  12527. const float deltaY) throw();
  12528. /** Returns a transform which is the same as this one followed by a rotation.
  12529. The rotation is specified by a number of radians to rotate clockwise, centred around
  12530. the origin (0, 0).
  12531. */
  12532. const AffineTransform rotated (const float angleInRadians) const throw();
  12533. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12534. The rotation is specified by a number of radians to rotate clockwise, centred around
  12535. the co-ordinates passed in.
  12536. */
  12537. const AffineTransform rotated (const float angleInRadians,
  12538. const float pivotX,
  12539. const float pivotY) const throw();
  12540. /** Returns a new transform which is a rotation about (0, 0). */
  12541. static const AffineTransform rotation (const float angleInRadians) throw();
  12542. /** Returns a new transform which is a rotation about a given point. */
  12543. static const AffineTransform rotation (const float angleInRadians,
  12544. const float pivotX,
  12545. const float pivotY) throw();
  12546. /** Returns a transform which is the same as this one followed by a re-scaling.
  12547. The scaling is centred around the origin (0, 0).
  12548. */
  12549. const AffineTransform scaled (const float factorX,
  12550. const float factorY) const throw();
  12551. /** Returns a new transform which is a re-scale about the origin. */
  12552. static const AffineTransform scale (const float factorX,
  12553. const float factorY) throw();
  12554. /** Returns a transform which is the same as this one followed by a shear.
  12555. The shear is centred around the origin (0, 0).
  12556. */
  12557. const AffineTransform sheared (const float shearX,
  12558. const float shearY) const throw();
  12559. /** Returns a matrix which is the inverse operation of this one.
  12560. Some matrices don't have an inverse - in this case, the method will just return
  12561. an identity transform.
  12562. */
  12563. const AffineTransform inverted() const throw();
  12564. /** Returns the result of concatenating another transformation after this one. */
  12565. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12566. /** Returns true if this transform has no effect on points. */
  12567. bool isIdentity() const throw();
  12568. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12569. bool isSingularity() const throw();
  12570. /** Returns true if the transform only translates, and doesn't scale or rotate the
  12571. points. */
  12572. bool isOnlyTranslation() const throw();
  12573. /** If this transform is only a translation, this returns the X offset.
  12574. @see isOnlyTranslation
  12575. */
  12576. float getTranslationX() const throw() { return mat02; }
  12577. /** If this transform is only a translation, this returns the X offset.
  12578. @see isOnlyTranslation
  12579. */
  12580. float getTranslationY() const throw() { return mat12; }
  12581. juce_UseDebuggingNewOperator
  12582. /* The transform matrix is:
  12583. (mat00 mat01 mat02)
  12584. (mat10 mat11 mat12)
  12585. ( 0 0 1 )
  12586. */
  12587. float mat00, mat01, mat02;
  12588. float mat10, mat11, mat12;
  12589. private:
  12590. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12591. const float mat10, const float mat11, const float mat12) const throw();
  12592. };
  12593. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12594. /********* End of inlined file: juce_AffineTransform.h *********/
  12595. /********* Start of inlined file: juce_Point.h *********/
  12596. #ifndef __JUCE_POINT_JUCEHEADER__
  12597. #define __JUCE_POINT_JUCEHEADER__
  12598. /**
  12599. A pair of (x, y) co-ordinates.
  12600. Uses 32-bit floating point accuracy.
  12601. @see Line, Path, AffineTransform
  12602. */
  12603. class JUCE_API Point
  12604. {
  12605. public:
  12606. /** Creates a point with co-ordinates (0, 0). */
  12607. Point() throw();
  12608. /** Creates a copy of another point. */
  12609. Point (const Point& other) throw();
  12610. /** Creates a point from an (x, y) position. */
  12611. Point (const float x, const float y) throw();
  12612. /** Copies this point from another one.
  12613. @see setXY
  12614. */
  12615. const Point& operator= (const Point& other) throw();
  12616. /** Destructor. */
  12617. ~Point() throw();
  12618. /** Returns the point's x co-ordinate. */
  12619. inline float getX() const throw() { return x; }
  12620. /** Returns the point's y co-ordinate. */
  12621. inline float getY() const throw() { return y; }
  12622. /** Changes the point's x and y co-ordinates. */
  12623. void setXY (const float x,
  12624. const float y) throw();
  12625. /** Uses a transform to change the point's co-ordinates.
  12626. @see AffineTransform::transformPoint
  12627. */
  12628. void applyTransform (const AffineTransform& transform) throw();
  12629. juce_UseDebuggingNewOperator
  12630. private:
  12631. float x, y;
  12632. };
  12633. #endif // __JUCE_POINT_JUCEHEADER__
  12634. /********* End of inlined file: juce_Point.h *********/
  12635. /********* Start of inlined file: juce_Rectangle.h *********/
  12636. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  12637. #define __JUCE_RECTANGLE_JUCEHEADER__
  12638. /**
  12639. A rectangle, specified using integer co-ordinates.
  12640. @see RectangleList, Path, Line, Point
  12641. */
  12642. class JUCE_API Rectangle
  12643. {
  12644. public:
  12645. /** Creates a rectangle of zero size.
  12646. The default co-ordinates will be (0, 0, 0, 0).
  12647. */
  12648. Rectangle() throw();
  12649. /** Creates a copy of another rectangle. */
  12650. Rectangle (const Rectangle& other) throw();
  12651. /** Creates a rectangle with a given position and size. */
  12652. Rectangle (const int x, const int y,
  12653. const int width, const int height) throw();
  12654. /** Creates a rectangle with a given size, and a position of (0, 0). */
  12655. Rectangle (const int width, const int height) throw();
  12656. /** Destructor. */
  12657. ~Rectangle() throw();
  12658. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  12659. inline int getX() const throw() { return x; }
  12660. /** Returns the y co-ordinate of the rectangle's top edge. */
  12661. inline int getY() const throw() { return y; }
  12662. /** Returns the width of the rectangle. */
  12663. inline int getWidth() const throw() { return w; }
  12664. /** Returns the height of the rectangle. */
  12665. inline int getHeight() const throw() { return h; }
  12666. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  12667. inline int getRight() const throw() { return x + w; }
  12668. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  12669. inline int getBottom() const throw() { return y + h; }
  12670. /** Returns the x co-ordinate of the rectangle's centre. */
  12671. inline int getCentreX() const throw() { return x + (w >> 1); }
  12672. /** Returns the y co-ordinate of the rectangle's centre. */
  12673. inline int getCentreY() const throw() { return y + (h >> 1); }
  12674. /** Returns true if the rectangle's width and height are both zero or less */
  12675. bool isEmpty() const throw();
  12676. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  12677. void setPosition (const int x, const int y) throw();
  12678. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  12679. void setSize (const int w, const int h) throw();
  12680. /** Changes all the rectangle's co-ordinates. */
  12681. void setBounds (const int newX, const int newY,
  12682. const int newWidth, const int newHeight) throw();
  12683. /** Changes the rectangle's width */
  12684. void setWidth (const int newWidth) throw();
  12685. /** Changes the rectangle's height */
  12686. void setHeight (const int newHeight) throw();
  12687. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  12688. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  12689. */
  12690. void setLeft (const int newLeft) throw();
  12691. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  12692. If the y is moved to be below the current bottom edge, the height will be set to zero.
  12693. */
  12694. void setTop (const int newTop) throw();
  12695. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  12696. If the new right is below the current X value, the X will be pushed down to match it.
  12697. @see getRight
  12698. */
  12699. void setRight (const int newRight) throw();
  12700. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  12701. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  12702. @see getBottom
  12703. */
  12704. void setBottom (const int newBottom) throw();
  12705. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  12706. void translate (const int deltaX,
  12707. const int deltaY) throw();
  12708. /** Returns a rectangle which is the same as this one moved by a given amount. */
  12709. const Rectangle translated (const int deltaX,
  12710. const int deltaY) const throw();
  12711. /** Expands the rectangle by a given amount.
  12712. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  12713. @see expanded, reduce, reduced
  12714. */
  12715. void expand (const int deltaX,
  12716. const int deltaY) throw();
  12717. /** Returns a rectangle that is larger than this one by a given amount.
  12718. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  12719. @see expand, reduce, reduced
  12720. */
  12721. const Rectangle expanded (const int deltaX,
  12722. const int deltaY) const throw();
  12723. /** Shrinks the rectangle by a given amount.
  12724. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  12725. @see reduced, expand, expanded
  12726. */
  12727. void reduce (const int deltaX,
  12728. const int deltaY) throw();
  12729. /** Returns a rectangle that is smaller than this one by a given amount.
  12730. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  12731. @see reduce, expand, expanded
  12732. */
  12733. const Rectangle reduced (const int deltaX,
  12734. const int deltaY) const throw();
  12735. /** Returns true if the two rectangles are identical. */
  12736. bool operator== (const Rectangle& other) const throw();
  12737. /** Returns true if the two rectangles are not identical. */
  12738. bool operator!= (const Rectangle& other) const throw();
  12739. /** Returns true if this co-ordinate is inside the rectangle. */
  12740. bool contains (const int x, const int y) const throw();
  12741. /** Returns true if this other rectangle is completely inside this one. */
  12742. bool contains (const Rectangle& other) const throw();
  12743. /** Returns true if any part of another rectangle overlaps this one. */
  12744. bool intersects (const Rectangle& other) const throw();
  12745. /** Returns the region that is the overlap between this and another rectangle.
  12746. If the two rectangles don't overlap, the rectangle returned will be empty.
  12747. */
  12748. const Rectangle getIntersection (const Rectangle& other) const throw();
  12749. /** Clips a rectangle so that it lies only within this one.
  12750. This is a non-static version of intersectRectangles().
  12751. Returns false if the two regions didn't overlap.
  12752. */
  12753. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  12754. /** Returns the smallest rectangle that contains both this one and the one
  12755. passed-in.
  12756. */
  12757. const Rectangle getUnion (const Rectangle& other) const throw();
  12758. /** If this rectangle merged with another one results in a simple rectangle, this
  12759. will set this rectangle to the result, and return true.
  12760. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  12761. or if they form a complex region.
  12762. */
  12763. bool enlargeIfAdjacent (const Rectangle& other) throw();
  12764. /** If after removing another rectangle from this one the result is a simple rectangle,
  12765. this will set this object's bounds to be the result, and return true.
  12766. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  12767. or if removing the other one would form a complex region.
  12768. */
  12769. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  12770. /** Static utility to intersect two sets of rectangular co-ordinates.
  12771. Returns false if the two regions didn't overlap.
  12772. @see intersectRectangle
  12773. */
  12774. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  12775. int x2, int y2, int w2, int h2) throw();
  12776. /** Creates a string describing this rectangle.
  12777. The string will be of the form "x y width height", e.g. "100 100 400 200".
  12778. Coupled with the fromString() method, this is very handy for things like
  12779. storing rectangles (particularly component positions) in XML attributes.
  12780. @see fromString
  12781. */
  12782. const String toString() const throw();
  12783. /** Parses a string containing a rectangle's details.
  12784. The string should contain 4 integer tokens, in the form "x y width height". They
  12785. can be comma or whitespace separated.
  12786. This method is intended to go with the toString() method, to form an easy way
  12787. of saving/loading rectangles as strings.
  12788. @see toString
  12789. */
  12790. static const Rectangle fromString (const String& stringVersion);
  12791. juce_UseDebuggingNewOperator
  12792. private:
  12793. friend class RectangleList;
  12794. int x, y, w, h;
  12795. };
  12796. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  12797. /********* End of inlined file: juce_Rectangle.h *********/
  12798. /********* Start of inlined file: juce_Justification.h *********/
  12799. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12800. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12801. /**
  12802. Represents a type of justification to be used when positioning graphical items.
  12803. e.g. it indicates whether something should be placed top-left, top-right,
  12804. centred, etc.
  12805. It is used in various places wherever this kind of information is needed.
  12806. */
  12807. class JUCE_API Justification
  12808. {
  12809. public:
  12810. /** Creates a Justification object using a combination of flags. */
  12811. inline Justification (const int flags_) throw() : flags (flags_) {}
  12812. /** Creates a copy of another Justification object. */
  12813. Justification (const Justification& other) throw();
  12814. /** Copies another Justification object. */
  12815. const Justification& operator= (const Justification& other) throw();
  12816. /** Returns the raw flags that are set for this Justification object. */
  12817. inline int getFlags() const throw() { return flags; }
  12818. /** Tests a set of flags for this object.
  12819. @returns true if any of the flags passed in are set on this object.
  12820. */
  12821. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12822. /** Returns just the flags from this object that deal with vertical layout. */
  12823. int getOnlyVerticalFlags() const throw();
  12824. /** Returns just the flags from this object that deal with horizontal layout. */
  12825. int getOnlyHorizontalFlags() const throw();
  12826. /** Adjusts the position of a rectangle to fit it into a space.
  12827. The (x, y) position of the rectangle will be updated to position it inside the
  12828. given space according to the justification flags.
  12829. */
  12830. void applyToRectangle (int& x, int& y,
  12831. const int w, const int h,
  12832. const int spaceX, const int spaceY,
  12833. const int spaceW, const int spaceH) const throw();
  12834. /** Flag values that can be combined and used in the constructor. */
  12835. enum
  12836. {
  12837. /** Indicates that the item should be aligned against the left edge of the available space. */
  12838. left = 1,
  12839. /** Indicates that the item should be aligned against the right edge of the available space. */
  12840. right = 2,
  12841. /** Indicates that the item should be placed in the centre between the left and right
  12842. sides of the available space. */
  12843. horizontallyCentred = 4,
  12844. /** Indicates that the item should be aligned against the top edge of the available space. */
  12845. top = 8,
  12846. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12847. bottom = 16,
  12848. /** Indicates that the item should be placed in the centre between the top and bottom
  12849. sides of the available space. */
  12850. verticallyCentred = 32,
  12851. /** Indicates that lines of text should be spread out to fill the maximum width
  12852. available, so that both margins are aligned vertically.
  12853. */
  12854. horizontallyJustified = 64,
  12855. /** Indicates that the item should be centred vertically and horizontally.
  12856. This is equivalent to (horizontallyCentred | verticallyCentred)
  12857. */
  12858. centred = 36,
  12859. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12860. This is equivalent to (left | verticallyCentred)
  12861. */
  12862. centredLeft = 33,
  12863. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12864. This is equivalent to (right | verticallyCentred)
  12865. */
  12866. centredRight = 34,
  12867. /** Indicates that the item should be centred horizontally and placed at the top.
  12868. This is equivalent to (horizontallyCentred | top)
  12869. */
  12870. centredTop = 12,
  12871. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12872. This is equivalent to (horizontallyCentred | bottom)
  12873. */
  12874. centredBottom = 20,
  12875. /** Indicates that the item should be placed in the top-left corner.
  12876. This is equivalent to (left | top)
  12877. */
  12878. topLeft = 9,
  12879. /** Indicates that the item should be placed in the top-right corner.
  12880. This is equivalent to (right | top)
  12881. */
  12882. topRight = 10,
  12883. /** Indicates that the item should be placed in the bottom-left corner.
  12884. This is equivalent to (left | bottom)
  12885. */
  12886. bottomLeft = 17,
  12887. /** Indicates that the item should be placed in the bottom-left corner.
  12888. This is equivalent to (right | bottom)
  12889. */
  12890. bottomRight = 18
  12891. };
  12892. private:
  12893. int flags;
  12894. };
  12895. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12896. /********* End of inlined file: juce_Justification.h *********/
  12897. /********* Start of inlined file: juce_EdgeTable.h *********/
  12898. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  12899. #define __JUCE_EDGETABLE_JUCEHEADER__
  12900. class Path;
  12901. class Image;
  12902. /**
  12903. A table of horizontal scan-line segments - used for rasterising Paths.
  12904. @see Path, Graphics
  12905. */
  12906. class JUCE_API EdgeTable
  12907. {
  12908. public:
  12909. /** Creates an edge table containing a path.
  12910. A table is created with a fixed vertical range, and only sections of the path
  12911. which lie within this range will be added to the table.
  12912. @param clipLimits only the region of the path that lies within this area will be added
  12913. @param pathToAdd the path to add to the table
  12914. @param transform a transform to apply to the path being added
  12915. */
  12916. EdgeTable (const Rectangle& clipLimits,
  12917. const Path& pathToAdd,
  12918. const AffineTransform& transform) throw();
  12919. /** Creates an edge table containing a rectangle.
  12920. */
  12921. EdgeTable (const Rectangle& rectangleToAdd) throw();
  12922. /** Creates an edge table containing a rectangle.
  12923. */
  12924. EdgeTable (const float x, const float y,
  12925. const float w, const float h) throw();
  12926. /** Creates a copy of another edge table. */
  12927. EdgeTable (const EdgeTable& other) throw();
  12928. /** Copies from another edge table. */
  12929. const EdgeTable& operator= (const EdgeTable& other) throw();
  12930. /** Destructor. */
  12931. ~EdgeTable() throw();
  12932. void clipToRectangle (const Rectangle& r) throw();
  12933. void excludeRectangle (const Rectangle& r) throw();
  12934. void clipToEdgeTable (const EdgeTable& other);
  12935. void clipLineToMask (int x, int y, uint8* mask, int maskStride, int numPixels) throw();
  12936. bool isEmpty() throw();
  12937. const Rectangle& getMaximumBounds() const throw() { return bounds; }
  12938. void translate (float dx, int dy) throw();
  12939. /** Reduces the amount of space the table has allocated.
  12940. This will shrink the table down to use as little memory as possible - useful for
  12941. read-only tables that get stored and re-used for rendering.
  12942. */
  12943. void optimiseTable() throw();
  12944. /** Iterates the lines in the table, for rendering.
  12945. This function will iterate each line in the table, and call a user-defined class
  12946. to render each pixel or continuous line of pixels that the table contains.
  12947. @param iterationCallback this templated class must contain the following methods:
  12948. @code
  12949. inline void setEdgeTableYPos (int y);
  12950. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  12951. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  12952. @endcode
  12953. (these don't necessarily have to be 'const', but it might help it go faster)
  12954. */
  12955. template <class EdgeTableIterationCallback>
  12956. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  12957. {
  12958. const int* lineStart = table;
  12959. for (int y = 0; y < bounds.getHeight(); ++y)
  12960. {
  12961. const int* line = lineStart;
  12962. lineStart += lineStrideElements;
  12963. int numPoints = line[0];
  12964. if (--numPoints > 0)
  12965. {
  12966. int x = *++line;
  12967. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  12968. int levelAccumulator = 0;
  12969. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  12970. while (--numPoints >= 0)
  12971. {
  12972. const int level = *++line;
  12973. jassert (((unsigned int) level) < (unsigned int) 256);
  12974. const int endX = *++line;
  12975. jassert (endX >= x);
  12976. const int endOfRun = (endX >> 8);
  12977. if (endOfRun == (x >> 8))
  12978. {
  12979. // small segment within the same pixel, so just save it for the next
  12980. // time round..
  12981. levelAccumulator += (endX - x) * level;
  12982. }
  12983. else
  12984. {
  12985. // plot the fist pixel of this segment, including any accumulated
  12986. // levels from smaller segments that haven't been drawn yet
  12987. levelAccumulator += (0xff - (x & 0xff)) * level;
  12988. levelAccumulator >>= 8;
  12989. x >>= 8;
  12990. if (levelAccumulator > 0)
  12991. {
  12992. if (levelAccumulator >> 8)
  12993. levelAccumulator = 0xff;
  12994. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  12995. }
  12996. // if there's a run of similar pixels, do it all in one go..
  12997. if (level > 0)
  12998. {
  12999. jassert (endOfRun <= bounds.getRight());
  13000. const int numPix = endOfRun - ++x;
  13001. if (numPix > 0)
  13002. iterationCallback.handleEdgeTableLine (x, numPix, level);
  13003. }
  13004. // save the bit at the end to be drawn next time round the loop.
  13005. levelAccumulator = (endX & 0xff) * level;
  13006. }
  13007. x = endX;
  13008. }
  13009. if (levelAccumulator > 0)
  13010. {
  13011. levelAccumulator >>= 8;
  13012. if (levelAccumulator >> 8)
  13013. levelAccumulator = 0xff;
  13014. x >>= 8;
  13015. jassert (x >= bounds.getX() && x < bounds.getRight());
  13016. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  13017. }
  13018. }
  13019. }
  13020. }
  13021. juce_UseDebuggingNewOperator
  13022. private:
  13023. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  13024. int* table;
  13025. Rectangle bounds;
  13026. int maxEdgesPerLine, lineStrideElements;
  13027. bool needToCheckEmptinesss;
  13028. void addEdgePoint (const int x, const int y, const int winding) throw();
  13029. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  13030. void intersectWithEdgeTableLine (const int y, const int* otherLine) throw();
  13031. };
  13032. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  13033. /********* End of inlined file: juce_EdgeTable.h *********/
  13034. class Image;
  13035. /**
  13036. A path is a sequence of lines and curves that may either form a closed shape
  13037. or be open-ended.
  13038. To use a path, you can create an empty one, then add lines and curves to it
  13039. to create shapes, then it can be rendered by a Graphics context or used
  13040. for geometric operations.
  13041. e.g. @code
  13042. Path myPath;
  13043. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  13044. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  13045. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  13046. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  13047. // add an ellipse as well, which will form a second sub-path within the path..
  13048. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  13049. // double the width of the whole thing..
  13050. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  13051. // and draw it to a graphics context with a 5-pixel thick outline.
  13052. g.strokePath (myPath, PathStrokeType (5.0f));
  13053. @endcode
  13054. A path object can actually contain multiple sub-paths, which may themselves
  13055. be open or closed.
  13056. @see PathFlatteningIterator, PathStrokeType, Graphics
  13057. */
  13058. class JUCE_API Path : private ArrayAllocationBase <float>
  13059. {
  13060. public:
  13061. /** Creates an empty path. */
  13062. Path() throw();
  13063. /** Creates a copy of another path. */
  13064. Path (const Path& other) throw();
  13065. /** Destructor. */
  13066. ~Path() throw();
  13067. /** Copies this path from another one. */
  13068. const Path& operator= (const Path& other) throw();
  13069. /** Returns true if the path doesn't contain any lines or curves. */
  13070. bool isEmpty() const throw();
  13071. /** Returns the smallest rectangle that contains all points within the path.
  13072. */
  13073. void getBounds (float& x, float& y,
  13074. float& w, float& h) const throw();
  13075. /** Returns the smallest rectangle that contains all points within the path
  13076. after it's been transformed with the given tranasform matrix.
  13077. */
  13078. void getBoundsTransformed (const AffineTransform& transform,
  13079. float& x, float& y,
  13080. float& w, float& h) const throw();
  13081. /** Checks whether a point lies within the path.
  13082. This is only relevent for closed paths (see closeSubPath()), and
  13083. may produce false results if used on a path which has open sub-paths.
  13084. The path's winding rule is taken into account by this method.
  13085. The tolerence parameter is passed to the PathFlatteningIterator that
  13086. is used to trace the path - for more info about it, see the notes for
  13087. the PathFlatteningIterator constructor.
  13088. @see closeSubPath, setUsingNonZeroWinding
  13089. */
  13090. bool contains (const float x,
  13091. const float y,
  13092. const float tolerence = 10.0f) const throw();
  13093. /** Checks whether a line crosses the path.
  13094. This will return positive if the line crosses any of the paths constituent
  13095. lines or curves. It doesn't take into account whether the line is inside
  13096. or outside the path, or whether the path is open or closed.
  13097. The tolerence parameter is passed to the PathFlatteningIterator that
  13098. is used to trace the path - for more info about it, see the notes for
  13099. the PathFlatteningIterator constructor.
  13100. */
  13101. bool intersectsLine (const float x1, const float y1,
  13102. const float x2, const float y2,
  13103. const float tolerence = 10.0f) throw();
  13104. /** Removes all lines and curves, resetting the path completely. */
  13105. void clear() throw();
  13106. /** Begins a new subpath with a given starting position.
  13107. This will move the path's current position to the co-ordinates passed in and
  13108. make it ready to draw lines or curves starting from this position.
  13109. After adding whatever lines and curves are needed, you can either
  13110. close the current sub-path using closeSubPath() or call startNewSubPath()
  13111. to move to a new sub-path, leaving the old one open-ended.
  13112. @see lineTo, quadraticTo, cubicTo, closeSubPath
  13113. */
  13114. void startNewSubPath (const float startX,
  13115. const float startY) throw();
  13116. /** Closes a the current sub-path with a line back to its start-point.
  13117. When creating a closed shape such as a triangle, don't use 3 lineTo()
  13118. calls - instead use two lineTo() calls, followed by a closeSubPath()
  13119. to join the final point back to the start.
  13120. This ensures that closes shapes are recognised as such, and this is
  13121. important for tasks like drawing strokes, which needs to know whether to
  13122. draw end-caps or not.
  13123. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  13124. */
  13125. void closeSubPath() throw();
  13126. /** Adds a line from the shape's last position to a new end-point.
  13127. This will connect the end-point of the last line or curve that was added
  13128. to a new point, using a straight line.
  13129. See the class description for an example of how to add lines and curves to a path.
  13130. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  13131. */
  13132. void lineTo (const float endX,
  13133. const float endY) throw();
  13134. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  13135. This will connect the end-point of the last line or curve that was added
  13136. to a new point, using a quadratic spline with one control-point.
  13137. See the class description for an example of how to add lines and curves to a path.
  13138. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  13139. */
  13140. void quadraticTo (const float controlPointX,
  13141. const float controlPointY,
  13142. const float endPointX,
  13143. const float endPointY) throw();
  13144. /** Adds a cubic bezier curve from the shape's last position to a new position.
  13145. This will connect the end-point of the last line or curve that was added
  13146. to a new point, using a cubic spline with two control-points.
  13147. See the class description for an example of how to add lines and curves to a path.
  13148. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  13149. */
  13150. void cubicTo (const float controlPoint1X,
  13151. const float controlPoint1Y,
  13152. const float controlPoint2X,
  13153. const float controlPoint2Y,
  13154. const float endPointX,
  13155. const float endPointY) throw();
  13156. /** Returns the last point that was added to the path by one of the drawing methods.
  13157. */
  13158. const Point getCurrentPosition() const;
  13159. /** Adds a rectangle to the path.
  13160. The rectangle is added as a new sub-path. (Any currently open paths will be
  13161. left open).
  13162. @see addRoundedRectangle, addTriangle
  13163. */
  13164. void addRectangle (const float x, const float y,
  13165. const float w, const float h) throw();
  13166. /** Adds a rectangle to the path.
  13167. The rectangle is added as a new sub-path. (Any currently open paths will be
  13168. left open).
  13169. @see addRoundedRectangle, addTriangle
  13170. */
  13171. void addRectangle (const Rectangle& rectangle) throw();
  13172. /** Adds a rectangle with rounded corners to the path.
  13173. The rectangle is added as a new sub-path. (Any currently open paths will be
  13174. left open).
  13175. @see addRectangle, addTriangle
  13176. */
  13177. void addRoundedRectangle (const float x, const float y,
  13178. const float w, const float h,
  13179. float cornerSize) throw();
  13180. /** Adds a rectangle with rounded corners to the path.
  13181. The rectangle is added as a new sub-path. (Any currently open paths will be
  13182. left open).
  13183. @see addRectangle, addTriangle
  13184. */
  13185. void addRoundedRectangle (const float x, const float y,
  13186. const float w, const float h,
  13187. float cornerSizeX,
  13188. float cornerSizeY) throw();
  13189. /** Adds a triangle to the path.
  13190. The triangle is added as a new closed sub-path. (Any currently open paths will be
  13191. left open).
  13192. Note that whether the vertices are specified in clockwise or anticlockwise
  13193. order will affect how the triangle is filled when it overlaps other
  13194. shapes (the winding order setting will affect this of course).
  13195. */
  13196. void addTriangle (const float x1, const float y1,
  13197. const float x2, const float y2,
  13198. const float x3, const float y3) throw();
  13199. /** Adds a quadrilateral to the path.
  13200. The quad is added as a new closed sub-path. (Any currently open paths will be
  13201. left open).
  13202. Note that whether the vertices are specified in clockwise or anticlockwise
  13203. order will affect how the quad is filled when it overlaps other
  13204. shapes (the winding order setting will affect this of course).
  13205. */
  13206. void addQuadrilateral (const float x1, const float y1,
  13207. const float x2, const float y2,
  13208. const float x3, const float y3,
  13209. const float x4, const float y4) throw();
  13210. /** Adds an ellipse to the path.
  13211. The shape is added as a new sub-path. (Any currently open paths will be
  13212. left open).
  13213. @see addArc
  13214. */
  13215. void addEllipse (const float x, const float y,
  13216. const float width, const float height) throw();
  13217. /** Adds an elliptical arc to the current path.
  13218. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  13219. or anti-clockwise according to whether the end angle is greater than the start. This means
  13220. that sometimes you may need to use values greater than 2*Pi for the end angle.
  13221. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  13222. @param y the top edge of the rectangle in which the elliptical outline fits
  13223. @param width the width of the rectangle in which the elliptical outline fits
  13224. @param height the height of the rectangle in which the elliptical outline fits
  13225. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  13226. top-centre of the ellipse)
  13227. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  13228. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  13229. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  13230. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  13231. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  13232. it will be added to the current sub-path, continuing from the current postition
  13233. @see addCentredArc, arcTo, addPieSegment, addEllipse
  13234. */
  13235. void addArc (const float x, const float y,
  13236. const float width, const float height,
  13237. const float fromRadians,
  13238. const float toRadians,
  13239. const bool startAsNewSubPath = false) throw();
  13240. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  13241. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  13242. or anti-clockwise according to whether the end angle is greater than the start. This means
  13243. that sometimes you may need to use values greater than 2*Pi for the end angle.
  13244. @param centreX the centre x of the ellipse
  13245. @param centreY the centre y of the ellipse
  13246. @param radiusX the horizontal radius of the ellipse
  13247. @param radiusY the vertical radius of the ellipse
  13248. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  13249. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  13250. top-centre of the ellipse)
  13251. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  13252. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  13253. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  13254. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  13255. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  13256. it will be added to the current sub-path, continuing from the current postition
  13257. @see addArc, arcTo
  13258. */
  13259. void addCentredArc (const float centreX, const float centreY,
  13260. const float radiusX, const float radiusY,
  13261. const float rotationOfEllipse,
  13262. const float fromRadians,
  13263. const float toRadians,
  13264. const bool startAsNewSubPath = false) throw();
  13265. /** Adds a "pie-chart" shape to the path.
  13266. The shape is added as a new sub-path. (Any currently open paths will be
  13267. left open).
  13268. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  13269. or anti-clockwise according to whether the end angle is greater than the start. This means
  13270. that sometimes you may need to use values greater than 2*Pi for the end angle.
  13271. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  13272. @param y the top edge of the rectangle in which the elliptical outline fits
  13273. @param width the width of the rectangle in which the elliptical outline fits
  13274. @param height the height of the rectangle in which the elliptical outline fits
  13275. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  13276. top-centre of the ellipse)
  13277. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  13278. top-centre of the ellipse)
  13279. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  13280. ellipse at its centre, where this value indicates the inner ellipse's size with
  13281. respect to the outer one.
  13282. @see addArc
  13283. */
  13284. void addPieSegment (const float x, const float y,
  13285. const float width, const float height,
  13286. const float fromRadians,
  13287. const float toRadians,
  13288. const float innerCircleProportionalSize);
  13289. /** Adds a line with a specified thickness.
  13290. The line is added as a new closed sub-path. (Any currently open paths will be
  13291. left open).
  13292. @see addArrow
  13293. */
  13294. void addLineSegment (const float startX, const float startY,
  13295. const float endX, const float endY,
  13296. float lineThickness) throw();
  13297. /** Adds a line with an arrowhead on the end.
  13298. The arrow is added as a new closed sub-path. (Any currently open paths will be
  13299. left open).
  13300. */
  13301. void addArrow (const float startX, const float startY,
  13302. const float endX, const float endY,
  13303. float lineThickness,
  13304. float arrowheadWidth,
  13305. float arrowheadLength) throw();
  13306. /** Adds a star shape to the path.
  13307. */
  13308. void addStar (const float centreX,
  13309. const float centreY,
  13310. const int numberOfPoints,
  13311. const float innerRadius,
  13312. const float outerRadius,
  13313. const float startAngle = 0.0f);
  13314. /** Adds a speech-bubble shape to the path.
  13315. @param bodyX the left of the main body area of the bubble
  13316. @param bodyY the top of the main body area of the bubble
  13317. @param bodyW the width of the main body area of the bubble
  13318. @param bodyH the height of the main body area of the bubble
  13319. @param cornerSize the amount by which to round off the corners of the main body rectangle
  13320. @param arrowTipX the x position that the tip of the arrow should connect to
  13321. @param arrowTipY the y position that the tip of the arrow should connect to
  13322. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  13323. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  13324. arrow's base should be - this is a proportional distance between 0 and 1.0
  13325. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  13326. */
  13327. void addBubble (float bodyX, float bodyY,
  13328. float bodyW, float bodyH,
  13329. float cornerSize,
  13330. float arrowTipX,
  13331. float arrowTipY,
  13332. int whichSide,
  13333. float arrowPositionAlongEdgeProportional,
  13334. float arrowWidth);
  13335. /** Adds another path to this one.
  13336. The new path is added as a new sub-path. (Any currently open paths in this
  13337. path will be left open).
  13338. @param pathToAppend the path to add
  13339. */
  13340. void addPath (const Path& pathToAppend) throw();
  13341. /** Adds another path to this one, transforming it on the way in.
  13342. The new path is added as a new sub-path, its points being transformed by the given
  13343. matrix before being added.
  13344. @param pathToAppend the path to add
  13345. @param transformToApply an optional transform to apply to the incoming vertices
  13346. */
  13347. void addPath (const Path& pathToAppend,
  13348. const AffineTransform& transformToApply) throw();
  13349. /** Swaps the contents of this path with another one.
  13350. The internal data of the two paths is swapped over, so this is much faster than
  13351. copying it to a temp variable and back.
  13352. */
  13353. void swapWithPath (Path& other);
  13354. /** Applies a 2D transform to all the vertices in the path.
  13355. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  13356. */
  13357. void applyTransform (const AffineTransform& transform) throw();
  13358. /** Rescales this path to make it fit neatly into a given space.
  13359. This is effectively a quick way of calling
  13360. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  13361. @param x the x position of the rectangle to fit the path inside
  13362. @param y the y position of the rectangle to fit the path inside
  13363. @param width the width of the rectangle to fit the path inside
  13364. @param height the height of the rectangle to fit the path inside
  13365. @param preserveProportions if true, it will fit the path into the space without altering its
  13366. horizontal/vertical scale ratio; if false, it will distort the
  13367. path to fill the specified ratio both horizontally and vertically
  13368. @see applyTransform, getTransformToScaleToFit
  13369. */
  13370. void scaleToFit (const float x, const float y,
  13371. const float width, const float height,
  13372. const bool preserveProportions) throw();
  13373. /** Returns a transform that can be used to rescale the path to fit into a given space.
  13374. @param x the x position of the rectangle to fit the path inside
  13375. @param y the y position of the rectangle to fit the path inside
  13376. @param width the width of the rectangle to fit the path inside
  13377. @param height the height of the rectangle to fit the path inside
  13378. @param preserveProportions if true, it will fit the path into the space without altering its
  13379. horizontal/vertical scale ratio; if false, it will distort the
  13380. path to fill the specified ratio both horizontally and vertically
  13381. @param justificationType if the proportions are preseved, the resultant path may be smaller
  13382. than the available rectangle, so this describes how it should be
  13383. positioned within the space.
  13384. @returns an appropriate transformation
  13385. @see applyTransform, scaleToFit
  13386. */
  13387. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  13388. const float width, const float height,
  13389. const bool preserveProportions,
  13390. const Justification& justificationType = Justification::centred) const throw();
  13391. /** Creates a version of this path where all sharp corners have been replaced by curves.
  13392. Wherever two lines meet at an angle, this will replace the corner with a curve
  13393. of the given radius.
  13394. */
  13395. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  13396. /** Changes the winding-rule to be used when filling the path.
  13397. If set to true (which is the default), then the path uses a non-zero-winding rule
  13398. to determine which points are inside the path. If set to false, it uses an
  13399. alternate-winding rule.
  13400. The winding-rule comes into play when areas of the shape overlap other
  13401. areas, and determines whether the overlapping regions are considered to be
  13402. inside or outside.
  13403. Changing this value just sets a flag - it doesn't affect the contents of the
  13404. path.
  13405. @see isUsingNonZeroWinding
  13406. */
  13407. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  13408. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  13409. The default for a new path is true.
  13410. @see setUsingNonZeroWinding
  13411. */
  13412. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  13413. /** Iterates the lines and curves that a path contains.
  13414. @see Path, PathFlatteningIterator
  13415. */
  13416. class JUCE_API Iterator
  13417. {
  13418. public:
  13419. Iterator (const Path& path);
  13420. ~Iterator();
  13421. /** Moves onto the next element in the path.
  13422. If this returns false, there are no more elements. If it returns true,
  13423. the elementType variable will be set to the type of the current element,
  13424. and some of the x and y variables will be filled in with values.
  13425. */
  13426. bool next();
  13427. enum PathElementType
  13428. {
  13429. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  13430. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  13431. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  13432. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  13433. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  13434. };
  13435. PathElementType elementType;
  13436. float x1, y1, x2, y2, x3, y3;
  13437. private:
  13438. const Path& path;
  13439. int index;
  13440. Iterator (const Iterator&);
  13441. const Iterator& operator= (const Iterator&);
  13442. };
  13443. /** Loads a stored path from a data stream.
  13444. The data in the stream must have been written using writePathToStream().
  13445. Note that this will append the stored path to whatever is currently in
  13446. this path, so you might need to call clear() beforehand.
  13447. @see loadPathFromData, writePathToStream
  13448. */
  13449. void loadPathFromStream (InputStream& source);
  13450. /** Loads a stored path from a block of data.
  13451. This is similar to loadPathFromStream(), but just reads from a block
  13452. of data. Useful if you're including stored shapes in your code as a
  13453. block of static data.
  13454. @see loadPathFromStream, writePathToStream
  13455. */
  13456. void loadPathFromData (const unsigned char* const data,
  13457. const int numberOfBytes) throw();
  13458. /** Stores the path by writing it out to a stream.
  13459. After writing out a path, you can reload it using loadPathFromStream().
  13460. @see loadPathFromStream, loadPathFromData
  13461. */
  13462. void writePathToStream (OutputStream& destination) const;
  13463. /** Creates a string containing a textual representation of this path.
  13464. @see restoreFromString
  13465. */
  13466. const String toString() const;
  13467. /** Restores this path from a string that was created with the toString() method.
  13468. @see toString()
  13469. */
  13470. void restoreFromString (const String& stringVersion);
  13471. juce_UseDebuggingNewOperator
  13472. private:
  13473. friend class PathFlatteningIterator;
  13474. friend class Path::Iterator;
  13475. int numElements;
  13476. float pathXMin, pathXMax, pathYMin, pathYMax;
  13477. bool useNonZeroWinding;
  13478. static const float lineMarker;
  13479. static const float moveMarker;
  13480. static const float quadMarker;
  13481. static const float cubicMarker;
  13482. static const float closeSubPathMarker;
  13483. };
  13484. #endif // __JUCE_PATH_JUCEHEADER__
  13485. /********* End of inlined file: juce_Path.h *********/
  13486. class Font;
  13487. class CustomTypefaceGlyphInfo;
  13488. /** A typeface represents a size-independent font.
  13489. This base class is abstract, but calling createSystemTypefaceFor() will return
  13490. a platform-specific subclass that can be used.
  13491. The CustomTypeface subclass allow you to build your own typeface, and to
  13492. load and save it in the Juce typeface format.
  13493. Normally you should never need to deal directly with Typeface objects - the Font
  13494. class does everything you typically need for rendering text.
  13495. @see CustomTypeface, Font
  13496. */
  13497. class JUCE_API Typeface : public ReferenceCountedObject
  13498. {
  13499. public:
  13500. /** A handy typedef for a pointer to a typeface. */
  13501. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  13502. /** Returns the name of the typeface.
  13503. @see Font::getTypefaceName
  13504. */
  13505. const String getName() const throw() { return name; }
  13506. /** Creates a new system typeface. */
  13507. static const Ptr createSystemTypefaceFor (const Font& font);
  13508. /** Destructor. */
  13509. virtual ~Typeface();
  13510. /** Returns the ascent of the font, as a proportion of its height.
  13511. The height is considered to always be normalised as 1.0, so this will be a
  13512. value less that 1.0, indicating the proportion of the font that lies above
  13513. its baseline.
  13514. */
  13515. virtual float getAscent() const = 0;
  13516. /** Returns the descent of the font, as a proportion of its height.
  13517. The height is considered to always be normalised as 1.0, so this will be a
  13518. value less that 1.0, indicating the proportion of the font that lies below
  13519. its baseline.
  13520. */
  13521. virtual float getDescent() const = 0;
  13522. /** Measures the width of a line of text.
  13523. The distance returned is based on the font having an normalised height of 1.0.
  13524. You should never need to call this directly! Use Font::getStringWidth() instead!
  13525. */
  13526. virtual float getStringWidth (const String& text) = 0;
  13527. /** Converts a line of text into its glyph numbers and their positions.
  13528. The distances returned are based on the font having an normalised height of 1.0.
  13529. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  13530. */
  13531. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  13532. /** Returns the outline for a glyph.
  13533. The path returned will be normalised to a font height of 1.0.
  13534. */
  13535. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  13536. juce_UseDebuggingNewOperator
  13537. protected:
  13538. String name;
  13539. Typeface (const String& name) throw();
  13540. private:
  13541. Typeface (const Typeface&);
  13542. const Typeface& operator= (const Typeface&);
  13543. };
  13544. /** A typeface that can be populated with custom glyphs.
  13545. You can create a CustomTypeface if you need one that contains your own glyphs,
  13546. or if you need to load a typeface from a Juce-formatted binary stream.
  13547. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  13548. to copy glyphs into this face.
  13549. @see Typeface, Font
  13550. */
  13551. class JUCE_API CustomTypeface : public Typeface
  13552. {
  13553. public:
  13554. /** Creates a new, empty typeface. */
  13555. CustomTypeface();
  13556. /** Loads a typeface from a previously saved stream.
  13557. The stream must have been created by writeToStream().
  13558. @see writeToStream
  13559. */
  13560. CustomTypeface (InputStream& serialisedTypefaceStream);
  13561. /** Destructor. */
  13562. ~CustomTypeface();
  13563. /** Resets this typeface, deleting all its glyphs and settings. */
  13564. void clear();
  13565. /** Sets the vital statistics for the typeface.
  13566. @param name the typeface's name
  13567. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  13568. the value that will be returned by Typeface::getAscent(). The
  13569. descent is assumed to be (1.0 - ascent)
  13570. @param isBold should be true if the typeface is bold
  13571. @param isItalic should be true if the typeface is italic
  13572. @param defaultCharacter the character to be used as a replacement if there's
  13573. no glyph available for the character that's being drawn
  13574. */
  13575. void setCharacteristics (const String& name, const float ascent,
  13576. const bool isBold, const bool isItalic,
  13577. const juce_wchar defaultCharacter) throw();
  13578. /** Adds a glyph to the typeface.
  13579. The path that is passed in is normalised so that the font height is 1.0, and its
  13580. origin is the anchor point of the character on its baseline.
  13581. The width is the nominal width of the character, and any extra kerning values that
  13582. are specified will be added to this width.
  13583. */
  13584. void addGlyph (const juce_wchar character, const Path& path, const float width) throw();
  13585. /** Specifies an extra kerning amount to be used between a pair of characters.
  13586. The amount will be added to the nominal width of the first character when laying out a string.
  13587. */
  13588. void addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw();
  13589. /** Adds a range of glyphs from another typeface.
  13590. This will attempt to pull in the paths and kerning information from another typeface and
  13591. add it to this one.
  13592. */
  13593. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  13594. /** Saves this typeface as a Juce-formatted font file.
  13595. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  13596. constructor.
  13597. */
  13598. bool writeToStream (OutputStream& outputStream);
  13599. // The following methods implement the basic Typeface behaviour.
  13600. float getAscent() const;
  13601. float getDescent() const;
  13602. float getStringWidth (const String& text);
  13603. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  13604. bool getOutlineForGlyph (int glyphNumber, Path& path);
  13605. int getGlyphForCharacter (juce_wchar character);
  13606. juce_UseDebuggingNewOperator
  13607. protected:
  13608. juce_wchar defaultCharacter;
  13609. float ascent;
  13610. bool isBold, isItalic;
  13611. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  13612. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  13613. particular character and there's no corresponding glyph, they'll call this
  13614. method so that a subclass can try to add that glyph, returning true if it
  13615. manages to do so.
  13616. */
  13617. virtual bool loadGlyphIfPossible (const juce_wchar characterNeeded);
  13618. private:
  13619. OwnedArray <CustomTypefaceGlyphInfo> glyphs;
  13620. short lookupTable [128];
  13621. CustomTypeface (const CustomTypeface&);
  13622. const CustomTypeface& operator= (const CustomTypeface&);
  13623. CustomTypefaceGlyphInfo* findGlyph (const juce_wchar character, const bool loadIfNeeded) throw();
  13624. CustomTypefaceGlyphInfo* findGlyphSubstituting (const juce_wchar character) throw();
  13625. };
  13626. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  13627. /********* End of inlined file: juce_Typeface.h *********/
  13628. class LowLevelGraphicsContext;
  13629. /**
  13630. Represents a particular font, including its size, style, etc.
  13631. Apart from the typeface to be used, a Font object also dictates whether
  13632. the font is bold, italic, underlined, how big it is, and its kerning and
  13633. horizontal scale factor.
  13634. @see Typeface
  13635. */
  13636. class JUCE_API Font
  13637. {
  13638. public:
  13639. /** A combination of these values is used by the constructor to specify the
  13640. style of font to use.
  13641. */
  13642. enum FontStyleFlags
  13643. {
  13644. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  13645. bold = 1, /**< boldens the font. @see setStyleFlags */
  13646. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  13647. underlined = 4 /**< underlines the font. @see setStyleFlags */
  13648. };
  13649. /** Creates a sans-serif font in a given size.
  13650. @param fontHeight the height in pixels (can be fractional)
  13651. @param styleFlags the style to use - this can be a combination of the
  13652. Font::bold, Font::italic and Font::underlined, or
  13653. just Font::plain for the normal style.
  13654. @see FontStyleFlags, getDefaultSansSerifFontName
  13655. */
  13656. Font (const float fontHeight,
  13657. const int styleFlags = plain) throw();
  13658. /** Creates a font with a given typeface and parameters.
  13659. @param typefaceName the name of the typeface to use
  13660. @param fontHeight the height in pixels (can be fractional)
  13661. @param styleFlags the style to use - this can be a combination of the
  13662. Font::bold, Font::italic and Font::underlined, or
  13663. just Font::plain for the normal style.
  13664. @see FontStyleFlags, getDefaultSansSerifFontName
  13665. */
  13666. Font (const String& typefaceName,
  13667. const float fontHeight,
  13668. const int styleFlags) throw();
  13669. /** Creates a copy of another Font object. */
  13670. Font (const Font& other) throw();
  13671. /** Creates a font for a typeface. */
  13672. Font (const Typeface::Ptr& typeface) throw();
  13673. /** Creates a basic sans-serif font at a default height.
  13674. You should use one of the other constructors for creating a font that you're planning
  13675. on drawing with - this constructor is here to help initialise objects before changing
  13676. the font's settings later.
  13677. */
  13678. Font() throw();
  13679. /** Copies this font from another one. */
  13680. const Font& operator= (const Font& other) throw();
  13681. bool operator== (const Font& other) const throw();
  13682. bool operator!= (const Font& other) const throw();
  13683. /** Destructor. */
  13684. ~Font() throw();
  13685. /** Changes the name of the typeface family.
  13686. e.g. "Arial", "Courier", etc.
  13687. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  13688. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  13689. but are generic names that are used to represent the various default fonts.
  13690. If you need to know the exact typeface name being used, you can call
  13691. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  13692. If a suitable font isn't found on the machine, it'll just use a default instead.
  13693. */
  13694. void setTypefaceName (const String& faceName) throw();
  13695. /** Returns the name of the typeface family that this font uses.
  13696. e.g. "Arial", "Courier", etc.
  13697. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  13698. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  13699. but are generic names that are used to represent the various default fonts.
  13700. If you need to know the exact typeface name being used, you can call
  13701. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  13702. */
  13703. const String& getTypefaceName() const throw() { return font->typefaceName; }
  13704. /** Returns a typeface name that represents the default sans-serif font.
  13705. This is also the typeface that will be used when a font is created without
  13706. specifying any typeface details.
  13707. Note that this method just returns a generic placeholder string that means "the default
  13708. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  13709. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  13710. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  13711. */
  13712. static const String getDefaultSansSerifFontName() throw();
  13713. /** Returns a typeface name that represents the default sans-serif font.
  13714. Note that this method just returns a generic placeholder string that means "the default
  13715. serif font" - it's not the actual name of this font. To get the actual name, use
  13716. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  13717. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13718. */
  13719. static const String getDefaultSerifFontName() throw();
  13720. /** Returns a typeface name that represents the default sans-serif font.
  13721. Note that this method just returns a generic placeholder string that means "the default
  13722. monospaced font" - it's not the actual name of this font. To get the actual name, use
  13723. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  13724. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13725. */
  13726. static const String getDefaultMonospacedFontName() throw();
  13727. /** Returns the typeface names of the default fonts on the current platform. */
  13728. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13729. /** Returns the total height of this font.
  13730. This is the maximum height, from the top of the ascent to the bottom of the
  13731. descenders.
  13732. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13733. */
  13734. float getHeight() const throw() { return font->height; }
  13735. /** Changes the font's height.
  13736. @see getHeight, setHeightWithoutChangingWidth
  13737. */
  13738. void setHeight (float newHeight) throw();
  13739. /** Changes the font's height without changing its width.
  13740. This alters the horizontal scale to compensate for the change in height.
  13741. */
  13742. void setHeightWithoutChangingWidth (float newHeight) throw();
  13743. /** Returns the height of the font above its baseline.
  13744. This is the maximum height from the baseline to the top.
  13745. @see getHeight, getDescent
  13746. */
  13747. float getAscent() const throw();
  13748. /** Returns the amount that the font descends below its baseline.
  13749. This is calculated as (getHeight() - getAscent()).
  13750. @see getAscent, getHeight
  13751. */
  13752. float getDescent() const throw();
  13753. /** Returns the font's style flags.
  13754. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13755. enum, to describe whether the font is bold, italic, etc.
  13756. @see FontStyleFlags
  13757. */
  13758. int getStyleFlags() const throw() { return font->styleFlags; }
  13759. /** Changes the font's style.
  13760. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13761. enum, to set the font's properties
  13762. @see FontStyleFlags
  13763. */
  13764. void setStyleFlags (const int newFlags) throw();
  13765. /** Makes the font bold or non-bold. */
  13766. void setBold (const bool shouldBeBold) throw();
  13767. /** Returns true if the font is bold. */
  13768. bool isBold() const throw();
  13769. /** Makes the font italic or non-italic. */
  13770. void setItalic (const bool shouldBeItalic) throw();
  13771. /** Returns true if the font is italic. */
  13772. bool isItalic() const throw();
  13773. /** Makes the font underlined or non-underlined. */
  13774. void setUnderline (const bool shouldBeUnderlined) throw();
  13775. /** Returns true if the font is underlined. */
  13776. bool isUnderlined() const throw();
  13777. /** Changes the font's horizontal scale factor.
  13778. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13779. narrower, greater than 1.0 will be stretched out.
  13780. */
  13781. void setHorizontalScale (const float scaleFactor) throw();
  13782. /** Returns the font's horizontal scale.
  13783. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13784. than 1.0 will be stretched out.
  13785. @see setHorizontalScale
  13786. */
  13787. float getHorizontalScale() const throw() { return font->horizontalScale; }
  13788. /** Changes the font's kerning.
  13789. @param extraKerning a multiple of the font's height that will be added
  13790. to space between the characters. So a value of zero is
  13791. normal spacing, positive values spread the letters out,
  13792. negative values make them closer together.
  13793. */
  13794. void setExtraKerningFactor (const float extraKerning) throw();
  13795. /** Returns the font's kerning.
  13796. This is the extra space added between adjacent characters, as a proportion
  13797. of the font's height.
  13798. A value of zero is normal spacing, positive values will spread the letters
  13799. out more, and negative values make them closer together.
  13800. */
  13801. float getExtraKerningFactor() const throw() { return font->kerning; }
  13802. /** Changes all the font's characteristics with one call. */
  13803. void setSizeAndStyle (float newHeight,
  13804. const int newStyleFlags,
  13805. const float newHorizontalScale,
  13806. const float newKerningAmount) throw();
  13807. /** Returns the total width of a string as it would be drawn using this font.
  13808. For a more accurate floating-point result, use getStringWidthFloat().
  13809. */
  13810. int getStringWidth (const String& text) const throw();
  13811. /** Returns the total width of a string as it would be drawn using this font.
  13812. @see getStringWidth
  13813. */
  13814. float getStringWidthFloat (const String& text) const throw();
  13815. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  13816. An extra x offset is added at the end of the run, to indicate where the right hand
  13817. edge of the last character is.
  13818. */
  13819. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  13820. /** Returns the typeface used by this font.
  13821. Note that the object returned may go out of scope if this font is deleted
  13822. or has its style changed.
  13823. */
  13824. Typeface* getTypeface() const throw();
  13825. /** Creates an array of Font objects to represent all the fonts on the system.
  13826. If you just need the names of the typefaces, you can also use
  13827. findAllTypefaceNames() instead.
  13828. @param results the array to which new Font objects will be added.
  13829. */
  13830. static void findFonts (OwnedArray<Font>& results) throw();
  13831. /** Returns a list of all the available typeface names.
  13832. The names returned can be passed into setTypefaceName().
  13833. You can use this instead of findFonts() if you only need their names, and not
  13834. font objects.
  13835. */
  13836. static const StringArray findAllTypefaceNames() throw();
  13837. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13838. in the requested typeface.
  13839. */
  13840. static const String getFallbackFontName() throw();
  13841. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13842. available in whatever font you're trying to use.
  13843. */
  13844. static void setFallbackFontName (const String& name) throw();
  13845. juce_UseDebuggingNewOperator
  13846. private:
  13847. friend class FontGlyphAlphaMap;
  13848. friend class TypefaceCache;
  13849. class SharedFontInternal : public ReferenceCountedObject
  13850. {
  13851. public:
  13852. SharedFontInternal (const String& typefaceName, const float height, const float horizontalScale,
  13853. const float kerning, const float ascent, const int styleFlags,
  13854. Typeface* const typeface) throw();
  13855. SharedFontInternal (const SharedFontInternal& other) throw();
  13856. String typefaceName;
  13857. float height, horizontalScale, kerning, ascent;
  13858. int styleFlags;
  13859. Typeface::Ptr typeface;
  13860. };
  13861. ReferenceCountedObjectPtr <SharedFontInternal> font;
  13862. void dupeInternalIfShared() throw();
  13863. };
  13864. #endif // __JUCE_FONT_JUCEHEADER__
  13865. /********* End of inlined file: juce_Font.h *********/
  13866. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13867. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13868. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13869. /**
  13870. Describes a type of stroke used to render a solid outline along a path.
  13871. A PathStrokeType object can be used directly to create the shape of an outline
  13872. around a path, and is used by Graphics::strokePath to specify the type of
  13873. stroke to draw.
  13874. @see Path, Graphics::strokePath
  13875. */
  13876. class JUCE_API PathStrokeType
  13877. {
  13878. public:
  13879. /** The type of shape to use for the corners between two adjacent line segments. */
  13880. enum JointStyle
  13881. {
  13882. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13883. Note that for angles that curve back on themselves, drawing a
  13884. mitre could require extending the point too far away from the
  13885. path, so a mitre limit is imposed and any corners that exceed it
  13886. are drawn as bevelled instead. */
  13887. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13888. beveled /**< Indicates that corners should be drawn with a line flattening their
  13889. outside edge. */
  13890. };
  13891. /** The type shape to use for the ends of lines. */
  13892. enum EndCapStyle
  13893. {
  13894. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13895. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13896. the thickness of the stroke. */
  13897. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13898. };
  13899. /** Creates a stroke type.
  13900. @param strokeThickness the width of the line to use
  13901. @param jointStyle the type of joints to use for corners
  13902. @param endStyle the type of end-caps to use for the ends of open paths.
  13903. */
  13904. PathStrokeType (const float strokeThickness,
  13905. const JointStyle jointStyle = mitered,
  13906. const EndCapStyle endStyle = butt) throw();
  13907. /** Createes a copy of another stroke type. */
  13908. PathStrokeType (const PathStrokeType& other) throw();
  13909. /** Copies another stroke onto this one. */
  13910. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13911. /** Destructor. */
  13912. ~PathStrokeType() throw();
  13913. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13914. @param destPath the resultant stroked outline shape will be copied into this path.
  13915. Note that it's ok for the source and destination Paths to be
  13916. the same object, so you can easily turn a path into a stroked version
  13917. of itself.
  13918. @param sourcePath the path to use as the source
  13919. @param transform an optional transform to apply to the points from the source path
  13920. as they are being used
  13921. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13922. a higher resolution, which improved the quality if you'll later want
  13923. to enlarge the stroked path
  13924. @see createDashedStroke
  13925. */
  13926. void createStrokedPath (Path& destPath,
  13927. const Path& sourcePath,
  13928. const AffineTransform& transform = AffineTransform::identity,
  13929. const float extraAccuracy = 1.0f) const throw();
  13930. /** Applies this stroke type to a path, creating a dashed line.
  13931. This is similar to createStrokedPath, but uses the array passed in to
  13932. break the stroke up into a series of dashes.
  13933. @param destPath the resultant stroked outline shape will be copied into this path.
  13934. Note that it's ok for the source and destination Paths to be
  13935. the same object, so you can easily turn a path into a stroked version
  13936. of itself.
  13937. @param sourcePath the path to use as the source
  13938. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13939. a line of length 2, then skip a length of 3, then add a line of length 4,
  13940. skip 5, and keep repeating this pattern.
  13941. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13942. an even number, otherwise the pattern will get out of step as it
  13943. repeats.
  13944. @param transform an optional transform to apply to the points from the source path
  13945. as they are being used
  13946. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13947. a higher resolution, which improved the quality if you'll later want
  13948. to enlarge the stroked path
  13949. */
  13950. void createDashedStroke (Path& destPath,
  13951. const Path& sourcePath,
  13952. const float* dashLengths,
  13953. int numDashLengths,
  13954. const AffineTransform& transform = AffineTransform::identity,
  13955. const float extraAccuracy = 1.0f) const throw();
  13956. /** Returns the stroke thickness. */
  13957. float getStrokeThickness() const throw() { return thickness; }
  13958. /** Returns the joint style. */
  13959. JointStyle getJointStyle() const throw() { return jointStyle; }
  13960. /** Returns the end-cap style. */
  13961. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13962. juce_UseDebuggingNewOperator
  13963. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13964. bool operator== (const PathStrokeType& other) const throw();
  13965. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13966. bool operator!= (const PathStrokeType& other) const throw();
  13967. private:
  13968. float thickness;
  13969. JointStyle jointStyle;
  13970. EndCapStyle endStyle;
  13971. };
  13972. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13973. /********* End of inlined file: juce_PathStrokeType.h *********/
  13974. /********* Start of inlined file: juce_Line.h *********/
  13975. #ifndef __JUCE_LINE_JUCEHEADER__
  13976. #define __JUCE_LINE_JUCEHEADER__
  13977. /**
  13978. Represents a line, using 32-bit float co-ordinates.
  13979. This class contains a bunch of useful methods for various geometric
  13980. tasks.
  13981. @see Point, Rectangle, Path, Graphics::drawLine
  13982. */
  13983. class JUCE_API Line
  13984. {
  13985. public:
  13986. /** Creates a line, using (0, 0) as its start and end points. */
  13987. Line() throw();
  13988. /** Creates a copy of another line. */
  13989. Line (const Line& other) throw();
  13990. /** Creates a line based on the co-ordinates of its start and end points. */
  13991. Line (const float startX,
  13992. const float startY,
  13993. const float endX,
  13994. const float endY) throw();
  13995. /** Creates a line from its start and end points. */
  13996. Line (const Point& start,
  13997. const Point& end) throw();
  13998. /** Copies a line from another one. */
  13999. const Line& operator= (const Line& other) throw();
  14000. /** Destructor. */
  14001. ~Line() throw();
  14002. /** Returns the x co-ordinate of the line's start point. */
  14003. inline float getStartX() const throw() { return startX; }
  14004. /** Returns the y co-ordinate of the line's start point. */
  14005. inline float getStartY() const throw() { return startY; }
  14006. /** Returns the x co-ordinate of the line's end point. */
  14007. inline float getEndX() const throw() { return endX; }
  14008. /** Returns the y co-ordinate of the line's end point. */
  14009. inline float getEndY() const throw() { return endY; }
  14010. /** Returns the line's start point. */
  14011. const Point getStart() const throw();
  14012. /** Returns the line's end point. */
  14013. const Point getEnd() const throw();
  14014. /** Changes this line's start point */
  14015. void setStart (const float newStartX,
  14016. const float newStartY) throw();
  14017. /** Changes this line's end point */
  14018. void setEnd (const float newEndX,
  14019. const float newEndY) throw();
  14020. /** Changes this line's start point */
  14021. void setStart (const Point& newStart) throw();
  14022. /** Changes this line's end point */
  14023. void setEnd (const Point& newEnd) throw();
  14024. /** Applies an affine transform to the line's start and end points. */
  14025. void applyTransform (const AffineTransform& transform) throw();
  14026. /** Returns the length of the line. */
  14027. float getLength() const throw();
  14028. /** Returns true if the line's start and end x co-ordinates are the same. */
  14029. bool isVertical() const throw();
  14030. /** Returns true if the line's start and end y co-ordinates are the same. */
  14031. bool isHorizontal() const throw();
  14032. /** Returns the line's angle.
  14033. This value is the number of radians clockwise from the 3 o'clock direction,
  14034. where the line's start point is considered to be at the centre.
  14035. */
  14036. float getAngle() const throw();
  14037. /** Compares two lines. */
  14038. bool operator== (const Line& other) const throw();
  14039. /** Compares two lines. */
  14040. bool operator!= (const Line& other) const throw();
  14041. /** Finds the intersection between two lines.
  14042. @param line the other line
  14043. @param intersectionX the x co-ordinate of the point where the lines meet (or
  14044. where they would meet if they were infinitely long)
  14045. the intersection (if the lines intersect). If the lines
  14046. are parallel, this will just be set to the position
  14047. of one of the line's endpoints.
  14048. @param intersectionY the y co-ordinate of the point where the lines meet
  14049. @returns true if the line segments intersect; false if they dont. Even if they
  14050. don't intersect, the intersection co-ordinates returned will still
  14051. be valid
  14052. */
  14053. bool intersects (const Line& line,
  14054. float& intersectionX,
  14055. float& intersectionY) const throw();
  14056. /** Returns the location of the point which is a given distance along this line.
  14057. @param distanceFromStart the distance to move along the line from its
  14058. start point. This value can be negative or longer
  14059. than the line itself
  14060. @see getPointAlongLineProportionally
  14061. */
  14062. const Point getPointAlongLine (const float distanceFromStart) const throw();
  14063. /** Returns a point which is a certain distance along and to the side of this line.
  14064. This effectively moves a given distance along the line, then another distance
  14065. perpendicularly to this, and returns the resulting position.
  14066. @param distanceFromStart the distance to move along the line from its
  14067. start point. This value can be negative or longer
  14068. than the line itself
  14069. @param perpendicularDistance how far to move sideways from the line. If you're
  14070. looking along the line from its start towards its
  14071. end, then a positive value here will move to the
  14072. right, negative value move to the left.
  14073. */
  14074. const Point getPointAlongLine (const float distanceFromStart,
  14075. const float perpendicularDistance) const throw();
  14076. /** Returns the location of the point which is a given distance along this line
  14077. proportional to the line's length.
  14078. @param proportionOfLength the distance to move along the line from its
  14079. start point, in multiples of the line's length.
  14080. So a value of 0.0 will return the line's start point
  14081. and a value of 1.0 will return its end point. (This value
  14082. can be negative or greater than 1.0).
  14083. @see getPointAlongLine
  14084. */
  14085. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  14086. /** Returns the smallest distance between this line segment and a given point.
  14087. So if the point is close to the line, this will return the perpendicular
  14088. distance from the line; if the point is a long way beyond one of the line's
  14089. end-point's, it'll return the straight-line distance to the nearest end-point.
  14090. @param x x position of the point to test
  14091. @param y y position of the point to test
  14092. @returns the point's distance from the line
  14093. @see getPositionAlongLineOfNearestPoint
  14094. */
  14095. float getDistanceFromLine (const float x,
  14096. const float y) const throw();
  14097. /** Finds the point on this line which is nearest to a given point, and
  14098. returns its position as a proportional position along the line.
  14099. @param x x position of the point to test
  14100. @param y y position of the point to test
  14101. @returns a value 0 to 1.0 which is the distance along this line from the
  14102. line's start to the point which is nearest to the point passed-in. To
  14103. turn this number into a position, use getPointAlongLineProportionally().
  14104. @see getDistanceFromLine, getPointAlongLineProportionally
  14105. */
  14106. float findNearestPointTo (const float x,
  14107. const float y) const throw();
  14108. /** Returns true if the given point lies above this line.
  14109. The return value is true if the point's y coordinate is less than the y
  14110. coordinate of this line at the given x (assuming the line extends infinitely
  14111. in both directions).
  14112. */
  14113. bool isPointAbove (const float x, const float y) const throw();
  14114. /** Returns a shortened copy of this line.
  14115. This will chop off part of the start of this line by a certain amount, (leaving the
  14116. end-point the same), and return the new line.
  14117. */
  14118. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  14119. /** Returns a shortened copy of this line.
  14120. This will chop off part of the end of this line by a certain amount, (leaving the
  14121. start-point the same), and return the new line.
  14122. */
  14123. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  14124. /** Cuts off parts of this line to keep the parts that are either inside or
  14125. outside a path.
  14126. Note that this isn't smart enough to cope with situations where the
  14127. line would need to be cut into multiple pieces to correctly clip against
  14128. a re-entrant shape.
  14129. @param path the path to clip against
  14130. @param keepSectionOutsidePath if true, it's the section outside the path
  14131. that will be kept; if false its the section inside
  14132. the path
  14133. @returns true if the line was changed.
  14134. */
  14135. bool clipToPath (const Path& path,
  14136. const bool keepSectionOutsidePath) throw();
  14137. juce_UseDebuggingNewOperator
  14138. private:
  14139. float startX, startY, endX, endY;
  14140. };
  14141. #endif // __JUCE_LINE_JUCEHEADER__
  14142. /********* End of inlined file: juce_Line.h *********/
  14143. /********* Start of inlined file: juce_Colours.h *********/
  14144. #ifndef __JUCE_COLOURS_JUCEHEADER__
  14145. #define __JUCE_COLOURS_JUCEHEADER__
  14146. /********* Start of inlined file: juce_Colour.h *********/
  14147. #ifndef __JUCE_COLOUR_JUCEHEADER__
  14148. #define __JUCE_COLOUR_JUCEHEADER__
  14149. /********* Start of inlined file: juce_PixelFormats.h *********/
  14150. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  14151. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  14152. #if JUCE_MSVC
  14153. #pragma pack (push, 1)
  14154. #define PACKED
  14155. #elif JUCE_GCC
  14156. #define PACKED __attribute__((packed))
  14157. #else
  14158. #define PACKED
  14159. #endif
  14160. class PixelRGB;
  14161. /**
  14162. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  14163. operations with it.
  14164. This is used internally by the imaging classes.
  14165. @see PixelRGB
  14166. */
  14167. class JUCE_API PixelARGB
  14168. {
  14169. public:
  14170. /** Creates a pixel without defining its colour. */
  14171. PixelARGB() throw() {}
  14172. ~PixelARGB() throw() {}
  14173. /** Creates a pixel from a 32-bit argb value.
  14174. */
  14175. PixelARGB (const uint32 argb_) throw()
  14176. : argb (argb_)
  14177. {
  14178. }
  14179. forcedinline uint32 getARGB() const throw() { return argb; }
  14180. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  14181. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  14182. forcedinline uint8 getAlpha() const throw() { return components.a; }
  14183. forcedinline uint8 getRed() const throw() { return components.r; }
  14184. forcedinline uint8 getGreen() const throw() { return components.g; }
  14185. forcedinline uint8 getBlue() const throw() { return components.b; }
  14186. /** Blends another pixel onto this one.
  14187. This takes into account the opacity of the pixel being overlaid, and blends
  14188. it accordingly.
  14189. */
  14190. template <class Pixel>
  14191. forcedinline void blend (const Pixel& src) throw()
  14192. {
  14193. uint32 sargb = src.getARGB();
  14194. const uint32 alpha = 0x100 - (sargb >> 24);
  14195. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14196. sargb += 0xff00ff00 & (getAG() * alpha);
  14197. argb = sargb;
  14198. }
  14199. /** Blends another pixel onto this one.
  14200. This takes into account the opacity of the pixel being overlaid, and blends
  14201. it accordingly.
  14202. */
  14203. forcedinline void blend (const PixelRGB& src) throw();
  14204. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  14205. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  14206. being used, so this can blend semi-transparently from a PixelRGB argument.
  14207. */
  14208. template <class Pixel>
  14209. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  14210. {
  14211. ++extraAlpha;
  14212. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  14213. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  14214. const uint32 alpha = 0x100 - (sargb >> 24);
  14215. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14216. sargb += 0xff00ff00 & (getAG() * alpha);
  14217. argb = sargb;
  14218. }
  14219. /** Blends another pixel with this one, creating a colour that is somewhere
  14220. between the two, as specified by the amount.
  14221. */
  14222. template <class Pixel>
  14223. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  14224. {
  14225. uint32 drb = getRB();
  14226. drb += (((src.getRB() - drb) * amount) >> 8);
  14227. drb &= 0x00ff00ff;
  14228. uint32 dag = getAG();
  14229. dag += (((src.getAG() - dag) * amount) >> 8);
  14230. dag &= 0x00ff00ff;
  14231. dag <<= 8;
  14232. dag |= drb;
  14233. argb = dag;
  14234. }
  14235. /** Copies another pixel colour over this one.
  14236. This doesn't blend it - this colour is simply replaced by the other one.
  14237. */
  14238. template <class Pixel>
  14239. forcedinline void set (const Pixel& src) throw()
  14240. {
  14241. argb = src.getARGB();
  14242. }
  14243. /** Replaces the colour's alpha value with another one. */
  14244. forcedinline void setAlpha (const uint8 newAlpha) throw()
  14245. {
  14246. components.a = newAlpha;
  14247. }
  14248. /** Multiplies the colour's alpha value with another one. */
  14249. forcedinline void multiplyAlpha (int multiplier) throw()
  14250. {
  14251. ++multiplier;
  14252. argb = ((multiplier * getAG()) & 0xff00ff00)
  14253. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  14254. }
  14255. forcedinline void multiplyAlpha (const float multiplier) throw()
  14256. {
  14257. multiplyAlpha ((int) (multiplier * 256.0f));
  14258. }
  14259. /** Sets the pixel's colour from individual components. */
  14260. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  14261. {
  14262. components.b = b;
  14263. components.g = g;
  14264. components.r = r;
  14265. components.a = a;
  14266. }
  14267. /** Premultiplies the pixel's RGB values by its alpha. */
  14268. forcedinline void premultiply() throw()
  14269. {
  14270. const uint32 alpha = components.a;
  14271. if (alpha < 0xff)
  14272. {
  14273. if (alpha == 0)
  14274. {
  14275. components.b = 0;
  14276. components.g = 0;
  14277. components.r = 0;
  14278. }
  14279. else
  14280. {
  14281. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  14282. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  14283. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  14284. }
  14285. }
  14286. }
  14287. /** Unpremultiplies the pixel's RGB values. */
  14288. forcedinline void unpremultiply() throw()
  14289. {
  14290. const uint32 alpha = components.a;
  14291. if (alpha < 0xff)
  14292. {
  14293. if (alpha == 0)
  14294. {
  14295. components.b = 0;
  14296. components.g = 0;
  14297. components.r = 0;
  14298. }
  14299. else
  14300. {
  14301. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  14302. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  14303. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  14304. }
  14305. }
  14306. }
  14307. forcedinline void desaturate() throw()
  14308. {
  14309. if (components.a < 0xff && components.a > 0)
  14310. {
  14311. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  14312. components.r = components.g = components.b
  14313. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  14314. }
  14315. else
  14316. {
  14317. components.r = components.g = components.b
  14318. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  14319. }
  14320. }
  14321. /** The indexes of the different components in the byte layout of this type of colour. */
  14322. #if JUCE_BIG_ENDIAN
  14323. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  14324. #else
  14325. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  14326. #endif
  14327. private:
  14328. union
  14329. {
  14330. uint32 argb;
  14331. struct
  14332. {
  14333. #if JUCE_BIG_ENDIAN
  14334. uint8 a : 8, r : 8, g : 8, b : 8;
  14335. #else
  14336. uint8 b, g, r, a;
  14337. #endif
  14338. } PACKED components;
  14339. };
  14340. } PACKED;
  14341. /**
  14342. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  14343. This is used internally by the imaging classes.
  14344. @see PixelARGB
  14345. */
  14346. class JUCE_API PixelRGB
  14347. {
  14348. public:
  14349. /** Creates a pixel without defining its colour. */
  14350. PixelRGB() throw() {}
  14351. ~PixelRGB() throw() {}
  14352. /** Creates a pixel from a 32-bit argb value.
  14353. (The argb format is that used by PixelARGB)
  14354. */
  14355. PixelRGB (const uint32 argb) throw()
  14356. {
  14357. r = (uint8) (argb >> 16);
  14358. g = (uint8) (argb >> 8);
  14359. b = (uint8) (argb);
  14360. }
  14361. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  14362. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  14363. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  14364. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  14365. forcedinline uint8 getRed() const throw() { return r; }
  14366. forcedinline uint8 getGreen() const throw() { return g; }
  14367. forcedinline uint8 getBlue() const throw() { return b; }
  14368. /** Blends another pixel onto this one.
  14369. This takes into account the opacity of the pixel being overlaid, and blends
  14370. it accordingly.
  14371. */
  14372. forcedinline void blend (const PixelARGB& src) throw()
  14373. {
  14374. uint32 sargb = src.getARGB();
  14375. const uint32 alpha = 0x100 - (sargb >> 24);
  14376. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14377. sargb += 0x0000ff00 & (g * alpha);
  14378. r = (uint8) (sargb >> 16);
  14379. g = (uint8) (sargb >> 8);
  14380. b = (uint8) sargb;
  14381. }
  14382. forcedinline void blend (const PixelRGB& src) throw()
  14383. {
  14384. set (src);
  14385. }
  14386. template <class Pixel>
  14387. forcedinline void blend (const Pixel& src) throw()
  14388. {
  14389. blend (PixelARGB (src.getARGB()));
  14390. }
  14391. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  14392. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  14393. being used, so this can blend semi-transparently from a PixelRGB argument.
  14394. */
  14395. template <class Pixel>
  14396. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  14397. {
  14398. ++extraAlpha;
  14399. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  14400. const uint32 sag = extraAlpha * src.getAG();
  14401. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  14402. const uint32 alpha = 0x100 - (sargb >> 24);
  14403. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14404. sargb += 0x0000ff00 & (g * alpha);
  14405. b = (uint8) sargb;
  14406. g = (uint8) (sargb >> 8);
  14407. r = (uint8) (sargb >> 16);
  14408. }
  14409. /** Blends another pixel with this one, creating a colour that is somewhere
  14410. between the two, as specified by the amount.
  14411. */
  14412. template <class Pixel>
  14413. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  14414. {
  14415. uint32 drb = getRB();
  14416. drb += (((src.getRB() - drb) * amount) >> 8);
  14417. uint32 dag = getAG();
  14418. dag += (((src.getAG() - dag) * amount) >> 8);
  14419. b = (uint8) drb;
  14420. g = (uint8) dag;
  14421. r = (uint8) (drb >> 16);
  14422. }
  14423. /** Copies another pixel colour over this one.
  14424. This doesn't blend it - this colour is simply replaced by the other one.
  14425. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  14426. is thrown away.
  14427. */
  14428. template <class Pixel>
  14429. forcedinline void set (const Pixel& src) throw()
  14430. {
  14431. b = src.getBlue();
  14432. g = src.getGreen();
  14433. r = src.getRed();
  14434. }
  14435. /** This method is included for compatibility with the PixelARGB class. */
  14436. forcedinline void setAlpha (const uint8) throw() {}
  14437. /** Multiplies the colour's alpha value with another one. */
  14438. forcedinline void multiplyAlpha (int) throw() {}
  14439. /** Sets the pixel's colour from individual components. */
  14440. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  14441. {
  14442. r = r_;
  14443. g = g_;
  14444. b = b_;
  14445. }
  14446. /** Premultiplies the pixel's RGB values by its alpha. */
  14447. forcedinline void premultiply() throw() {}
  14448. /** Unpremultiplies the pixel's RGB values. */
  14449. forcedinline void unpremultiply() throw() {}
  14450. forcedinline void desaturate() throw()
  14451. {
  14452. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  14453. }
  14454. /** The indexes of the different components in the byte layout of this type of colour. */
  14455. #if JUCE_MAC
  14456. enum { indexR = 0, indexG = 1, indexB = 2 };
  14457. #else
  14458. enum { indexR = 2, indexG = 1, indexB = 0 };
  14459. #endif
  14460. private:
  14461. #if JUCE_MAC
  14462. uint8 r, g, b;
  14463. #else
  14464. uint8 b, g, r;
  14465. #endif
  14466. } PACKED;
  14467. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  14468. {
  14469. set (src);
  14470. }
  14471. /**
  14472. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  14473. This is used internally by the imaging classes.
  14474. @see PixelARGB, PixelRGB
  14475. */
  14476. class JUCE_API PixelAlpha
  14477. {
  14478. public:
  14479. /** Creates a pixel without defining its colour. */
  14480. PixelAlpha() throw() {}
  14481. ~PixelAlpha() throw() {}
  14482. /** Creates a pixel from a 32-bit argb value.
  14483. (The argb format is that used by PixelARGB)
  14484. */
  14485. PixelAlpha (const uint32 argb) throw()
  14486. {
  14487. a = (uint8) (argb >> 24);
  14488. }
  14489. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  14490. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  14491. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  14492. forcedinline uint8 getAlpha() const throw() { return a; }
  14493. forcedinline uint8 getRed() const throw() { return 0; }
  14494. forcedinline uint8 getGreen() const throw() { return 0; }
  14495. forcedinline uint8 getBlue() const throw() { return 0; }
  14496. /** Blends another pixel onto this one.
  14497. This takes into account the opacity of the pixel being overlaid, and blends
  14498. it accordingly.
  14499. */
  14500. template <class Pixel>
  14501. forcedinline void blend (const Pixel& src) throw()
  14502. {
  14503. const int srcA = src.getAlpha();
  14504. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  14505. }
  14506. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  14507. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  14508. being used, so this can blend semi-transparently from a PixelRGB argument.
  14509. */
  14510. template <class Pixel>
  14511. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  14512. {
  14513. ++extraAlpha;
  14514. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  14515. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  14516. }
  14517. /** Blends another pixel with this one, creating a colour that is somewhere
  14518. between the two, as specified by the amount.
  14519. */
  14520. template <class Pixel>
  14521. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  14522. {
  14523. a += ((src,getAlpha() - a) * amount) >> 8;
  14524. }
  14525. /** Copies another pixel colour over this one.
  14526. This doesn't blend it - this colour is simply replaced by the other one.
  14527. */
  14528. template <class Pixel>
  14529. forcedinline void set (const Pixel& src) throw()
  14530. {
  14531. a = src.getAlpha();
  14532. }
  14533. /** Replaces the colour's alpha value with another one. */
  14534. forcedinline void setAlpha (const uint8 newAlpha) throw()
  14535. {
  14536. a = newAlpha;
  14537. }
  14538. /** Multiplies the colour's alpha value with another one. */
  14539. forcedinline void multiplyAlpha (int multiplier) throw()
  14540. {
  14541. ++multiplier;
  14542. a = (uint8) ((a * multiplier) >> 8);
  14543. }
  14544. forcedinline void multiplyAlpha (const float multiplier) throw()
  14545. {
  14546. a = (uint8) (a * multiplier);
  14547. }
  14548. /** Sets the pixel's colour from individual components. */
  14549. forcedinline void setARGB (const uint8 a_, const uint8 r, const uint8 g, const uint8 b) throw()
  14550. {
  14551. a = a_;
  14552. }
  14553. /** Premultiplies the pixel's RGB values by its alpha. */
  14554. forcedinline void premultiply() throw()
  14555. {
  14556. }
  14557. /** Unpremultiplies the pixel's RGB values. */
  14558. forcedinline void unpremultiply() throw()
  14559. {
  14560. }
  14561. forcedinline void desaturate() throw()
  14562. {
  14563. }
  14564. private:
  14565. uint8 a : 8;
  14566. } PACKED;
  14567. #if JUCE_MSVC
  14568. #pragma pack (pop)
  14569. #endif
  14570. #undef PACKED
  14571. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  14572. /********* End of inlined file: juce_PixelFormats.h *********/
  14573. /**
  14574. Represents a colour, also including a transparency value.
  14575. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  14576. */
  14577. class JUCE_API Colour
  14578. {
  14579. public:
  14580. /** Creates a transparent black colour. */
  14581. Colour() throw();
  14582. /** Creates a copy of another Colour object. */
  14583. Colour (const Colour& other) throw();
  14584. /** Creates a colour from a 32-bit ARGB value.
  14585. The format of this number is:
  14586. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  14587. All components in the range 0x00 to 0xff.
  14588. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14589. @see getPixelARGB
  14590. */
  14591. explicit Colour (const uint32 argb) throw();
  14592. /** Creates an opaque colour using 8-bit red, green and blue values */
  14593. Colour (const uint8 red,
  14594. const uint8 green,
  14595. const uint8 blue) throw();
  14596. /** Creates an opaque colour using 8-bit red, green and blue values */
  14597. static const Colour fromRGB (const uint8 red,
  14598. const uint8 green,
  14599. const uint8 blue) throw();
  14600. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14601. Colour (const uint8 red,
  14602. const uint8 green,
  14603. const uint8 blue,
  14604. const uint8 alpha) throw();
  14605. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14606. static const Colour fromRGBA (const uint8 red,
  14607. const uint8 green,
  14608. const uint8 blue,
  14609. const uint8 alpha) throw();
  14610. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  14611. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  14612. Values outside the valid range will be clipped.
  14613. */
  14614. Colour (const uint8 red,
  14615. const uint8 green,
  14616. const uint8 blue,
  14617. const float alpha) throw();
  14618. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  14619. static const Colour fromRGBAFloat (const uint8 red,
  14620. const uint8 green,
  14621. const uint8 blue,
  14622. const float alpha) throw();
  14623. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14624. The floating point values must be between 0.0 and 1.0.
  14625. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14626. Values outside the valid range will be clipped.
  14627. */
  14628. Colour (const float hue,
  14629. const float saturation,
  14630. const float brightness,
  14631. const uint8 alpha) throw();
  14632. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  14633. All values must be between 0.0 and 1.0.
  14634. Numbers outside the valid range will be clipped.
  14635. */
  14636. Colour (const float hue,
  14637. const float saturation,
  14638. const float brightness,
  14639. const float alpha) throw();
  14640. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14641. The floating point values must be between 0.0 and 1.0.
  14642. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14643. Values outside the valid range will be clipped.
  14644. */
  14645. static const Colour fromHSV (const float hue,
  14646. const float saturation,
  14647. const float brightness,
  14648. const float alpha) throw();
  14649. /** Destructor. */
  14650. ~Colour() throw();
  14651. /** Copies another Colour object. */
  14652. const Colour& operator= (const Colour& other) throw();
  14653. /** Compares two colours. */
  14654. bool operator== (const Colour& other) const throw();
  14655. /** Compares two colours. */
  14656. bool operator!= (const Colour& other) const throw();
  14657. /** Returns the red component of this colour.
  14658. @returns a value between 0x00 and 0xff.
  14659. */
  14660. uint8 getRed() const throw() { return argb.getRed(); }
  14661. /** Returns the green component of this colour.
  14662. @returns a value between 0x00 and 0xff.
  14663. */
  14664. uint8 getGreen() const throw() { return argb.getGreen(); }
  14665. /** Returns the blue component of this colour.
  14666. @returns a value between 0x00 and 0xff.
  14667. */
  14668. uint8 getBlue() const throw() { return argb.getBlue(); }
  14669. /** Returns the red component of this colour as a floating point value.
  14670. @returns a value between 0.0 and 1.0
  14671. */
  14672. float getFloatRed() const throw();
  14673. /** Returns the green component of this colour as a floating point value.
  14674. @returns a value between 0.0 and 1.0
  14675. */
  14676. float getFloatGreen() const throw();
  14677. /** Returns the blue component of this colour as a floating point value.
  14678. @returns a value between 0.0 and 1.0
  14679. */
  14680. float getFloatBlue() const throw();
  14681. /** Returns a premultiplied ARGB pixel object that represents this colour.
  14682. */
  14683. const PixelARGB getPixelARGB() const throw();
  14684. /** Returns a 32-bit integer that represents this colour.
  14685. The format of this number is:
  14686. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14687. */
  14688. uint32 getARGB() const throw();
  14689. /** Returns the colour's alpha (opacity).
  14690. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  14691. */
  14692. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  14693. /** Returns the colour's alpha (opacity) as a floating point value.
  14694. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  14695. */
  14696. float getFloatAlpha() const throw();
  14697. /** Returns true if this colour is completely opaque.
  14698. Equivalent to (getAlpha() == 0xff).
  14699. */
  14700. bool isOpaque() const throw();
  14701. /** Returns true if this colour is completely transparent.
  14702. Equivalent to (getAlpha() == 0x00).
  14703. */
  14704. bool isTransparent() const throw();
  14705. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14706. const Colour withAlpha (const uint8 newAlpha) const throw();
  14707. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14708. const Colour withAlpha (const float newAlpha) const throw();
  14709. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14710. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14711. */
  14712. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14713. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14714. If the foreground colour is semi-transparent, it is blended onto this colour
  14715. accordingly.
  14716. */
  14717. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14718. /** Returns a colour that lies somewhere between this one and another.
  14719. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  14720. is 1.0, the result is 100% of the other colour.
  14721. */
  14722. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  14723. /** Returns the colour's hue component.
  14724. The value returned is in the range 0.0 to 1.0
  14725. */
  14726. float getHue() const throw();
  14727. /** Returns the colour's saturation component.
  14728. The value returned is in the range 0.0 to 1.0
  14729. */
  14730. float getSaturation() const throw();
  14731. /** Returns the colour's brightness component.
  14732. The value returned is in the range 0.0 to 1.0
  14733. */
  14734. float getBrightness() const throw();
  14735. /** Returns the colour's hue, saturation and brightness components all at once.
  14736. The values returned are in the range 0.0 to 1.0
  14737. */
  14738. void getHSB (float& hue,
  14739. float& saturation,
  14740. float& brightness) const throw();
  14741. /** Returns a copy of this colour with a different hue. */
  14742. const Colour withHue (const float newHue) const throw();
  14743. /** Returns a copy of this colour with a different saturation. */
  14744. const Colour withSaturation (const float newSaturation) const throw();
  14745. /** Returns a copy of this colour with a different brightness.
  14746. @see brighter, darker, withMultipliedBrightness
  14747. */
  14748. const Colour withBrightness (const float newBrightness) const throw();
  14749. /** Returns a copy of this colour with it hue rotated.
  14750. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14751. @see brighter, darker, withMultipliedBrightness
  14752. */
  14753. const Colour withRotatedHue (const float amountToRotate) const throw();
  14754. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14755. The new colour's saturation is (this->getSaturation() * multiplier)
  14756. (the result is clipped to legal limits).
  14757. */
  14758. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14759. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14760. The new colour's saturation is (this->getBrightness() * multiplier)
  14761. (the result is clipped to legal limits).
  14762. */
  14763. const Colour withMultipliedBrightness (const float amount) const throw();
  14764. /** Returns a brighter version of this colour.
  14765. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14766. unchanged, and higher values make it brighter
  14767. @see withMultipliedBrightness
  14768. */
  14769. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14770. /** Returns a darker version of this colour.
  14771. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14772. unchanged, and higher values make it darker
  14773. @see withMultipliedBrightness
  14774. */
  14775. const Colour darker (float amountDarker = 0.4f) const throw();
  14776. /** Returns a colour that will be clearly visible against this colour.
  14777. The amount parameter indicates how contrasting the new colour should
  14778. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14779. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14780. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14781. */
  14782. const Colour contrasting (const float amount = 1.0f) const throw();
  14783. /** Returns a colour that contrasts against two colours.
  14784. Looks for a colour that contrasts with both of the colours passed-in.
  14785. Handy for things like choosing a highlight colour in text editors, etc.
  14786. */
  14787. static const Colour contrasting (const Colour& colour1,
  14788. const Colour& colour2) throw();
  14789. /** Returns an opaque shade of grey.
  14790. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14791. */
  14792. static const Colour greyLevel (const float brightness) throw();
  14793. /** Returns a stringified version of this colour.
  14794. The string can be turned back into a colour using the fromString() method.
  14795. */
  14796. const String toString() const throw();
  14797. /** Reads the colour from a string that was created with toString().
  14798. */
  14799. static const Colour fromString (const String& encodedColourString);
  14800. juce_UseDebuggingNewOperator
  14801. private:
  14802. PixelARGB argb;
  14803. };
  14804. #endif // __JUCE_COLOUR_JUCEHEADER__
  14805. /********* End of inlined file: juce_Colour.h *********/
  14806. /**
  14807. Contains a set of predefined named colours (mostly standard HTML colours)
  14808. @see Colour, Colours::greyLevel
  14809. */
  14810. class Colours
  14811. {
  14812. public:
  14813. static JUCE_API const Colour
  14814. transparentBlack, /**< ARGB = 0x00000000 */
  14815. transparentWhite, /**< ARGB = 0x00ffffff */
  14816. black, /**< ARGB = 0xff000000 */
  14817. white, /**< ARGB = 0xffffffff */
  14818. blue, /**< ARGB = 0xff0000ff */
  14819. grey, /**< ARGB = 0xff808080 */
  14820. green, /**< ARGB = 0xff008000 */
  14821. red, /**< ARGB = 0xffff0000 */
  14822. yellow, /**< ARGB = 0xffffff00 */
  14823. aliceblue, antiquewhite, aqua, aquamarine,
  14824. azure, beige, bisque, blanchedalmond,
  14825. blueviolet, brown, burlywood, cadetblue,
  14826. chartreuse, chocolate, coral, cornflowerblue,
  14827. cornsilk, crimson, cyan, darkblue,
  14828. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14829. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14830. darkorchid, darkred, darksalmon, darkseagreen,
  14831. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14832. deeppink, deepskyblue, dimgrey, dodgerblue,
  14833. firebrick, floralwhite, forestgreen, fuchsia,
  14834. gainsboro, gold, goldenrod, greenyellow,
  14835. honeydew, hotpink, indianred, indigo,
  14836. ivory, khaki, lavender, lavenderblush,
  14837. lemonchiffon, lightblue, lightcoral, lightcyan,
  14838. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14839. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14840. lightsteelblue, lightyellow, lime, limegreen,
  14841. linen, magenta, maroon, mediumaquamarine,
  14842. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14843. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14844. midnightblue, mintcream, mistyrose, navajowhite,
  14845. navy, oldlace, olive, olivedrab,
  14846. orange, orangered, orchid, palegoldenrod,
  14847. palegreen, paleturquoise, palevioletred, papayawhip,
  14848. peachpuff, peru, pink, plum,
  14849. powderblue, purple, rosybrown, royalblue,
  14850. saddlebrown, salmon, sandybrown, seagreen,
  14851. seashell, sienna, silver, skyblue,
  14852. slateblue, slategrey, snow, springgreen,
  14853. steelblue, tan, teal, thistle,
  14854. tomato, turquoise, violet, wheat,
  14855. whitesmoke, yellowgreen;
  14856. /** Attempts to look up a string in the list of known colour names, and return
  14857. the appropriate colour.
  14858. A non-case-sensitive search is made of the list of predefined colours, and
  14859. if a match is found, that colour is returned. If no match is found, the
  14860. colour passed in as the defaultColour parameter is returned.
  14861. */
  14862. static JUCE_API const Colour findColourForName (const String& colourName,
  14863. const Colour& defaultColour);
  14864. private:
  14865. // this isn't a class you should ever instantiate - it's just here for the
  14866. // static values in it.
  14867. Colours();
  14868. };
  14869. #endif // __JUCE_COLOURS_JUCEHEADER__
  14870. /********* End of inlined file: juce_Colours.h *********/
  14871. /********* Start of inlined file: juce_FillType.h *********/
  14872. #ifndef __JUCE_GRAPHICS_JUCEHEADER__x
  14873. #define __JUCE_GRAPHICS_JUCEHEADER__x
  14874. /********* Start of inlined file: juce_ColourGradient.h *********/
  14875. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  14876. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  14877. /**
  14878. Describes the layout and colours that should be used to paint a colour gradient.
  14879. @see Graphics::setGradientFill
  14880. */
  14881. class JUCE_API ColourGradient
  14882. {
  14883. public:
  14884. /** Creates a gradient object.
  14885. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  14886. colour2 should be. In between them there's a gradient.
  14887. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  14888. its centre.
  14889. The alpha transparencies of the colours are used, so note that
  14890. if you blend from transparent to a solid colour, the RGB of the transparent
  14891. colour will become visible in parts of the gradient. e.g. blending
  14892. from Colour::transparentBlack to Colours::white will produce a
  14893. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  14894. will be white all the way across.
  14895. @see ColourGradient
  14896. */
  14897. ColourGradient (const Colour& colour1,
  14898. const float x1,
  14899. const float y1,
  14900. const Colour& colour2,
  14901. const float x2,
  14902. const float y2,
  14903. const bool isRadial) throw();
  14904. /** Creates an uninitialised gradient.
  14905. If you use this constructor instead of the other one, be sure to set all the
  14906. object's public member variables before using it!
  14907. */
  14908. ColourGradient() throw();
  14909. /** Destructor */
  14910. ~ColourGradient() throw();
  14911. /** Removes any colours that have been added.
  14912. This will also remove any start and end colours, so the gradient won't work. You'll
  14913. need to add more colours with addColour().
  14914. */
  14915. void clearColours() throw();
  14916. /** Adds a colour at a point along the length of the gradient.
  14917. This allows the gradient to go through a spectrum of colours, instead of just a
  14918. start and end colour.
  14919. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  14920. of the distance along the line between the two points
  14921. at which the colour should occur.
  14922. @param colour the colour that should be used at this point
  14923. */
  14924. void addColour (const double proportionAlongGradient,
  14925. const Colour& colour) throw();
  14926. /** Multiplies the alpha value of all the colours by the given scale factor */
  14927. void multiplyOpacity (const float multiplier) throw();
  14928. /** Returns the number of colour-stops that have been added. */
  14929. int getNumColours() const throw();
  14930. /** Returns the position along the length of the gradient of the colour with this index.
  14931. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  14932. */
  14933. double getColourPosition (const int index) const throw();
  14934. /** Returns the colour that was added with a given index.
  14935. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  14936. */
  14937. const Colour getColour (const int index) const throw();
  14938. /** Returns the an interpolated colour at any position along the gradient.
  14939. @param position the position along the gradient, between 0 and 1
  14940. */
  14941. const Colour getColourAtPosition (const float position) const throw();
  14942. /** Creates a set of interpolated premultiplied ARGB values.
  14943. The caller must delete the array that is returned using juce_free().
  14944. */
  14945. PixelARGB* createLookupTable (const AffineTransform& transform, int& numEntries) const throw();
  14946. /** Returns true if all colours are opaque. */
  14947. bool isOpaque() const throw();
  14948. /** Returns true if all colours are completely transparent. */
  14949. bool isInvisible() const throw();
  14950. float x1;
  14951. float y1;
  14952. float x2;
  14953. float y2;
  14954. /** If true, the gradient should be filled circularly, centred around
  14955. (x1, y1), with (x2, y2) defining a point on the circumference.
  14956. If false, the gradient is linear between the two points.
  14957. */
  14958. bool isRadial;
  14959. juce_UseDebuggingNewOperator
  14960. private:
  14961. Array <uint32> colours;
  14962. };
  14963. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  14964. /********* End of inlined file: juce_ColourGradient.h *********/
  14965. class Image;
  14966. /**
  14967. Represents a colour or fill pattern to use for rendering paths.
  14968. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  14969. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  14970. @see Graphics::setFillType, DrawablePath::setFill
  14971. */
  14972. class JUCE_API FillType
  14973. {
  14974. public:
  14975. /** Creates a default fill type, of solid black. */
  14976. FillType() throw();
  14977. /** Creates a fill type of a solid colour.
  14978. @see setColour
  14979. */
  14980. FillType (const Colour& colour) throw();
  14981. /** Creates a gradient fill type.
  14982. @see setGradient
  14983. */
  14984. FillType (const ColourGradient& gradient) throw();
  14985. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  14986. and rotation of the pattern.
  14987. @see setTiledImage
  14988. */
  14989. FillType (const Image& image, const AffineTransform& transform) throw();
  14990. /** Creates a copy of another FillType. */
  14991. FillType (const FillType& other) throw();
  14992. /** Makes a copy of another FillType. */
  14993. const FillType& operator= (const FillType& other) throw();
  14994. /** Destructor. */
  14995. ~FillType() throw();
  14996. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  14997. bool isColour() const throw() { return gradient == 0 && image == 0; }
  14998. /** Returns true if this is a gradient fill. */
  14999. bool isGradient() const throw() { return gradient != 0; }
  15000. /** Returns true if this is a tiled image pattern fill. */
  15001. bool isTiledImage() const throw() { return image != 0; }
  15002. /** Turns this object into a solid colour fill.
  15003. If the object was an image or gradient, those fields will no longer be valid. */
  15004. void setColour (const Colour& newColour) throw();
  15005. /** Turns this object into a gradient fill. */
  15006. void setGradient (const ColourGradient& newGradient) throw();
  15007. /** Turns this object into a tiled image fill type. The transform allows you to set
  15008. the scaling, offset and rotation of the pattern.
  15009. */
  15010. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  15011. /** Changes the opacity that should be used.
  15012. If the fill is a solid colour, this just changes the opacity of that colour. For
  15013. gradients and image tiles, it changes the opacity that will be used for them.
  15014. */
  15015. void setOpacity (const float newOpacity) throw();
  15016. /** Returns the current opacity to be applied to the colour, gradient, or image.
  15017. @see setOpacity
  15018. */
  15019. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  15020. /** The solid colour being used.
  15021. If the fill type is not a solid colour, the alpha channel of this colour indicates
  15022. the opacity that should be used for the fill, and the RGB channels are ignored.
  15023. */
  15024. Colour colour;
  15025. /** Returns the gradient that should be used for filling.
  15026. This will be zero if the object is some other type of fill.
  15027. If a gradient is active, the overall opacity with which it should be applied
  15028. is indicated by the alpha channel of the colour variable.
  15029. */
  15030. ColourGradient* gradient;
  15031. /** Returns the image that should be used for tiling.
  15032. The FillType object just keeps a pointer to this image, it doesn't own it, so you have to
  15033. be careful to make sure the image doesn't get deleted while it's being used.
  15034. If an image fill is active, the overall opacity with which it should be applied
  15035. is indicated by the alpha channel of the colour variable.
  15036. */
  15037. const Image* image;
  15038. /** The transform that should be applied to the image or gradient that's being drawn.
  15039. */
  15040. AffineTransform transform;
  15041. juce_UseDebuggingNewOperator
  15042. };
  15043. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  15044. /********* End of inlined file: juce_FillType.h *********/
  15045. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  15046. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  15047. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  15048. /**
  15049. Defines the method used to postion some kind of rectangular object within
  15050. a rectangular viewport.
  15051. Although similar to Justification, this is more specific, and has some extra
  15052. options.
  15053. */
  15054. class JUCE_API RectanglePlacement
  15055. {
  15056. public:
  15057. /** Creates a RectanglePlacement object using a combination of flags. */
  15058. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  15059. /** Creates a copy of another Justification object. */
  15060. RectanglePlacement (const RectanglePlacement& other) throw();
  15061. /** Copies another Justification object. */
  15062. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  15063. /** Flag values that can be combined and used in the constructor. */
  15064. enum
  15065. {
  15066. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  15067. xLeft = 1,
  15068. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  15069. xRight = 2,
  15070. /** Indicates that the source should be placed in the centre between the left and right
  15071. sides of the available space. */
  15072. xMid = 4,
  15073. /** Indicates that the source's top edge should be aligned with the top edge of the
  15074. destination rectangle. */
  15075. yTop = 8,
  15076. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  15077. destination rectangle. */
  15078. yBottom = 16,
  15079. /** Indicates that the source should be placed in the centre between the top and bottom
  15080. sides of the available space. */
  15081. yMid = 32,
  15082. /** If this flag is set, then the source rectangle will be resized to completely fill
  15083. the destination rectangle, and all other flags are ignored.
  15084. */
  15085. stretchToFit = 64,
  15086. /** If this flag is set, then the source rectangle will be resized so that it is the
  15087. minimum size to completely fill the destination rectangle, without changing its
  15088. aspect ratio. This means that some of the source rectangle may fall outside
  15089. the destination.
  15090. If this flag is not set, the source will be given the maximum size at which none
  15091. of it falls outside the destination rectangle.
  15092. */
  15093. fillDestination = 128,
  15094. /** Indicates that the source rectangle can be reduced in size if required, but should
  15095. never be made larger than its original size.
  15096. */
  15097. onlyReduceInSize = 256,
  15098. /** Indicates that the source rectangle can be enlarged if required, but should
  15099. never be made smaller than its original size.
  15100. */
  15101. onlyIncreaseInSize = 512,
  15102. /** Indicates that the source rectangle's size should be left unchanged.
  15103. */
  15104. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  15105. /** A shorthand value that is equivalent to (xMid | yMid). */
  15106. centred = 4 + 32
  15107. };
  15108. /** Returns the raw flags that are set for this object. */
  15109. inline int getFlags() const throw() { return flags; }
  15110. /** Tests a set of flags for this object.
  15111. @returns true if any of the flags passed in are set on this object.
  15112. */
  15113. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15114. /** Adjusts the position and size of a rectangle to fit it into a space.
  15115. The source rectangle co-ordinates will be adjusted so that they fit into
  15116. the destination rectangle based on this object's flags.
  15117. */
  15118. void applyTo (double& sourceX,
  15119. double& sourceY,
  15120. double& sourceW,
  15121. double& sourceH,
  15122. const double destinationX,
  15123. const double destinationY,
  15124. const double destinationW,
  15125. const double destinationH) const throw();
  15126. /** Returns the transform that should be applied to these source co-ordinates to fit them
  15127. into the destination rectangle using the current flags.
  15128. */
  15129. const AffineTransform getTransformToFit (float sourceX,
  15130. float sourceY,
  15131. float sourceW,
  15132. float sourceH,
  15133. const float destinationX,
  15134. const float destinationY,
  15135. const float destinationW,
  15136. const float destinationH) const throw();
  15137. private:
  15138. int flags;
  15139. };
  15140. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  15141. /********* End of inlined file: juce_RectanglePlacement.h *********/
  15142. class LowLevelGraphicsContext;
  15143. class Image;
  15144. class RectangleList;
  15145. /**
  15146. A graphics context, used for drawing a component or image.
  15147. When a Component needs painting, a Graphics context is passed to its
  15148. Component::paint() method, and this you then call methods within this
  15149. object to actually draw the component's content.
  15150. A Graphics can also be created from an image, to allow drawing directly onto
  15151. that image.
  15152. @see Component::paint
  15153. */
  15154. class JUCE_API Graphics
  15155. {
  15156. public:
  15157. /** Creates a Graphics object to draw directly onto the given image.
  15158. The graphics object that is created will be set up to draw onto the image,
  15159. with the context's clipping area being the entire size of the image, and its
  15160. origin being the image's origin. To draw into a subsection of an image, use the
  15161. reduceClipRegion() and setOrigin() methods.
  15162. Obviously you shouldn't delete the image before this context is deleted.
  15163. */
  15164. Graphics (Image& imageToDrawOnto) throw();
  15165. /** Destructor. */
  15166. ~Graphics() throw();
  15167. /** Changes the current drawing colour.
  15168. This sets the colour that will now be used for drawing operations - it also
  15169. sets the opacity to that of the colour passed-in.
  15170. If a brush is being used when this method is called, the brush will be deselected,
  15171. and any subsequent drawing will be done with a solid colour brush instead.
  15172. @see setOpacity
  15173. */
  15174. void setColour (const Colour& newColour) throw();
  15175. /** Changes the opacity to use with the current colour.
  15176. If a solid colour is being used for drawing, this changes its opacity
  15177. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  15178. If a gradient is being used, this will have no effect on it.
  15179. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  15180. */
  15181. void setOpacity (const float newOpacity) throw();
  15182. /** Sets the context to use a gradient for its fill pattern.
  15183. */
  15184. void setGradientFill (const ColourGradient& gradient) throw();
  15185. /** Sets the context to use a tiled image pattern for filling.
  15186. Make sure that you don't delete this image while it's still being used by
  15187. this context!
  15188. */
  15189. void setTiledImageFill (const Image& imageToUse,
  15190. const int anchorX,
  15191. const int anchorY,
  15192. const float opacity) throw();
  15193. /** Changes the current fill settings.
  15194. @see setColour, setGradientFill, setTiledImageFill
  15195. */
  15196. void setFillType (const FillType& newFill) throw();
  15197. /** Changes the font to use for subsequent text-drawing functions.
  15198. Note there's also a setFont (float, int) method to quickly change the size and
  15199. style of the current font.
  15200. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  15201. */
  15202. void setFont (const Font& newFont) throw();
  15203. /** Changes the size and style of the currently-selected font.
  15204. This is a convenient shortcut that changes the context's current font to a
  15205. different size or style. The typeface won't be changed.
  15206. @see Font
  15207. */
  15208. void setFont (const float newFontHeight,
  15209. const int fontStyleFlags = Font::plain) throw();
  15210. /** Draws a one-line text string.
  15211. This will use the current colour (or brush) to fill the text. The font is the last
  15212. one specified by setFont().
  15213. @param text the string to draw
  15214. @param startX the position to draw the left-hand edge of the text
  15215. @param baselineY the position of the text's baseline
  15216. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  15217. */
  15218. void drawSingleLineText (const String& text,
  15219. const int startX,
  15220. const int baselineY) const throw();
  15221. /** Draws text across multiple lines.
  15222. This will break the text onto a new line where there's a new-line or
  15223. carriage-return character, or at a word-boundary when the text becomes wider
  15224. than the size specified by the maximumLineWidth parameter.
  15225. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  15226. */
  15227. void drawMultiLineText (const String& text,
  15228. const int startX,
  15229. const int baselineY,
  15230. const int maximumLineWidth) const throw();
  15231. /** Renders a string of text as a vector path.
  15232. This allows a string to be transformed with an arbitrary AffineTransform and
  15233. rendered using the current colour/brush. It's much slower than the normal text methods
  15234. but more accurate.
  15235. @see setFont
  15236. */
  15237. void drawTextAsPath (const String& text,
  15238. const AffineTransform& transform) const throw();
  15239. /** Draws a line of text within a specified rectangle.
  15240. The text will be positioned within the rectangle based on the justification
  15241. flags passed-in. If the string is too long to fit inside the rectangle, it will
  15242. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  15243. flag is true).
  15244. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  15245. */
  15246. void drawText (const String& text,
  15247. const int x,
  15248. const int y,
  15249. const int width,
  15250. const int height,
  15251. const Justification& justificationType,
  15252. const bool useEllipsesIfTooBig) const throw();
  15253. /** Tries to draw a text string inside a given space.
  15254. This does its best to make the given text readable within the specified rectangle,
  15255. so it useful for labelling things.
  15256. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  15257. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  15258. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  15259. it's been truncated.
  15260. A Justification parameter lets you specify how the text is laid out within the rectangle,
  15261. both horizontally and vertically.
  15262. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  15263. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  15264. can set this value to 1.0f.
  15265. @see GlyphArrangement::addFittedText
  15266. */
  15267. void drawFittedText (const String& text,
  15268. const int x,
  15269. const int y,
  15270. const int width,
  15271. const int height,
  15272. const Justification& justificationFlags,
  15273. const int maximumNumberOfLines,
  15274. const float minimumHorizontalScale = 0.7f) const throw();
  15275. /** Fills the context's entire clip region with the current colour or brush.
  15276. (See also the fillAll (const Colour&) method which is a quick way of filling
  15277. it with a given colour).
  15278. */
  15279. void fillAll() const throw();
  15280. /** Fills the context's entire clip region with a given colour.
  15281. This leaves the context's current colour and brush unchanged, it just
  15282. uses the specified colour temporarily.
  15283. */
  15284. void fillAll (const Colour& colourToUse) const throw();
  15285. /** Fills a rectangle with the current colour or brush.
  15286. @see drawRect, fillRoundedRectangle
  15287. */
  15288. void fillRect (int x,
  15289. int y,
  15290. int width,
  15291. int height) const throw();
  15292. /** Fills a rectangle with the current colour or brush. */
  15293. void fillRect (const Rectangle& rectangle) const throw();
  15294. /** Fills a rectangle with the current colour or brush.
  15295. This uses sub-pixel positioning so is slower than the fillRect method which
  15296. takes integer co-ordinates.
  15297. */
  15298. void fillRect (const float x,
  15299. const float y,
  15300. const float width,
  15301. const float height) const throw();
  15302. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  15303. @see drawRoundedRectangle, Path::addRoundedRectangle
  15304. */
  15305. void fillRoundedRectangle (const float x,
  15306. const float y,
  15307. const float width,
  15308. const float height,
  15309. const float cornerSize) const throw();
  15310. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  15311. @see drawRoundedRectangle, Path::addRoundedRectangle
  15312. */
  15313. void fillRoundedRectangle (const Rectangle& rectangle,
  15314. const float cornerSize) const throw();
  15315. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  15316. */
  15317. void fillCheckerBoard (int x, int y,
  15318. int width, int height,
  15319. const int checkWidth,
  15320. const int checkHeight,
  15321. const Colour& colour1,
  15322. const Colour& colour2) const throw();
  15323. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  15324. The lines are drawn inside the given rectangle, and greater line thicknesses
  15325. extend inwards.
  15326. @see fillRect
  15327. */
  15328. void drawRect (const int x,
  15329. const int y,
  15330. const int width,
  15331. const int height,
  15332. const int lineThickness = 1) const throw();
  15333. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  15334. The lines are drawn inside the given rectangle, and greater line thicknesses
  15335. extend inwards.
  15336. @see fillRect
  15337. */
  15338. void drawRect (const float x,
  15339. const float y,
  15340. const float width,
  15341. const float height,
  15342. const float lineThickness = 1.0f) const throw();
  15343. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  15344. The lines are drawn inside the given rectangle, and greater line thicknesses
  15345. extend inwards.
  15346. @see fillRect
  15347. */
  15348. void drawRect (const Rectangle& rectangle,
  15349. const int lineThickness = 1) const throw();
  15350. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  15351. @see fillRoundedRectangle, Path::addRoundedRectangle
  15352. */
  15353. void drawRoundedRectangle (const float x,
  15354. const float y,
  15355. const float width,
  15356. const float height,
  15357. const float cornerSize,
  15358. const float lineThickness) const throw();
  15359. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  15360. @see fillRoundedRectangle, Path::addRoundedRectangle
  15361. */
  15362. void drawRoundedRectangle (const Rectangle& rectangle,
  15363. const float cornerSize,
  15364. const float lineThickness) const throw();
  15365. /** Draws a 3D raised (or indented) bevel using two colours.
  15366. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  15367. extend inwards.
  15368. The top-left colour is used for the top- and left-hand edges of the
  15369. bevel; the bottom-right colour is used for the bottom- and right-hand
  15370. edges.
  15371. If useGradient is true, then the bevel fades out to make it look more curved
  15372. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  15373. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  15374. the centre edges are sharp and it fades towards the outside.
  15375. */
  15376. void drawBevel (const int x,
  15377. const int y,
  15378. const int width,
  15379. const int height,
  15380. const int bevelThickness,
  15381. const Colour& topLeftColour = Colours::white,
  15382. const Colour& bottomRightColour = Colours::black,
  15383. const bool useGradient = true,
  15384. const bool sharpEdgeOnOutside = true) const throw();
  15385. /** Draws a pixel using the current colour or brush.
  15386. */
  15387. void setPixel (int x, int y) const throw();
  15388. /** Fills an ellipse with the current colour or brush.
  15389. The ellipse is drawn to fit inside the given rectangle.
  15390. @see drawEllipse, Path::addEllipse
  15391. */
  15392. void fillEllipse (const float x,
  15393. const float y,
  15394. const float width,
  15395. const float height) const throw();
  15396. /** Draws an elliptical stroke using the current colour or brush.
  15397. @see fillEllipse, Path::addEllipse
  15398. */
  15399. void drawEllipse (const float x,
  15400. const float y,
  15401. const float width,
  15402. const float height,
  15403. const float lineThickness) const throw();
  15404. /** Draws a line between two points.
  15405. The line is 1 pixel wide and drawn with the current colour or brush.
  15406. */
  15407. void drawLine (float startX,
  15408. float startY,
  15409. float endX,
  15410. float endY) const throw();
  15411. /** Draws a line between two points with a given thickness.
  15412. @see Path::addLineSegment
  15413. */
  15414. void drawLine (const float startX,
  15415. const float startY,
  15416. const float endX,
  15417. const float endY,
  15418. const float lineThickness) const throw();
  15419. /** Draws a line between two points.
  15420. The line is 1 pixel wide and drawn with the current colour or brush.
  15421. */
  15422. void drawLine (const Line& line) const throw();
  15423. /** Draws a line between two points with a given thickness.
  15424. @see Path::addLineSegment
  15425. */
  15426. void drawLine (const Line& line,
  15427. const float lineThickness) const throw();
  15428. /** Draws a dashed line using a custom set of dash-lengths.
  15429. @param startX the line's start x co-ordinate
  15430. @param startY the line's start y co-ordinate
  15431. @param endX the line's end x co-ordinate
  15432. @param endY the line's end y co-ordinate
  15433. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  15434. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  15435. draw 6 pixels, skip 7 pixels, and then repeat.
  15436. @param numDashLengths the number of elements in the array (this must be an even number).
  15437. @param lineThickness the thickness of the line to draw
  15438. @see PathStrokeType::createDashedStroke
  15439. */
  15440. void drawDashedLine (const float startX,
  15441. const float startY,
  15442. const float endX,
  15443. const float endY,
  15444. const float* const dashLengths,
  15445. const int numDashLengths,
  15446. const float lineThickness = 1.0f) const throw();
  15447. /** Draws a vertical line of pixels at a given x position.
  15448. The x position is an integer, but the top and bottom of the line can be sub-pixel
  15449. positions, and these will be anti-aliased if necessary.
  15450. */
  15451. void drawVerticalLine (const int x, float top, float bottom) const throw();
  15452. /** Draws a horizontal line of pixels at a given y position.
  15453. The y position is an integer, but the left and right ends of the line can be sub-pixel
  15454. positions, and these will be anti-aliased if necessary.
  15455. */
  15456. void drawHorizontalLine (const int y, float left, float right) const throw();
  15457. /** Fills a path using the currently selected colour or brush.
  15458. */
  15459. void fillPath (const Path& path,
  15460. const AffineTransform& transform = AffineTransform::identity) const throw();
  15461. /** Draws a path's outline using the currently selected colour or brush.
  15462. */
  15463. void strokePath (const Path& path,
  15464. const PathStrokeType& strokeType,
  15465. const AffineTransform& transform = AffineTransform::identity) const throw();
  15466. /** Draws a line with an arrowhead.
  15467. @param startX the line's start x co-ordinate
  15468. @param startY the line's start y co-ordinate
  15469. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  15470. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  15471. @param lineThickness the thickness of the line
  15472. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  15473. @param arrowheadLength the length of the arrow head (along the length of the line)
  15474. */
  15475. void drawArrow (const float startX,
  15476. const float startY,
  15477. const float endX,
  15478. const float endY,
  15479. const float lineThickness,
  15480. const float arrowheadWidth,
  15481. const float arrowheadLength) const throw();
  15482. /** Types of rendering quality that can be specified when drawing images.
  15483. @see blendImage, Graphics::setImageResamplingQuality
  15484. */
  15485. enum ResamplingQuality
  15486. {
  15487. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  15488. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  15489. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  15490. };
  15491. /** Changes the quality that will be used when resampling images.
  15492. By default a Graphics object will be set to mediumRenderingQuality.
  15493. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  15494. */
  15495. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  15496. /** Draws an image.
  15497. This will draw the whole of an image, positioning its top-left corner at the
  15498. given co-ordinates, and keeping its size the same. This is the simplest image
  15499. drawing method - the others give more control over the scaling and clipping
  15500. of the images.
  15501. Images are composited using the context's current opacity, so if you
  15502. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  15503. (or setColour() with an opaque colour) before drawing images.
  15504. */
  15505. void drawImageAt (const Image* const imageToDraw,
  15506. const int topLeftX,
  15507. const int topLeftY,
  15508. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15509. /** Draws part of an image, rescaling it to fit in a given target region.
  15510. The specified area of the source image is rescaled and drawn to fill the
  15511. specifed destination rectangle.
  15512. Images are composited using the context's current opacity, so if you
  15513. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  15514. (or setColour() with an opaque colour) before drawing images.
  15515. @param imageToDraw the image to overlay
  15516. @param destX the left of the destination rectangle
  15517. @param destY the top of the destination rectangle
  15518. @param destWidth the width of the destination rectangle
  15519. @param destHeight the height of the destination rectangle
  15520. @param sourceX the left of the rectangle to copy from the source image
  15521. @param sourceY the top of the rectangle to copy from the source image
  15522. @param sourceWidth the width of the rectangle to copy from the source image
  15523. @param sourceHeight the height of the rectangle to copy from the source image
  15524. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  15525. the source image's alpha channel is used as a mask with
  15526. which to fill the destination using the current colour
  15527. or brush. (If the source is has no alpha channel, then
  15528. it will just fill the target with a solid rectangle)
  15529. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  15530. */
  15531. void drawImage (const Image* const imageToDraw,
  15532. int destX,
  15533. int destY,
  15534. int destWidth,
  15535. int destHeight,
  15536. int sourceX,
  15537. int sourceY,
  15538. int sourceWidth,
  15539. int sourceHeight,
  15540. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15541. /** Draws part of an image, having applied an affine transform to it.
  15542. This lets you throw the image around in some wacky ways, rotate it, shear,
  15543. scale it, etc.
  15544. A clipping subregion is specified within the source image and no pixels
  15545. outside this region will be used.
  15546. Images are composited using the context's current opacity, so if you
  15547. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  15548. (or setColour() with an opaque colour) before drawing images.
  15549. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  15550. are ignored and it is filled with the current brush, masked by its alpha channel.
  15551. @see setImageResamplingQuality, drawImage
  15552. */
  15553. void drawImageTransformed (const Image* const imageToDraw,
  15554. int sourceClipX,
  15555. int sourceClipY,
  15556. int sourceClipWidth,
  15557. int sourceClipHeight,
  15558. const AffineTransform& transform,
  15559. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15560. /** Draws an image to fit within a designated rectangle.
  15561. If the image is too big or too small for the space, it will be rescaled
  15562. to fit as nicely as it can do without affecting its aspect ratio. It will
  15563. then be placed within the target rectangle according to the justification flags
  15564. specified.
  15565. @param imageToDraw the source image to draw
  15566. @param destX top-left of the target rectangle to fit it into
  15567. @param destY top-left of the target rectangle to fit it into
  15568. @param destWidth size of the target rectangle to fit the image into
  15569. @param destHeight size of the target rectangle to fit the image into
  15570. @param placementWithinTarget this specifies how the image should be positioned
  15571. within the target rectangle - see the RectanglePlacement
  15572. class for more details about this.
  15573. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  15574. alpha channel will be used as a mask with which to
  15575. draw with the current brush or colour. This is
  15576. similar to fillAlphaMap(), and see also drawImage()
  15577. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  15578. */
  15579. void drawImageWithin (const Image* const imageToDraw,
  15580. const int destX,
  15581. const int destY,
  15582. const int destWidth,
  15583. const int destHeight,
  15584. const RectanglePlacement& placementWithinTarget,
  15585. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15586. /** Returns the position of the bounding box for the current clipping region.
  15587. @see getClipRegion, clipRegionIntersects
  15588. */
  15589. const Rectangle getClipBounds() const throw();
  15590. /** Checks whether a rectangle overlaps the context's clipping region.
  15591. If this returns false, no part of the given area can be drawn onto, so this
  15592. method can be used to optimise a component's paint() method, by letting it
  15593. avoid drawing complex objects that aren't within the region being repainted.
  15594. */
  15595. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  15596. /** Intersects the current clipping region with another region.
  15597. @returns true if the resulting clipping region is non-zero in size
  15598. @see setOrigin, clipRegionIntersects
  15599. */
  15600. bool reduceClipRegion (const int x, const int y,
  15601. const int width, const int height) throw();
  15602. /** Intersects the current clipping region with a rectangle list region.
  15603. @returns true if the resulting clipping region is non-zero in size
  15604. @see setOrigin, clipRegionIntersects
  15605. */
  15606. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  15607. /** Intersects the current clipping region with a path.
  15608. @returns true if the resulting clipping region is non-zero in size
  15609. @see reduceClipRegion
  15610. */
  15611. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity) throw();
  15612. /** Intersects the current clipping region with an image's alpha-channel.
  15613. The current clipping path is intersected with the area covered by this image's
  15614. alpha-channel, after the image has been transformed by the specified matrix.
  15615. @param image the image whose alpha-channel should be used. If the image doesn't
  15616. have an alpha-channel, it is treated as entirely opaque.
  15617. @param sourceClipRegion a subsection of the image that should be used. To use the
  15618. entire image, just pass a rectangle of bounds
  15619. (0, 0, image.getWidth(), image.getHeight()).
  15620. @param transform a matrix to apply to the image
  15621. @returns true if the resulting clipping region is non-zero in size
  15622. @see reduceClipRegion
  15623. */
  15624. bool reduceClipRegion (const Image& image, const Rectangle& sourceClipRegion,
  15625. const AffineTransform& transform) throw();
  15626. /** Excludes a rectangle to stop it being drawn into. */
  15627. void excludeClipRegion (const int x, const int y,
  15628. const int width, const int height) throw();
  15629. /** Returns true if no drawing can be done because the clip region is zero. */
  15630. bool isClipEmpty() const throw();
  15631. /** Saves the current graphics state on an internal stack.
  15632. To restore the state, use restoreState().
  15633. */
  15634. void saveState() throw();
  15635. /** Restores a graphics state that was previously saved with saveState().
  15636. */
  15637. void restoreState() throw();
  15638. /** Moves the position of the context's origin.
  15639. This changes the position that the context considers to be (0, 0) to
  15640. the specified position.
  15641. So if you call setOrigin (100, 100), then the position that was previously
  15642. referred to as (100, 100) will subsequently be considered to be (0, 0).
  15643. @see reduceClipRegion
  15644. */
  15645. void setOrigin (const int newOriginX,
  15646. const int newOriginY) throw();
  15647. /** Resets the current colour, brush, and font to default settings. */
  15648. void resetToDefaultState() throw();
  15649. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  15650. bool isVectorDevice() const throw();
  15651. juce_UseDebuggingNewOperator
  15652. /** Create a graphics that uses a given low-level renderer.
  15653. For internal use only.
  15654. NB. The context will NOT be deleted by this object when it is deleted.
  15655. */
  15656. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  15657. /** @internal */
  15658. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  15659. private:
  15660. LowLevelGraphicsContext* const context;
  15661. const bool ownsContext;
  15662. bool saveStatePending;
  15663. void saveStateIfPending() throw();
  15664. const Graphics& operator= (const Graphics& other);
  15665. Graphics (const Graphics&);
  15666. };
  15667. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  15668. /********* End of inlined file: juce_Graphics.h *********/
  15669. /**
  15670. A graphical effect filter that can be applied to components.
  15671. An ImageEffectFilter can be applied to the image that a component
  15672. paints before it hits the screen.
  15673. This is used for adding effects like shadows, blurs, etc.
  15674. @see Component::setComponentEffect
  15675. */
  15676. class JUCE_API ImageEffectFilter
  15677. {
  15678. public:
  15679. /** Overridden to render the effect.
  15680. The implementation of this method must use the image that is passed in
  15681. as its source, and should render its output to the graphics context passed in.
  15682. @param sourceImage the image that the source component has just rendered with
  15683. its paint() method. The image may or may not have an alpha
  15684. channel, depending on whether the component is opaque.
  15685. @param destContext the graphics context to use to draw the resultant image.
  15686. */
  15687. virtual void applyEffect (Image& sourceImage,
  15688. Graphics& destContext) = 0;
  15689. /** Destructor. */
  15690. virtual ~ImageEffectFilter() {}
  15691. };
  15692. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15693. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  15694. /********* Start of inlined file: juce_RectangleList.h *********/
  15695. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  15696. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  15697. /**
  15698. Maintains a set of rectangles as a complex region.
  15699. This class allows a set of rectangles to be treated as a solid shape, and can
  15700. add and remove rectangular sections of it, and simplify overlapping or
  15701. adjacent rectangles.
  15702. @see Rectangle
  15703. */
  15704. class JUCE_API RectangleList
  15705. {
  15706. public:
  15707. /** Creates an empty RectangleList */
  15708. RectangleList() throw();
  15709. /** Creates a copy of another list */
  15710. RectangleList (const RectangleList& other) throw();
  15711. /** Creates a list containing just one rectangle. */
  15712. RectangleList (const Rectangle& rect) throw();
  15713. /** Copies this list from another one. */
  15714. const RectangleList& operator= (const RectangleList& other) throw();
  15715. /** Destructor. */
  15716. ~RectangleList() throw();
  15717. /** Returns true if the region is empty. */
  15718. bool isEmpty() const throw();
  15719. /** Returns the number of rectangles in the list. */
  15720. int getNumRectangles() const throw() { return rects.size(); }
  15721. /** Returns one of the rectangles at a particular index.
  15722. @returns the rectangle at the index, or an empty rectangle if the
  15723. index is out-of-range.
  15724. */
  15725. const Rectangle getRectangle (const int index) const throw();
  15726. /** Removes all rectangles to leave an empty region. */
  15727. void clear() throw();
  15728. /** Merges a new rectangle into the list.
  15729. The rectangle being added will first be clipped to remove any parts of it
  15730. that overlap existing rectangles in the list.
  15731. */
  15732. void add (const int x, const int y,
  15733. const int w, const int h) throw();
  15734. /** Merges a new rectangle into the list.
  15735. The rectangle being added will first be clipped to remove any parts of it
  15736. that overlap existing rectangles in the list, and adjacent rectangles will be
  15737. merged into it.
  15738. */
  15739. void add (const Rectangle& rect) throw();
  15740. /** Dumbly adds a rectangle to the list without checking for overlaps.
  15741. This simply adds the rectangle to the end, it doesn't merge it or remove
  15742. any overlapping bits.
  15743. */
  15744. void addWithoutMerging (const Rectangle& rect) throw();
  15745. /** Merges another rectangle list into this one.
  15746. Any overlaps between the two lists will be clipped, so that the result is
  15747. the union of both lists.
  15748. */
  15749. void add (const RectangleList& other) throw();
  15750. /** Removes a rectangular region from the list.
  15751. Any rectangles in the list which overlap this will be clipped and subdivided
  15752. if necessary.
  15753. */
  15754. void subtract (const Rectangle& rect) throw();
  15755. /** Removes all areas in another RectangleList from this one.
  15756. Any rectangles in the list which overlap this will be clipped and subdivided
  15757. if necessary.
  15758. */
  15759. void subtract (const RectangleList& otherList) throw();
  15760. /** Removes any areas of the region that lie outside a given rectangle.
  15761. Any rectangles in the list which overlap this will be clipped and subdivided
  15762. if necessary.
  15763. Returns true if the resulting region is not empty, false if it is empty.
  15764. @see getIntersectionWith
  15765. */
  15766. bool clipTo (const Rectangle& rect) throw();
  15767. /** Removes any areas of the region that lie outside a given rectangle list.
  15768. Any rectangles in this object which overlap the specified list will be clipped
  15769. and subdivided if necessary.
  15770. Returns true if the resulting region is not empty, false if it is empty.
  15771. @see getIntersectionWith
  15772. */
  15773. bool clipTo (const RectangleList& other) throw();
  15774. /** Creates a region which is the result of clipping this one to a given rectangle.
  15775. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  15776. resulting region into the list whose reference is passed-in.
  15777. Returns true if the resulting region is not empty, false if it is empty.
  15778. @see clipTo
  15779. */
  15780. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15781. /** Swaps the contents of this and another list.
  15782. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15783. to swap them.
  15784. */
  15785. void swapWith (RectangleList& otherList) throw();
  15786. /** Checks whether the region contains a given point.
  15787. @returns true if the point lies within one of the rectangles in the list
  15788. */
  15789. bool containsPoint (const int x, const int y) const throw();
  15790. /** Checks whether the region contains the whole of a given rectangle.
  15791. @returns true all parts of the rectangle passed in lie within the region
  15792. defined by this object
  15793. @see intersectsRectangle, containsPoint
  15794. */
  15795. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15796. /** Checks whether the region contains any part of a given rectangle.
  15797. @returns true if any part of the rectangle passed in lies within the region
  15798. defined by this object
  15799. @see containsRectangle
  15800. */
  15801. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15802. /** Checks whether this region intersects any part of another one.
  15803. @see intersectsRectangle
  15804. */
  15805. bool intersects (const RectangleList& other) const throw();
  15806. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15807. const Rectangle getBounds() const throw();
  15808. /** Optimises the list into a minimum number of constituent rectangles.
  15809. This will try to combine any adjacent rectangles into larger ones where
  15810. possible, to simplify lists that might have been fragmented by repeated
  15811. add/subtract calls.
  15812. */
  15813. void consolidate() throw();
  15814. /** Adds an x and y value to all the co-ordinates. */
  15815. void offsetAll (const int dx, const int dy) throw();
  15816. /** Creates a Path object to represent this region. */
  15817. const Path toPath() const throw();
  15818. /** An iterator for accessing all the rectangles in a RectangleList. */
  15819. class Iterator
  15820. {
  15821. public:
  15822. Iterator (const RectangleList& list) throw();
  15823. ~Iterator() throw();
  15824. /** Advances to the next rectangle, and returns true if it's not finished.
  15825. Call this before using getRectangle() to find the rectangle that was returned.
  15826. */
  15827. bool next() throw();
  15828. /** Returns the current rectangle. */
  15829. const Rectangle* getRectangle() const throw() { return current; }
  15830. juce_UseDebuggingNewOperator
  15831. private:
  15832. const Rectangle* current;
  15833. const RectangleList& owner;
  15834. int index;
  15835. Iterator (const Iterator&);
  15836. const Iterator& operator= (const Iterator&);
  15837. };
  15838. juce_UseDebuggingNewOperator
  15839. private:
  15840. friend class Iterator;
  15841. Array <Rectangle> rects;
  15842. };
  15843. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15844. /********* End of inlined file: juce_RectangleList.h *********/
  15845. /********* Start of inlined file: juce_BorderSize.h *********/
  15846. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15847. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15848. /**
  15849. Specifies a set of gaps to be left around the sides of a rectangle.
  15850. This is basically the size of the spaces at the top, bottom, left and right of
  15851. a rectangle. It's used by various component classes to specify borders.
  15852. @see Rectangle
  15853. */
  15854. class JUCE_API BorderSize
  15855. {
  15856. public:
  15857. /** Creates a null border.
  15858. All sizes are left as 0.
  15859. */
  15860. BorderSize() throw();
  15861. /** Creates a copy of another border. */
  15862. BorderSize (const BorderSize& other) throw();
  15863. /** Creates a border with the given gaps. */
  15864. BorderSize (const int topGap,
  15865. const int leftGap,
  15866. const int bottomGap,
  15867. const int rightGap) throw();
  15868. /** Creates a border with the given gap on all sides. */
  15869. BorderSize (const int allGaps) throw();
  15870. /** Destructor. */
  15871. ~BorderSize() throw();
  15872. /** Returns the gap that should be left at the top of the region. */
  15873. int getTop() const throw() { return top; }
  15874. /** Returns the gap that should be left at the top of the region. */
  15875. int getLeft() const throw() { return left; }
  15876. /** Returns the gap that should be left at the top of the region. */
  15877. int getBottom() const throw() { return bottom; }
  15878. /** Returns the gap that should be left at the top of the region. */
  15879. int getRight() const throw() { return right; }
  15880. /** Returns the sum of the top and bottom gaps. */
  15881. int getTopAndBottom() const throw() { return top + bottom; }
  15882. /** Returns the sum of the left and right gaps. */
  15883. int getLeftAndRight() const throw() { return left + right; }
  15884. /** Changes the top gap. */
  15885. void setTop (const int newTopGap) throw();
  15886. /** Changes the left gap. */
  15887. void setLeft (const int newLeftGap) throw();
  15888. /** Changes the bottom gap. */
  15889. void setBottom (const int newBottomGap) throw();
  15890. /** Changes the right gap. */
  15891. void setRight (const int newRightGap) throw();
  15892. /** Returns a rectangle with these borders removed from it. */
  15893. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15894. /** Removes this border from a given rectangle. */
  15895. void subtractFrom (Rectangle& rectangle) const throw();
  15896. /** Returns a rectangle with these borders added around it. */
  15897. const Rectangle addedTo (const Rectangle& original) const throw();
  15898. /** Adds this border around a given rectangle. */
  15899. void addTo (Rectangle& original) const throw();
  15900. bool operator== (const BorderSize& other) const throw();
  15901. bool operator!= (const BorderSize& other) const throw();
  15902. juce_UseDebuggingNewOperator
  15903. private:
  15904. int top, left, bottom, right;
  15905. };
  15906. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15907. /********* End of inlined file: juce_BorderSize.h *********/
  15908. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15909. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15910. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15911. class Component;
  15912. class Graphics;
  15913. /********* Start of inlined file: juce_MessageListener.h *********/
  15914. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15915. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15916. /********* Start of inlined file: juce_Message.h *********/
  15917. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15918. #define __JUCE_MESSAGE_JUCEHEADER__
  15919. class MessageListener;
  15920. class MessageManager;
  15921. /** The base class for objects that can be delivered to a MessageListener.
  15922. The simplest Message object contains a few integer and pointer parameters
  15923. that the user can set, and this is enough for a lot of purposes. For passing more
  15924. complex data, subclasses of Message can also be used.
  15925. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15926. */
  15927. class JUCE_API Message
  15928. {
  15929. public:
  15930. /** Creates an uninitialised message.
  15931. The class's variables will also be left uninitialised.
  15932. */
  15933. Message() throw();
  15934. /** Creates a message object, filling in the member variables.
  15935. The corresponding public member variables will be set from the parameters
  15936. passed in.
  15937. */
  15938. Message (const int intParameter1,
  15939. const int intParameter2,
  15940. const int intParameter3,
  15941. void* const pointerParameter) throw();
  15942. /** Destructor. */
  15943. virtual ~Message() throw();
  15944. // These values can be used for carrying simple data that the application needs to
  15945. // pass around. For more complex messages, just create a subclass.
  15946. int intParameter1; /**< user-defined integer value. */
  15947. int intParameter2; /**< user-defined integer value. */
  15948. int intParameter3; /**< user-defined integer value. */
  15949. void* pointerParameter; /**< user-defined pointer value. */
  15950. juce_UseDebuggingNewOperator
  15951. private:
  15952. friend class MessageListener;
  15953. friend class MessageManager;
  15954. MessageListener* messageRecipient;
  15955. Message (const Message&);
  15956. const Message& operator= (const Message&);
  15957. };
  15958. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15959. /********* End of inlined file: juce_Message.h *********/
  15960. /**
  15961. MessageListener subclasses can post and receive Message objects.
  15962. @see Message, MessageManager, ActionListener, ChangeListener
  15963. */
  15964. class JUCE_API MessageListener
  15965. {
  15966. protected:
  15967. /** Creates a MessageListener. */
  15968. MessageListener() throw();
  15969. public:
  15970. /** Destructor.
  15971. When a MessageListener is deleted, it removes itself from a global list
  15972. of registered listeners, so that the isValidMessageListener() method
  15973. will no longer return true.
  15974. */
  15975. virtual ~MessageListener();
  15976. /** This is the callback method that receives incoming messages.
  15977. This is called by the MessageManager from its dispatch loop.
  15978. @see postMessage
  15979. */
  15980. virtual void handleMessage (const Message& message) = 0;
  15981. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15982. later on.
  15983. This method can be called safely by any thread.
  15984. @param message the message object to send - this will be deleted
  15985. automatically by the message queue, so don't keep any
  15986. references to it after calling this method.
  15987. @see handleMessage
  15988. */
  15989. void postMessage (Message* const message) const throw();
  15990. /** Checks whether this MessageListener has been deleted.
  15991. Although not foolproof, this method is safe to call on dangling or null
  15992. pointers. A list of active MessageListeners is kept internally, so this
  15993. checks whether the object is on this list or not.
  15994. Note that it's possible to get a false-positive here, if an object is
  15995. deleted and another is subsequently created that happens to be at the
  15996. exact same memory location, but I can't think of a good way of avoiding
  15997. this.
  15998. */
  15999. bool isValidMessageListener() const throw();
  16000. };
  16001. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  16002. /********* End of inlined file: juce_MessageListener.h *********/
  16003. class ComponentBoundsConstrainer;
  16004. class ComponentDeletionWatcher;
  16005. /**
  16006. The base class for window objects that wrap a component as a real operating
  16007. system object.
  16008. This is an abstract base class - the platform specific code contains default
  16009. implementations of it that create and manage windows.
  16010. @see Component::createNewPeer
  16011. */
  16012. class JUCE_API ComponentPeer : public MessageListener
  16013. {
  16014. public:
  16015. /** A combination of these flags is passed to the ComponentPeer constructor. */
  16016. enum StyleFlags
  16017. {
  16018. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  16019. entry on the taskbar (ignored on MacOSX) */
  16020. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  16021. tooltip, etc. */
  16022. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  16023. through it (may not be possible on some platforms). */
  16024. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  16025. title bar and frame\. if not specified, the window will be
  16026. borderless. */
  16027. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  16028. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  16029. minimise button on it. */
  16030. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  16031. maximise button on it. */
  16032. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  16033. close button on it. */
  16034. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  16035. not be possible on all platforms). */
  16036. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  16037. do its own repainting, but only to repaint when the
  16038. performAnyPendingRepaintsNow() method is called. */
  16039. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  16040. be used for things like plugin windows, to stop them interfering
  16041. with the host's shortcut keys */
  16042. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  16043. };
  16044. /** Creates a peer.
  16045. The component is the one that we intend to represent, and the style flags are
  16046. a combination of the values in the StyleFlags enum
  16047. */
  16048. ComponentPeer (Component* const component,
  16049. const int styleFlags) throw();
  16050. /** Destructor. */
  16051. virtual ~ComponentPeer();
  16052. /** Returns the component being represented by this peer. */
  16053. Component* getComponent() const throw() { return component; }
  16054. /** Returns the set of style flags that were set when the window was created.
  16055. @see Component::addToDesktop
  16056. */
  16057. int getStyleFlags() const throw() { return styleFlags; }
  16058. /** Returns the raw handle to whatever kind of window is being used.
  16059. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  16060. but rememeber there's no guarantees what you'll get back.
  16061. */
  16062. virtual void* getNativeHandle() const = 0;
  16063. /** Shows or hides the window. */
  16064. virtual void setVisible (bool shouldBeVisible) = 0;
  16065. /** Changes the title of the window. */
  16066. virtual void setTitle (const String& title) = 0;
  16067. /** Moves the window without changing its size.
  16068. If the native window is contained in another window, then the co-ordinates are
  16069. relative to the parent window's origin, not the screen origin.
  16070. This should result in a callback to handleMovedOrResized().
  16071. */
  16072. virtual void setPosition (int x, int y) = 0;
  16073. /** Resizes the window without changing its position.
  16074. This should result in a callback to handleMovedOrResized().
  16075. */
  16076. virtual void setSize (int w, int h) = 0;
  16077. /** Moves and resizes the window.
  16078. If the native window is contained in another window, then the co-ordinates are
  16079. relative to the parent window's origin, not the screen origin.
  16080. This should result in a callback to handleMovedOrResized().
  16081. */
  16082. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  16083. /** Returns the current position and size of the window.
  16084. If the native window is contained in another window, then the co-ordinates are
  16085. relative to the parent window's origin, not the screen origin.
  16086. */
  16087. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  16088. /** Returns the x-position of this window, relative to the screen's origin. */
  16089. virtual int getScreenX() const = 0;
  16090. /** Returns the y-position of this window, relative to the screen's origin. */
  16091. virtual int getScreenY() const = 0;
  16092. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  16093. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  16094. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  16095. virtual void globalPositionToRelative (int& x, int& y) = 0;
  16096. /** Minimises the window. */
  16097. virtual void setMinimised (bool shouldBeMinimised) = 0;
  16098. /** True if the window is currently minimised. */
  16099. virtual bool isMinimised() const = 0;
  16100. /** Enable/disable fullscreen mode for the window. */
  16101. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  16102. /** True if the window is currently full-screen. */
  16103. virtual bool isFullScreen() const = 0;
  16104. /** Sets the size to restore to if fullscreen mode is turned off. */
  16105. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  16106. /** Returns the size to restore to if fullscreen mode is turned off. */
  16107. const Rectangle& getNonFullScreenBounds() const throw();
  16108. /** Attempts to change the icon associated with this window.
  16109. */
  16110. virtual void setIcon (const Image& newIcon) = 0;
  16111. /** Sets a constrainer to use if the peer can resize itself.
  16112. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  16113. */
  16114. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  16115. /** Returns the current constrainer, if one has been set. */
  16116. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  16117. /** Checks if a point is in the window.
  16118. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  16119. is false, then this returns false if the point is actually inside a child of this
  16120. window.
  16121. */
  16122. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  16123. /** Returns the size of the window frame that's around this window.
  16124. Whether or not the window has a normal window frame depends on the flags
  16125. that were set when the window was created by Component::addToDesktop()
  16126. */
  16127. virtual const BorderSize getFrameSize() const = 0;
  16128. /** This is called when the window's bounds change.
  16129. A peer implementation must call this when the window is moved and resized, so that
  16130. this method can pass the message on to the component.
  16131. */
  16132. void handleMovedOrResized();
  16133. /** This is called if the screen resolution changes.
  16134. A peer implementation must call this if the monitor arrangement changes or the available
  16135. screen size changes.
  16136. */
  16137. void handleScreenSizeChange();
  16138. /** This is called to repaint the component into the given context. */
  16139. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  16140. /** Sets this window to either be always-on-top or normal.
  16141. Some kinds of window might not be able to do this, so should return false.
  16142. */
  16143. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  16144. /** Brings the window to the top, optionally also giving it focus. */
  16145. virtual void toFront (bool makeActive) = 0;
  16146. /** Moves the window to be just behind another one. */
  16147. virtual void toBehind (ComponentPeer* other) = 0;
  16148. /** Called when the window is brought to the front, either by the OS or by a call
  16149. to toFront().
  16150. */
  16151. void handleBroughtToFront();
  16152. /** True if the window has the keyboard focus. */
  16153. virtual bool isFocused() const = 0;
  16154. /** Tries to give the window keyboard focus. */
  16155. virtual void grabFocus() = 0;
  16156. /** Tells the window that text input may be required at the given position.
  16157. This may cause things like a virtual on-screen keyboard to appear, depending
  16158. on the OS.
  16159. */
  16160. virtual void textInputRequired (int x, int y) = 0;
  16161. /** Called when the window gains keyboard focus. */
  16162. void handleFocusGain();
  16163. /** Called when the window loses keyboard focus. */
  16164. void handleFocusLoss();
  16165. Component* getLastFocusedSubcomponent() const throw();
  16166. /** Called when a key is pressed.
  16167. For keycode info, see the KeyPress class.
  16168. Returns true if the keystroke was used.
  16169. */
  16170. bool handleKeyPress (const int keyCode,
  16171. const juce_wchar textCharacter);
  16172. /** Called whenever a key is pressed or released.
  16173. Returns true if the keystroke was used.
  16174. */
  16175. bool handleKeyUpOrDown (const bool isKeyDown);
  16176. /** Called whenever a modifier key is pressed or released. */
  16177. void handleModifierKeysChange();
  16178. /** Invalidates a region of the window to be repainted asynchronously. */
  16179. virtual void repaint (int x, int y, int w, int h) = 0;
  16180. /** This can be called (from the message thread) to cause the immediate redrawing
  16181. of any areas of this window that need repainting.
  16182. You shouldn't ever really need to use this, it's mainly for special purposes
  16183. like supporting audio plugins where the host's event loop is out of our control.
  16184. */
  16185. virtual void performAnyPendingRepaintsNow() = 0;
  16186. void handleMouseEnter (int x, int y, const int64 time);
  16187. void handleMouseMove (int x, int y, const int64 time);
  16188. void handleMouseDown (int x, int y, const int64 time);
  16189. void handleMouseDrag (int x, int y, const int64 time);
  16190. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16191. void handleMouseExit (int x, int y, const int64 time);
  16192. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  16193. /** Causes a mouse-move callback to be made asynchronously. */
  16194. void sendFakeMouseMove() throw();
  16195. void handleUserClosingWindow();
  16196. void handleFileDragMove (const StringArray& files, int x, int y);
  16197. void handleFileDragExit (const StringArray& files);
  16198. void handleFileDragDrop (const StringArray& files, int x, int y);
  16199. /** Resets the masking region.
  16200. The subclass should call this every time it's about to call the handlePaint
  16201. method.
  16202. @see addMaskedRegion
  16203. */
  16204. void clearMaskedRegion() throw();
  16205. /** Adds a rectangle to the set of areas not to paint over.
  16206. A component can call this on its peer during its paint() method, to signal
  16207. that the painting code should ignore a given region. The reason
  16208. for this is to stop embedded windows (such as OpenGL) getting painted over.
  16209. The masked region is cleared each time before a paint happens, so a component
  16210. will have to make sure it calls this every time it's painted.
  16211. */
  16212. void addMaskedRegion (int x, int y, int w, int h) throw();
  16213. /** Returns the number of currently-active peers.
  16214. @see getPeer
  16215. */
  16216. static int getNumPeers() throw();
  16217. /** Returns one of the currently-active peers.
  16218. @see getNumPeers
  16219. */
  16220. static ComponentPeer* getPeer (const int index) throw();
  16221. /** Checks if this peer object is valid.
  16222. @see getNumPeers
  16223. */
  16224. static bool isValidPeer (const ComponentPeer* const peer) throw();
  16225. static void bringModalComponentToFront();
  16226. virtual const StringArray getAvailableRenderingEngines() throw();
  16227. virtual int getCurrentRenderingEngine() throw();
  16228. virtual void setCurrentRenderingEngine (int index) throw();
  16229. juce_UseDebuggingNewOperator
  16230. protected:
  16231. Component* const component;
  16232. const int styleFlags;
  16233. RectangleList maskedRegion;
  16234. Rectangle lastNonFullscreenBounds;
  16235. uint32 lastPaintTime;
  16236. ComponentBoundsConstrainer* constrainer;
  16237. static void updateCurrentModifiers() throw();
  16238. /** @internal */
  16239. void handleMessage (const Message& message);
  16240. private:
  16241. Component* lastFocusedComponent;
  16242. ComponentDeletionWatcher* dragAndDropTargetComponent;
  16243. Component* lastDragAndDropCompUnderMouse;
  16244. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  16245. friend class Component;
  16246. static ComponentPeer* getPeerFor (const Component* const component) throw();
  16247. void setLastDragDropTarget (Component* comp);
  16248. ComponentPeer (const ComponentPeer&);
  16249. const ComponentPeer& operator= (const ComponentPeer&);
  16250. };
  16251. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  16252. /********* End of inlined file: juce_ComponentPeer.h *********/
  16253. class LookAndFeel;
  16254. /**
  16255. The base class for all JUCE user-interface objects.
  16256. */
  16257. class JUCE_API Component : public MouseListener,
  16258. protected MessageListener
  16259. {
  16260. public:
  16261. /** Creates a component.
  16262. To get it to actually appear, you'll also need to:
  16263. - Either add it to a parent component or use the addToDesktop() method to
  16264. make it a desktop window
  16265. - Set its size and position to something sensible
  16266. - Use setVisible() to make it visible
  16267. And for it to serve any useful purpose, you'll need to write a
  16268. subclass of Component or use one of the other types of component from
  16269. the library.
  16270. */
  16271. Component() throw();
  16272. /** Destructor.
  16273. Note that when a component is deleted, any child components it might
  16274. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  16275. */
  16276. virtual ~Component();
  16277. /** Creates a component, setting its name at the same time.
  16278. @see getName, setName
  16279. */
  16280. Component (const String& componentName) throw();
  16281. /** Returns the name of this component.
  16282. @see setName
  16283. */
  16284. const String& getName() const throw() { return componentName_; }
  16285. /** Sets the name of this component.
  16286. When the name changes, all registered ComponentListeners will receive a
  16287. ComponentListener::componentNameChanged() callback.
  16288. @see getName
  16289. */
  16290. virtual void setName (const String& newName);
  16291. /** Checks whether this Component object has been deleted.
  16292. This will check whether this object is still a valid component, or whether
  16293. it's been deleted.
  16294. It's safe to call this on null or dangling pointers, but note that there is a
  16295. small risk if another new (but different) component has been created at the
  16296. same memory address which this one occupied, this methods can return a
  16297. false positive.
  16298. */
  16299. bool isValidComponent() const throw();
  16300. /** Makes the component visible or invisible.
  16301. This method will show or hide the component.
  16302. Note that components default to being non-visible when first created.
  16303. Also note that visible components won't be seen unless all their parent components
  16304. are also visible.
  16305. This method will call visibilityChanged() and also componentVisibilityChanged()
  16306. for any component listeners that are interested in this component.
  16307. @param shouldBeVisible whether to show or hide the component
  16308. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  16309. */
  16310. virtual void setVisible (bool shouldBeVisible);
  16311. /** Tests whether the component is visible or not.
  16312. this doesn't necessarily tell you whether this comp is actually on the screen
  16313. because this depends on whether all the parent components are also visible - use
  16314. isShowing() to find this out.
  16315. @see isShowing, setVisible
  16316. */
  16317. bool isVisible() const throw() { return flags.visibleFlag; }
  16318. /** Called when this component's visiblility changes.
  16319. @see setVisible, isVisible
  16320. */
  16321. virtual void visibilityChanged();
  16322. /** Tests whether this component and all its parents are visible.
  16323. @returns true only if this component and all its parents are visible.
  16324. @see isVisible
  16325. */
  16326. bool isShowing() const throw();
  16327. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  16328. To do this, this function will cunningly:
  16329. - take a snapshot of the component as it currently looks
  16330. - call setVisible(false) on the component
  16331. - replace it with a special component that will continue drawing the
  16332. snapshot, animating it and gradually making it more transparent
  16333. - when it's gone, the special component will also be deleted
  16334. As soon as this method returns, the component can be safely removed and deleted
  16335. leaving the proxy to do the fade-out, so it's even ok to call this in a
  16336. component's destructor.
  16337. Passing non-zero x and y values will cause the ghostly component image to
  16338. also whizz off by this distance while fading out. If the scale factor is
  16339. not 1.0, it will also zoom from the component's current size to this new size.
  16340. One thing to be careful about is that the parent component must be able to cope
  16341. with this unknown component type being added to it.
  16342. */
  16343. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  16344. const int deltaXToMove = 0,
  16345. const int deltaYToMove = 0,
  16346. const float scaleFactorAtEnd = 1.0f);
  16347. /** Makes this component appear as a window on the desktop.
  16348. Note that before calling this, you should make sure that the component's opacity is
  16349. set correctly using setOpaque(). If the component is non-opaque, the windowing
  16350. system will try to create a special transparent window for it, which will generally take
  16351. a lot more CPU to operate (and might not even be possible on some platforms).
  16352. If the component is inside a parent component at the time this method is called, it
  16353. will be first be removed from that parent. Likewise if a component on the desktop
  16354. is subsequently added to another component, it'll be removed from the desktop.
  16355. @param windowStyleFlags a combination of the flags specified in the
  16356. ComponentPeer::StyleFlags enum, which define the
  16357. window's characteristics.
  16358. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  16359. in which the juce component should place itself. On Windows,
  16360. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  16361. supported on all platforms, and best left as 0 unless you know
  16362. what you're doing
  16363. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  16364. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  16365. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  16366. */
  16367. virtual void addToDesktop (int windowStyleFlags,
  16368. void* nativeWindowToAttachTo = 0);
  16369. /** If the component is currently showing on the desktop, this will hide it.
  16370. You can also use setVisible() to hide a desktop window temporarily, but
  16371. removeFromDesktop() will free any system resources that are being used up.
  16372. @see addToDesktop, isOnDesktop
  16373. */
  16374. void removeFromDesktop();
  16375. /** Returns true if this component is currently showing on the desktop.
  16376. @see addToDesktop, removeFromDesktop
  16377. */
  16378. bool isOnDesktop() const throw();
  16379. /** Returns the heavyweight window that contains this component.
  16380. If this component is itself on the desktop, this will return the window
  16381. object that it is using. Otherwise, it will return the window of
  16382. its top-level parent component.
  16383. This may return 0 if there isn't a desktop component.
  16384. @see addToDesktop, isOnDesktop
  16385. */
  16386. ComponentPeer* getPeer() const throw();
  16387. /** For components on the desktop, this is called if the system wants to close the window.
  16388. This is a signal that either the user or the system wants the window to close. The
  16389. default implementation of this method will trigger an assertion to warn you that your
  16390. component should do something about it, but you can override this to ignore the event
  16391. if you want.
  16392. */
  16393. virtual void userTriedToCloseWindow();
  16394. /** Called for a desktop component which has just been minimised or un-minimised.
  16395. This will only be called for components on the desktop.
  16396. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  16397. */
  16398. virtual void minimisationStateChanged (bool isNowMinimised);
  16399. /** Brings the component to the front of its siblings.
  16400. If some of the component's siblings have had their 'always-on-top' flag set,
  16401. then they will still be kept in front of this one (unless of course this
  16402. one is also 'always-on-top').
  16403. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  16404. to the component (see grabKeyboardFocus() for more details)
  16405. @see toBack, toBehind, setAlwaysOnTop
  16406. */
  16407. void toFront (const bool shouldAlsoGainFocus);
  16408. /** Changes this component's z-order to be at the back of all its siblings.
  16409. If the component is set to be 'always-on-top', it will only be moved to the
  16410. back of the other other 'always-on-top' components.
  16411. @see toFront, toBehind, setAlwaysOnTop
  16412. */
  16413. void toBack();
  16414. /** Changes this component's z-order so that it's just behind another component.
  16415. @see toFront, toBack
  16416. */
  16417. void toBehind (Component* const other);
  16418. /** Sets whether the component should always be kept at the front of its siblings.
  16419. @see isAlwaysOnTop
  16420. */
  16421. void setAlwaysOnTop (const bool shouldStayOnTop);
  16422. /** Returns true if this component is set to always stay in front of its siblings.
  16423. @see setAlwaysOnTop
  16424. */
  16425. bool isAlwaysOnTop() const throw();
  16426. /** Returns the x co-ordinate of the component's left edge.
  16427. This is a distance in pixels from the left edge of the component's parent.
  16428. @see getScreenX
  16429. */
  16430. inline int getX() const throw() { return bounds_.getX(); }
  16431. /** Returns the y co-ordinate of the top of this component.
  16432. This is a distance in pixels from the top edge of the component's parent.
  16433. @see getScreenY
  16434. */
  16435. inline int getY() const throw() { return bounds_.getY(); }
  16436. /** Returns the component's width in pixels. */
  16437. inline int getWidth() const throw() { return bounds_.getWidth(); }
  16438. /** Returns the component's height in pixels. */
  16439. inline int getHeight() const throw() { return bounds_.getHeight(); }
  16440. /** Returns the x co-ordinate of the component's right-hand edge.
  16441. This is a distance in pixels from the left edge of the component's parent.
  16442. */
  16443. int getRight() const throw() { return bounds_.getRight(); }
  16444. /** Returns the y co-ordinate of the bottom edge of this component.
  16445. This is a distance in pixels from the top edge of the component's parent.
  16446. */
  16447. int getBottom() const throw() { return bounds_.getBottom(); }
  16448. /** Returns this component's bounding box.
  16449. The rectangle returned is relative to the top-left of the component's parent.
  16450. */
  16451. const Rectangle& getBounds() const throw() { return bounds_; }
  16452. /** Returns the region of this component that's not obscured by other, opaque components.
  16453. The RectangleList that is returned represents the area of this component
  16454. which isn't covered by opaque child components.
  16455. If includeSiblings is true, it will also take into account any siblings
  16456. that may be overlapping the component.
  16457. */
  16458. void getVisibleArea (RectangleList& result,
  16459. const bool includeSiblings) const;
  16460. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  16461. @see getX, relativePositionToGlobal
  16462. */
  16463. int getScreenX() const throw();
  16464. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  16465. @see getY, relativePositionToGlobal
  16466. */
  16467. int getScreenY() const throw();
  16468. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  16469. @see globalPositionToRelative, relativePositionToOtherComponent
  16470. */
  16471. void relativePositionToGlobal (int& x, int& y) const throw();
  16472. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  16473. @see relativePositionToGlobal, relativePositionToOtherComponent
  16474. */
  16475. void globalPositionToRelative (int& x, int& y) const throw();
  16476. /** Converts a position relative to this component's top-left into a position
  16477. relative to another component's top-left.
  16478. @see relativePositionToGlobal, globalPositionToRelative
  16479. */
  16480. void relativePositionToOtherComponent (const Component* const targetComponent,
  16481. int& x, int& y) const throw();
  16482. /** Moves the component to a new position.
  16483. Changes the component's top-left position (without changing its size).
  16484. The position is relative to the top-left of the component's parent.
  16485. If the component actually moves, this method will make a synchronous call to moved().
  16486. @see setBounds, ComponentListener::componentMovedOrResized
  16487. */
  16488. void setTopLeftPosition (const int x, const int y);
  16489. /** Moves the component to a new position.
  16490. Changes the position of the component's top-right corner (keeping it the same size).
  16491. The position is relative to the top-left of the component's parent.
  16492. If the component actually moves, this method will make a synchronous call to moved().
  16493. */
  16494. void setTopRightPosition (const int x, const int y);
  16495. /** Changes the size of the component.
  16496. A synchronous call to resized() will be occur if the size actually changes.
  16497. */
  16498. void setSize (const int newWidth, const int newHeight);
  16499. /** Changes the component's position and size.
  16500. The co-ordinates are relative to the top-left of the component's parent, or relative
  16501. to the origin of the screen is the component is on the desktop.
  16502. If this method changes the component's top-left position, it will make a synchronous
  16503. call to moved(). If it changes the size, it will also make a call to resized().
  16504. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  16505. */
  16506. void setBounds (int x, int y, int width, int height);
  16507. /** Changes the component's position and size.
  16508. @see setBounds
  16509. */
  16510. void setBounds (const Rectangle& newBounds);
  16511. /** Changes the component's position and size in terms of fractions of its parent's size.
  16512. The values are factors of the parent's size, so for example
  16513. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  16514. width and height of the parent, with its top-left position 20% of
  16515. the way across and down the parent.
  16516. */
  16517. void setBoundsRelative (const float proportionalX, const float proportionalY,
  16518. const float proportionalWidth, const float proportionalHeight);
  16519. /** Changes the component's position and size based on the amount of space to leave around it.
  16520. This will position the component within its parent, leaving the specified number of
  16521. pixels around each edge.
  16522. */
  16523. void setBoundsInset (const BorderSize& borders);
  16524. /** Positions the component within a given rectangle, keeping its proportions
  16525. unchanged.
  16526. If onlyReduceInSize is false, the component will be resized to fill as much of the
  16527. rectangle as possible without changing its aspect ratio (the component's
  16528. current size is used to determine its aspect ratio, so a zero-size component
  16529. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  16530. too big to fit inside the rectangle.
  16531. It will then be positioned within the rectangle according to the justification flags
  16532. specified.
  16533. */
  16534. void setBoundsToFit (int x, int y, int width, int height,
  16535. const Justification& justification,
  16536. const bool onlyReduceInSize);
  16537. /** Changes the position of the component's centre.
  16538. Leaves the component's size unchanged, but sets the position of its centre
  16539. relative to its parent's top-left.
  16540. */
  16541. void setCentrePosition (const int x, const int y);
  16542. /** Changes the position of the component's centre.
  16543. Leaves the position unchanged, but positions its centre relative to its
  16544. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  16545. its parent.
  16546. */
  16547. void setCentreRelative (const float x, const float y);
  16548. /** Changes the component's size and centres it within its parent.
  16549. After changing the size, the component will be moved so that it's
  16550. centred within its parent.
  16551. */
  16552. void centreWithSize (const int width, const int height);
  16553. /** Returns a proportion of the component's width.
  16554. This is a handy equivalent of (getWidth() * proportion).
  16555. */
  16556. int proportionOfWidth (const float proportion) const throw();
  16557. /** Returns a proportion of the component's height.
  16558. This is a handy equivalent of (getHeight() * proportion).
  16559. */
  16560. int proportionOfHeight (const float proportion) const throw();
  16561. /** Returns the width of the component's parent.
  16562. If the component has no parent (i.e. if it's on the desktop), this will return
  16563. the width of the screen.
  16564. */
  16565. int getParentWidth() const throw();
  16566. /** Returns the height of the component's parent.
  16567. If the component has no parent (i.e. if it's on the desktop), this will return
  16568. the height of the screen.
  16569. */
  16570. int getParentHeight() const throw();
  16571. /** Returns the screen co-ordinates of the monitor that contains this component.
  16572. If there's only one monitor, this will return its size - if there are multiple
  16573. monitors, it will return the area of the monitor that contains the component's
  16574. centre.
  16575. */
  16576. const Rectangle getParentMonitorArea() const throw();
  16577. /** Returns the number of child components that this component contains.
  16578. @see getChildComponent, getIndexOfChildComponent
  16579. */
  16580. int getNumChildComponents() const throw();
  16581. /** Returns one of this component's child components, by it index.
  16582. The component with index 0 is at the back of the z-order, the one at the
  16583. front will have index (getNumChildComponents() - 1).
  16584. If the index is out-of-range, this will return a null pointer.
  16585. @see getNumChildComponents, getIndexOfChildComponent
  16586. */
  16587. Component* getChildComponent (const int index) const throw();
  16588. /** Returns the index of this component in the list of child components.
  16589. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  16590. values are further towards the front.
  16591. Returns -1 if the component passed-in is not a child of this component.
  16592. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  16593. */
  16594. int getIndexOfChildComponent (const Component* const child) const throw();
  16595. /** Adds a child component to this one.
  16596. @param child the new component to add. If the component passed-in is already
  16597. the child of another component, it'll first be removed from that.
  16598. @param zOrder The index in the child-list at which this component should be inserted.
  16599. A value of -1 will insert it in front of the others, 0 is the back.
  16600. @see removeChildComponent, addAndMakeVisible, getChild,
  16601. ComponentListener::componentChildrenChanged
  16602. */
  16603. void addChildComponent (Component* const child,
  16604. int zOrder = -1);
  16605. /** Adds a child component to this one, and also makes the child visible if it isn't.
  16606. Quite a useful function, this is just the same as calling addChildComponent()
  16607. followed by setVisible (true) on the child.
  16608. */
  16609. void addAndMakeVisible (Component* const child,
  16610. int zOrder = -1);
  16611. /** Removes one of this component's child-components.
  16612. If the child passed-in isn't actually a child of this component (either because
  16613. it's invalid or is the child of a different parent), then nothing is done.
  16614. Note that removing a child will not delete it!
  16615. @see addChildComponent, ComponentListener::componentChildrenChanged
  16616. */
  16617. void removeChildComponent (Component* const childToRemove);
  16618. /** Removes one of this component's child-components by index.
  16619. This will return a pointer to the component that was removed, or null if
  16620. the index was out-of-range.
  16621. Note that removing a child will not delete it!
  16622. @see addChildComponent, ComponentListener::componentChildrenChanged
  16623. */
  16624. Component* removeChildComponent (const int childIndexToRemove);
  16625. /** Removes all this component's children.
  16626. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  16627. */
  16628. void removeAllChildren();
  16629. /** Removes all this component's children, and deletes them.
  16630. @see removeAllChildren
  16631. */
  16632. void deleteAllChildren();
  16633. /** Returns the component which this component is inside.
  16634. If this is the highest-level component or hasn't yet been added to
  16635. a parent, this will return null.
  16636. */
  16637. Component* getParentComponent() const throw() { return parentComponent_; }
  16638. /** Searches the parent components for a component of a specified class.
  16639. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  16640. component that can be dynamically cast to a MyComp, or will return 0 if none
  16641. of the parents are suitable.
  16642. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  16643. */
  16644. template <class TargetClass>
  16645. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  16646. {
  16647. (void) dummyParameter;
  16648. Component* p = parentComponent_;
  16649. while (p != 0)
  16650. {
  16651. TargetClass* target = dynamic_cast <TargetClass*> (p);
  16652. if (target != 0)
  16653. return target;
  16654. p = p->parentComponent_;
  16655. }
  16656. return 0;
  16657. }
  16658. /** Returns the highest-level component which contains this one or its parents.
  16659. This will search upwards in the parent-hierarchy from this component, until it
  16660. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  16661. not yet added to a parent), and will return that.
  16662. */
  16663. Component* getTopLevelComponent() const throw();
  16664. /** Checks whether a component is anywhere inside this component or its children.
  16665. This will recursively check through this components children to see if the
  16666. given component is anywhere inside.
  16667. */
  16668. bool isParentOf (const Component* possibleChild) const throw();
  16669. /** Called to indicate that the component's parents have changed.
  16670. When a component is added or removed from its parent, this method will
  16671. be called on all of its children (recursively - so all children of its
  16672. children will also be called as well).
  16673. Subclasses can override this if they need to react to this in some way.
  16674. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  16675. */
  16676. virtual void parentHierarchyChanged();
  16677. /** Subclasses can use this callback to be told when children are added or removed.
  16678. @see parentHierarchyChanged
  16679. */
  16680. virtual void childrenChanged();
  16681. /** Tests whether a given point inside the component.
  16682. Overriding this method allows you to create components which only intercept
  16683. mouse-clicks within a user-defined area.
  16684. This is called to find out whether a particular x, y co-ordinate is
  16685. considered to be inside the component or not, and is used by methods such
  16686. as contains() and getComponentAt() to work out which component
  16687. the mouse is clicked on.
  16688. Components with custom shapes will probably want to override it to perform
  16689. some more complex hit-testing.
  16690. The default implementation of this method returns either true or false,
  16691. depending on the value that was set by calling setInterceptsMouseClicks() (true
  16692. is the default return value).
  16693. Note that the hit-test region is not related to the opacity with which
  16694. areas of a component are painted.
  16695. Applications should never call hitTest() directly - instead use the
  16696. contains() method, because this will also test for occlusion by the
  16697. component's parent.
  16698. Note that for components on the desktop, this method will be ignored, because it's
  16699. not always possible to implement this behaviour on all platforms.
  16700. @param x the x co-ordinate to test, relative to the left hand edge of this
  16701. component. This value is guaranteed to be greater than or equal to
  16702. zero, and less than the component's width
  16703. @param y the y co-ordinate to test, relative to the top edge of this
  16704. component. This value is guaranteed to be greater than or equal to
  16705. zero, and less than the component's height
  16706. @returns true if the click is considered to be inside the component
  16707. @see setInterceptsMouseClicks, contains
  16708. */
  16709. virtual bool hitTest (int x, int y);
  16710. /** Changes the default return value for the hitTest() method.
  16711. Setting this to false is an easy way to make a component pass its mouse-clicks
  16712. through to the components behind it.
  16713. When a component is created, the default setting for this is true.
  16714. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  16715. return false (or true for child components if allowClicksOnChildComponents
  16716. is true)
  16717. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  16718. components can be clicked on as normal but clicks on this component pass
  16719. straight through; if this is false and allowClicksOnThisComponent
  16720. is false, then neither this component nor any child components can
  16721. be clicked on
  16722. @see hitTest, getInterceptsMouseClicks
  16723. */
  16724. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  16725. const bool allowClicksOnChildComponents) throw();
  16726. /** Retrieves the current state of the mouse-click interception flags.
  16727. On return, the two parameters are set to the state used in the last call to
  16728. setInterceptsMouseClicks().
  16729. @see setInterceptsMouseClicks
  16730. */
  16731. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  16732. bool& allowsClicksOnChildComponents) const throw();
  16733. /** Returns true if a given point lies within this component or one of its children.
  16734. Never override this method! Use hitTest to create custom hit regions.
  16735. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16736. @param y the y co-ordinate to test, relative to this component's top edge.
  16737. @returns true if the point is within the component's hit-test area, but only if
  16738. that part of the component isn't clipped by its parent component. Note
  16739. that this won't take into account any overlapping sibling components
  16740. which might be in the way - for that, see reallyContains()
  16741. @see hitTest, reallyContains, getComponentAt
  16742. */
  16743. virtual bool contains (int x, int y);
  16744. /** Returns true if a given point lies in this component, taking any overlapping
  16745. siblings into account.
  16746. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16747. @param y the y co-ordinate to test, relative to this component's top edge.
  16748. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  16749. component, this determines the value that will
  16750. be returned.
  16751. @see contains, getComponentAt
  16752. */
  16753. bool reallyContains (int x, int y,
  16754. const bool returnTrueIfWithinAChild);
  16755. /** Returns the component at a certain point within this one.
  16756. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16757. @param y the y co-ordinate to test, relative to this component's top edge.
  16758. @returns the component that is at this position - which may be 0, this component,
  16759. or one of its children. Note that overlapping siblings that might actually
  16760. be in the way are not taken into account by this method - to account for these,
  16761. instead call getComponentAt on the top-level parent of this component.
  16762. @see hitTest, contains, reallyContains
  16763. */
  16764. Component* getComponentAt (const int x, const int y);
  16765. /** Marks the whole component as needing to be redrawn.
  16766. Calling this will not do any repainting immediately, but will mark the component
  16767. as 'dirty'. At some point in the near future the operating system will send a paint
  16768. message, which will redraw all the dirty regions of all components.
  16769. There's no guarantee about how soon after calling repaint() the redraw will actually
  16770. happen, and other queued events may be delivered before a redraw is done.
  16771. If the setBufferedToImage() method has been used to cause this component
  16772. to use a buffer, the repaint() call will invalidate the component's buffer.
  16773. To redraw just a subsection of the component rather than the whole thing,
  16774. use the repaint (int, int, int, int) method.
  16775. @see paint
  16776. */
  16777. void repaint() throw();
  16778. /** Marks a subsection of this component as needing to be redrawn.
  16779. Calling this will not do any repainting immediately, but will mark the given region
  16780. of the component as 'dirty'. At some point in the near future the operating system
  16781. will send a paint message, which will redraw all the dirty regions of all components.
  16782. There's no guarantee about how soon after calling repaint() the redraw will actually
  16783. happen, and other queued events may be delivered before a redraw is done.
  16784. The region that is passed in will be clipped to keep it within the bounds of this
  16785. component.
  16786. @see repaint()
  16787. */
  16788. void repaint (const int x, const int y,
  16789. const int width, const int height) throw();
  16790. /** Makes the component use an internal buffer to optimise its redrawing.
  16791. Setting this flag to true will cause the component to allocate an
  16792. internal buffer into which it paints itself, so that when asked to
  16793. redraw itself, it can use this buffer rather than actually calling the
  16794. paint() method.
  16795. The buffer is kept until the repaint() method is called directly on
  16796. this component (or until it is resized), when the image is invalidated
  16797. and then redrawn the next time the component is painted.
  16798. Note that only the drawing that happens within the component's paint()
  16799. method is drawn into the buffer, it's child components are not buffered, and
  16800. nor is the paintOverChildren() method.
  16801. @see repaint, paint, createComponentSnapshot
  16802. */
  16803. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16804. /** Generates a snapshot of part of this component.
  16805. This will return a new Image, the size of the rectangle specified,
  16806. containing a snapshot of the specified area of the component and all
  16807. its children.
  16808. The image may or may not have an alpha-channel, depending on whether the
  16809. image is opaque or not.
  16810. If the clipImageToComponentBounds parameter is true and the area is greater than
  16811. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16812. then parts of the component beyond its bounds can be drawn.
  16813. The caller is responsible for deleting the image that is returned.
  16814. @see paintEntireComponent
  16815. */
  16816. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16817. const bool clipImageToComponentBounds = true);
  16818. /** Draws this component and all its subcomponents onto the specified graphics
  16819. context.
  16820. You should very rarely have to use this method, it's simply there in case you need
  16821. to draw a component with a custom graphics context for some reason, e.g. for
  16822. creating a snapshot of the component.
  16823. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16824. on its children in order to render the entire tree.
  16825. The graphics context may be left in an undefined state after this method returns,
  16826. so you may need to reset it if you're going to use it again.
  16827. */
  16828. void paintEntireComponent (Graphics& context);
  16829. /** Adds an effect filter to alter the component's appearance.
  16830. When a component has an effect filter set, then this is applied to the
  16831. results of its paint() method. There are a few preset effects, such as
  16832. a drop-shadow or glow, but they can be user-defined as well.
  16833. The effect that is passed in will not be deleted by the component - the
  16834. caller must take care of deleting it.
  16835. To remove an effect from a component, pass a null pointer in as the parameter.
  16836. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16837. */
  16838. void setComponentEffect (ImageEffectFilter* const newEffect);
  16839. /** Returns the current component effect.
  16840. @see setComponentEffect
  16841. */
  16842. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16843. /** Finds the appropriate look-and-feel to use for this component.
  16844. If the component hasn't had a look-and-feel explicitly set, this will
  16845. return the parent's look-and-feel, or just the default one if there's no
  16846. parent.
  16847. @see setLookAndFeel, lookAndFeelChanged
  16848. */
  16849. LookAndFeel& getLookAndFeel() const throw();
  16850. /** Sets the look and feel to use for this component.
  16851. This will also change the look and feel for any child components that haven't
  16852. had their look set explicitly.
  16853. The object passed in will not be deleted by the component, so it's the caller's
  16854. responsibility to manage it. It may be used at any time until this component
  16855. has been deleted.
  16856. Calling this method will also invoke the sendLookAndFeelChange() method.
  16857. @see getLookAndFeel, lookAndFeelChanged
  16858. */
  16859. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16860. /** Called to let the component react to a change in the look-and-feel setting.
  16861. When the look-and-feel is changed for a component, this will be called in
  16862. all its child components, recursively.
  16863. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16864. an application uses a LookAndFeel class that might have changed internally.
  16865. @see sendLookAndFeelChange, getLookAndFeel
  16866. */
  16867. virtual void lookAndFeelChanged();
  16868. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16869. This will recurse through the children and their children, calling lookAndFeelChanged()
  16870. on them all.
  16871. @see lookAndFeelChanged
  16872. */
  16873. void sendLookAndFeelChange();
  16874. /** Indicates whether any parts of the component might be transparent.
  16875. Components that always paint all of their contents with solid colour and
  16876. thus completely cover any components behind them should use this method
  16877. to tell the repaint system that they are opaque.
  16878. This information is used to optimise drawing, because it means that
  16879. objects underneath opaque windows don't need to be painted.
  16880. By default, components are considered transparent, unless this is used to
  16881. make it otherwise.
  16882. @see isOpaque, getVisibleArea
  16883. */
  16884. void setOpaque (const bool shouldBeOpaque) throw();
  16885. /** Returns true if no parts of this component are transparent.
  16886. @returns the value that was set by setOpaque, (the default being false)
  16887. @see setOpaque
  16888. */
  16889. bool isOpaque() const throw();
  16890. /** Indicates whether the component should be brought to the front when clicked.
  16891. Setting this flag to true will cause the component to be brought to the front
  16892. when the mouse is clicked somewhere inside it or its child components.
  16893. Note that a top-level desktop window might still be brought to the front by the
  16894. operating system when it's clicked, depending on how the OS works.
  16895. By default this is set to false.
  16896. @see setMouseClickGrabsKeyboardFocus
  16897. */
  16898. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16899. /** Indicates whether the component should be brought to the front when clicked-on.
  16900. @see setBroughtToFrontOnMouseClick
  16901. */
  16902. bool isBroughtToFrontOnMouseClick() const throw();
  16903. // Keyboard focus methods
  16904. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16905. By default components aren't actually interested in gaining the
  16906. focus, but this method can be used to turn this on.
  16907. See the grabKeyboardFocus() method for details about the way a component
  16908. is chosen to receive the focus.
  16909. @see grabKeyboardFocus, getWantsKeyboardFocus
  16910. */
  16911. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16912. /** Returns true if the component is interested in getting keyboard focus.
  16913. This returns the flag set by setWantsKeyboardFocus(). The default
  16914. setting is false.
  16915. @see setWantsKeyboardFocus
  16916. */
  16917. bool getWantsKeyboardFocus() const throw();
  16918. /** Chooses whether a click on this component automatically grabs the focus.
  16919. By default this is set to true, but you might want a component which can
  16920. be focused, but where you don't want the user to be able to affect it directly
  16921. by clicking.
  16922. */
  16923. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16924. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16925. See setMouseClickGrabsKeyboardFocus() for more info.
  16926. */
  16927. bool getMouseClickGrabsKeyboardFocus() const throw();
  16928. /** Tries to give keyboard focus to this component.
  16929. When the user clicks on a component or its grabKeyboardFocus()
  16930. method is called, the following procedure is used to work out which
  16931. component should get it:
  16932. - if the component that was clicked on actually wants focus (as indicated
  16933. by calling getWantsKeyboardFocus), it gets it.
  16934. - if the component itself doesn't want focus, it will try to pass it
  16935. on to whichever of its children is the default component, as determined by
  16936. KeyboardFocusTraverser::getDefaultComponent()
  16937. - if none of its children want focus at all, it will pass it up to its
  16938. parent instead, unless it's a top-level component without a parent,
  16939. in which case it just takes the focus itself.
  16940. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16941. getCurrentlyFocusedComponent, focusGained, focusLost,
  16942. keyPressed, keyStateChanged
  16943. */
  16944. void grabKeyboardFocus();
  16945. /** Returns true if this component currently has the keyboard focus.
  16946. @param trueIfChildIsFocused if this is true, then the method returns true if
  16947. either this component or any of its children (recursively)
  16948. have the focus. If false, the method only returns true if
  16949. this component has the focus.
  16950. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16951. focusGained, focusLost
  16952. */
  16953. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16954. /** Returns the component that currently has the keyboard focus.
  16955. @returns the focused component, or null if nothing is focused.
  16956. */
  16957. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16958. /** Tries to move the keyboard focus to one of this component's siblings.
  16959. This will try to move focus to either the next or previous component. (This
  16960. is the method that is used when shifting focus by pressing the tab key).
  16961. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16962. @param moveToNext if true, the focus will move forwards; if false, it will
  16963. move backwards
  16964. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16965. */
  16966. void moveKeyboardFocusToSibling (const bool moveToNext);
  16967. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16968. which focus should be passed from this component.
  16969. The default implementation of this method will return a default
  16970. KeyboardFocusTraverser if this component is a focus container (as determined
  16971. by the setFocusContainer() method). If the component isn't a focus
  16972. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16973. If you overrride this to return a custom KeyboardFocusTraverser, then
  16974. this component and all its sub-components will use the new object to
  16975. make their focusing decisions.
  16976. The method should return a new object, which the caller is required to
  16977. delete when no longer needed.
  16978. */
  16979. virtual KeyboardFocusTraverser* createFocusTraverser();
  16980. /** Returns the focus order of this component, if one has been specified.
  16981. By default components don't have a focus order - in that case, this
  16982. will return 0. Lower numbers indicate that the component will be
  16983. earlier in the focus traversal order.
  16984. To change the order, call setExplicitFocusOrder().
  16985. The focus order may be used by the KeyboardFocusTraverser class as part of
  16986. its algorithm for deciding the order in which components should be traversed.
  16987. See the KeyboardFocusTraverser class for more details on this.
  16988. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16989. */
  16990. int getExplicitFocusOrder() const throw();
  16991. /** Sets the index used in determining the order in which focusable components
  16992. should be traversed.
  16993. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16994. that traversal should use other factors, like the component's position.
  16995. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16996. */
  16997. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16998. /** Indicates whether this component is a parent for components that can have
  16999. their focus traversed.
  17000. This flag is used by the default implementation of the createFocusTraverser()
  17001. method, which uses the flag to find the first parent component (of the currently
  17002. focused one) which wants to be a focus container.
  17003. So using this method to set the flag to 'true' causes this component to
  17004. act as the top level within which focus is passed around.
  17005. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  17006. */
  17007. void setFocusContainer (const bool isFocusContainer) throw();
  17008. /** Returns true if this component has been marked as a focus container.
  17009. See setFocusContainer() for more details.
  17010. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  17011. */
  17012. bool isFocusContainer() const throw();
  17013. /** Returns true if the component (and all its parents) are enabled.
  17014. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  17015. what difference this makes to the component depends on the type. E.g. buttons
  17016. and sliders will choose to draw themselves differently, etc.
  17017. Note that if one of this component's parents is disabled, this will always
  17018. return false, even if this component itself is enabled.
  17019. @see setEnabled, enablementChanged
  17020. */
  17021. bool isEnabled() const throw();
  17022. /** Enables or disables this component.
  17023. Disabling a component will also cause all of its child components to become
  17024. disabled.
  17025. Similarly, enabling a component which is inside a disabled parent
  17026. component won't make any difference until the parent is re-enabled.
  17027. @see isEnabled, enablementChanged
  17028. */
  17029. void setEnabled (const bool shouldBeEnabled);
  17030. /** Callback to indicate that this component has been enabled or disabled.
  17031. This can be triggered by one of the component's parent components
  17032. being enabled or disabled, as well as changes to the component itself.
  17033. The default implementation of this method does nothing; your class may
  17034. wish to repaint itself or something when this happens.
  17035. @see setEnabled, isEnabled
  17036. */
  17037. virtual void enablementChanged();
  17038. /** Changes the mouse cursor shape to use when the mouse is over this component.
  17039. Note that the cursor set by this method can be overridden by the getMouseCursor
  17040. method.
  17041. @see MouseCursor
  17042. */
  17043. void setMouseCursor (const MouseCursor& cursorType) throw();
  17044. /** Returns the mouse cursor shape to use when the mouse is over this component.
  17045. The default implementation will return the cursor that was set by setCursor()
  17046. but can be overridden for more specialised purposes, e.g. returning different
  17047. cursors depending on the mouse position.
  17048. @see MouseCursor
  17049. */
  17050. virtual const MouseCursor getMouseCursor();
  17051. /** Forces the current mouse cursor to be updated.
  17052. If you're overriding the getMouseCursor() method to control which cursor is
  17053. displayed, then this will only be checked each time the user moves the mouse. So
  17054. if you want to force the system to check that the cursor being displayed is
  17055. up-to-date (even if the mouse is just sitting there), call this method.
  17056. This isn't needed if you're only using setMouseCursor().
  17057. */
  17058. void updateMouseCursor() const throw();
  17059. /** Components can override this method to draw their content.
  17060. The paint() method gets called when a region of a component needs redrawing,
  17061. either because the component's repaint() method has been called, or because
  17062. something has happened on the screen that means a section of a window needs
  17063. to be redrawn.
  17064. Any child components will draw themselves over whatever this method draws. If
  17065. you need to paint over the top of your child components, you can also implement
  17066. the paintOverChildren() method to do this.
  17067. If you want to cause a component to redraw itself, this is done asynchronously -
  17068. calling the repaint() method marks a region of the component as "dirty", and the
  17069. paint() method will automatically be called sometime later, by the message thread,
  17070. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  17071. you never redraw something synchronously.
  17072. You should never need to call this method directly - to take a snapshot of the
  17073. component you could use createComponentSnapshot() or paintEntireComponent().
  17074. @param g the graphics context that must be used to do the drawing operations.
  17075. @see repaint, paintOverChildren, Graphics
  17076. */
  17077. virtual void paint (Graphics& g);
  17078. /** Components can override this method to draw over the top of their children.
  17079. For most drawing operations, it's better to use the normal paint() method,
  17080. but if you need to overlay something on top of the children, this can be
  17081. used.
  17082. @see paint, Graphics
  17083. */
  17084. virtual void paintOverChildren (Graphics& g);
  17085. /** Called when the mouse moves inside this component.
  17086. If the mouse button isn't pressed and the mouse moves over a component,
  17087. this will be called to let the component react to this.
  17088. A component will always get a mouseEnter callback before a mouseMove.
  17089. @param e details about the position and status of the mouse event
  17090. @see mouseEnter, mouseExit, mouseDrag, contains
  17091. */
  17092. virtual void mouseMove (const MouseEvent& e);
  17093. /** Called when the mouse first enters this component.
  17094. If the mouse button isn't pressed and the mouse moves into a component,
  17095. this will be called to let the component react to this.
  17096. When the mouse button is pressed and held down while being moved in
  17097. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17098. mouseDrag messages are sent to the component that the mouse was originally
  17099. clicked on, until the button is released.
  17100. If you're writing a component that needs to repaint itself when the mouse
  17101. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  17102. method.
  17103. @param e details about the position and status of the mouse event
  17104. @see mouseExit, mouseDrag, mouseMove, contains
  17105. */
  17106. virtual void mouseEnter (const MouseEvent& e);
  17107. /** Called when the mouse moves out of this component.
  17108. This will be called when the mouse moves off the edge of this
  17109. component.
  17110. If the mouse button was pressed, and it was then dragged off the
  17111. edge of the component and released, then this callback will happen
  17112. when the button is released, after the mouseUp callback.
  17113. If you're writing a component that needs to repaint itself when the mouse
  17114. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  17115. method.
  17116. @param e details about the position and status of the mouse event
  17117. @see mouseEnter, mouseDrag, mouseMove, contains
  17118. */
  17119. virtual void mouseExit (const MouseEvent& e);
  17120. /** Called when a mouse button is pressed while it's over this component.
  17121. The MouseEvent object passed in contains lots of methods for finding out
  17122. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17123. were held down at the time.
  17124. Once a button is held down, the mouseDrag method will be called when the
  17125. mouse moves, until the button is released.
  17126. @param e details about the position and status of the mouse event
  17127. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  17128. */
  17129. virtual void mouseDown (const MouseEvent& e);
  17130. /** Called when the mouse is moved while a button is held down.
  17131. When a mouse button is pressed inside a component, that component
  17132. receives mouseDrag callbacks each time the mouse moves, even if the
  17133. mouse strays outside the component's bounds.
  17134. If you want to be able to drag things off the edge of a component
  17135. and have the component scroll when you get to the edges, the
  17136. beginDragAutoRepeat() method might be useful.
  17137. @param e details about the position and status of the mouse event
  17138. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  17139. */
  17140. virtual void mouseDrag (const MouseEvent& e);
  17141. /** Called when a mouse button is released.
  17142. A mouseUp callback is sent to the component in which a button was pressed
  17143. even if the mouse is actually over a different component when the
  17144. button is released.
  17145. The MouseEvent object passed in contains lots of methods for finding out
  17146. which buttons were down just before they were released.
  17147. @param e details about the position and status of the mouse event
  17148. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  17149. */
  17150. virtual void mouseUp (const MouseEvent& e);
  17151. /** Called when a mouse button has been double-clicked in this component.
  17152. The MouseEvent object passed in contains lots of methods for finding out
  17153. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17154. were held down at the time.
  17155. For altering the time limit used to detect double-clicks,
  17156. see MouseEvent::setDoubleClickTimeout.
  17157. @param e details about the position and status of the mouse event
  17158. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  17159. MouseEvent::getDoubleClickTimeout
  17160. */
  17161. virtual void mouseDoubleClick (const MouseEvent& e);
  17162. /** Called when the mouse-wheel is moved.
  17163. This callback is sent to the component that the mouse is over when the
  17164. wheel is moved.
  17165. If not overridden, the component will forward this message to its parent, so
  17166. that parent components can collect mouse-wheel messages that happen to
  17167. child components which aren't interested in them.
  17168. @param e details about the position and status of the mouse event
  17169. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  17170. value means the wheel has been pushed to the right, negative means it
  17171. was pushed to the left
  17172. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  17173. value means the wheel has been pushed upwards, negative means it
  17174. was pushed downwards
  17175. */
  17176. virtual void mouseWheelMove (const MouseEvent& e,
  17177. float wheelIncrementX,
  17178. float wheelIncrementY);
  17179. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  17180. next mouse-drag operation.
  17181. This allows you to make sure that mouseDrag() events sent continuously, even
  17182. when the mouse isn't moving. This can be useful for things like auto-scrolling
  17183. components when the mouse is near an edge.
  17184. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  17185. minimum interval between consecutive mouse drag callbacks. The callbacks
  17186. will continue until the mouse is released, and then the interval will be reset,
  17187. so you need to make sure it's called every time you begin a drag event. If it
  17188. is called when the mouse isn't actually being pressed, it will apply to the next
  17189. mouse-drag operation that happens.
  17190. Passing an interval of 0 or less will cancel the auto-repeat.
  17191. @see mouseDrag
  17192. */
  17193. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  17194. /** Causes automatic repaints when the mouse enters or exits this component.
  17195. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  17196. on the component, it will trigger a repaint.
  17197. This is handy for things like buttons that need to draw themselves differently when
  17198. the mouse moves over them, and it avoids having to override all the different mouse
  17199. callbacks and call repaint().
  17200. @see mouseEnter, mouseExit, mouseDown, mouseUp
  17201. */
  17202. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  17203. /** Registers a listener to be told when mouse events occur in this component.
  17204. If you need to get informed about mouse events in a component but can't or
  17205. don't want to override its methods, you can attach any number of listeners
  17206. to the component, and these will get told about the events in addition to
  17207. the component's own callbacks being called.
  17208. Note that a MouseListener can also be attached to more than one component.
  17209. @param newListener the listener to register
  17210. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  17211. for events that happen to any child component
  17212. within this component, including deeply-nested
  17213. child components. If false, it will only be
  17214. told about events that this component handles.
  17215. @see MouseListener, removeMouseListener
  17216. */
  17217. void addMouseListener (MouseListener* const newListener,
  17218. const bool wantsEventsForAllNestedChildComponents) throw();
  17219. /** Deregisters a mouse listener.
  17220. @see addMouseListener, MouseListener
  17221. */
  17222. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  17223. /** Adds a listener that wants to hear about keypresses that this component receives.
  17224. The listeners that are registered with a component are called by its keyPressed() or
  17225. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  17226. If you add an object as a key listener, be careful to remove it when the object
  17227. is deleted, or the component will be left with a dangling pointer.
  17228. @see keyPressed, keyStateChanged, removeKeyListener
  17229. */
  17230. void addKeyListener (KeyListener* const newListener) throw();
  17231. /** Removes a previously-registered key listener.
  17232. @see addKeyListener
  17233. */
  17234. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  17235. /** Called when a key is pressed.
  17236. When a key is pressed, the component that has the keyboard focus will have this
  17237. method called. Remember that a component will only be given the focus if its
  17238. setWantsKeyboardFocus() method has been used to enable this.
  17239. If your implementation returns true, the event will be consumed and not passed
  17240. on to any other listeners. If it returns false, the key will be passed to any
  17241. KeyListeners that have been registered with this component. As soon as one of these
  17242. returns true, the process will stop, but if they all return false, the event will
  17243. be passed upwards to this component's parent, and so on.
  17244. The default implementation of this method does nothing and returns false.
  17245. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  17246. */
  17247. virtual bool keyPressed (const KeyPress& key);
  17248. /** Called when a key is pressed or released.
  17249. Whenever a key on the keyboard is pressed or released (including modifier keys
  17250. like shift and ctrl), this method will be called on the component that currently
  17251. has the keyboard focus. Remember that a component will only be given the focus if
  17252. its setWantsKeyboardFocus() method has been used to enable this.
  17253. If your implementation returns true, the event will be consumed and not passed
  17254. on to any other listeners. If it returns false, then any KeyListeners that have
  17255. been registered with this component will have their keyStateChanged methods called.
  17256. As soon as one of these returns true, the process will stop, but if they all return
  17257. false, the event will be passed upwards to this component's parent, and so on.
  17258. The default implementation of this method does nothing and returns false.
  17259. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  17260. method.
  17261. @param isKeyDown true if a key has been pressed; false if it has been released
  17262. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  17263. */
  17264. virtual bool keyStateChanged (const bool isKeyDown);
  17265. /** Called when a modifier key is pressed or released.
  17266. Whenever the shift, control, alt or command keys are pressed or released,
  17267. this method will be called on the component that currently has the keyboard focus.
  17268. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  17269. method has been used to enable this.
  17270. The default implementation of this method actually calls its parent's modifierKeysChanged
  17271. method, so that focused components which aren't interested in this will give their
  17272. parents a chance to act on the event instead.
  17273. @see keyStateChanged, ModifierKeys
  17274. */
  17275. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  17276. /** Enumeration used by the focusChanged() and focusLost() methods. */
  17277. enum FocusChangeType
  17278. {
  17279. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  17280. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  17281. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  17282. };
  17283. /** Called to indicate that this component has just acquired the keyboard focus.
  17284. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  17285. */
  17286. virtual void focusGained (FocusChangeType cause);
  17287. /** Called to indicate that this component has just lost the keyboard focus.
  17288. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  17289. */
  17290. virtual void focusLost (FocusChangeType cause);
  17291. /** Called to indicate that one of this component's children has been focused or unfocused.
  17292. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  17293. changed. It happens when focus moves from one of this component's children (at any depth)
  17294. to a component that isn't contained in this one, (or vice-versa).
  17295. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  17296. */
  17297. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  17298. /** Returns true if the mouse is currently over this component.
  17299. If the mouse isn't over the component, this will return false, even if the
  17300. mouse is currently being dragged - so you can use this in your mouseDrag
  17301. method to find out whether it's really over the component or not.
  17302. Note that when the mouse button is being held down, then the only component
  17303. for which this method will return true is the one that was originally
  17304. clicked on.
  17305. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  17306. */
  17307. bool isMouseOver() const throw();
  17308. /** Returns true if the mouse button is currently held down in this component.
  17309. Note that this is a test to see whether the mouse is being pressed in this
  17310. component, so it'll return false if called on component A when the mouse
  17311. is actually being dragged in component B.
  17312. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  17313. */
  17314. bool isMouseButtonDown() const throw();
  17315. /** True if the mouse is over this component, or if it's being dragged in this component.
  17316. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  17317. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  17318. */
  17319. bool isMouseOverOrDragging() const throw();
  17320. /** Returns true if a mouse button is currently down.
  17321. Unlike isMouseButtonDown, this will test the current state of the
  17322. buttons without regard to which component (if any) it has been
  17323. pressed in.
  17324. @see isMouseButtonDown, ModifierKeys
  17325. */
  17326. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  17327. /** Returns the mouse's current position, relative to this component.
  17328. The co-ordinates are relative to the component's top-left corner.
  17329. */
  17330. void getMouseXYRelative (int& x, int& y) const throw();
  17331. /** Returns the component that's currently underneath the mouse.
  17332. @returns the component or 0 if there isn't one.
  17333. @see contains, getComponentAt
  17334. */
  17335. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  17336. /** Allows the mouse to move beyond the edges of the screen.
  17337. Calling this method when the mouse button is currently pressed inside this component
  17338. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  17339. the edges of the screen.
  17340. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  17341. can be used for things like custom slider controls or dragging objects around, where
  17342. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  17343. The unbounded mode is automatically turned off when the mouse button is released, or
  17344. it can be turned off explicitly by calling this method again.
  17345. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  17346. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  17347. hidden; if true, it will only be hidden when it
  17348. is moved beyond the edge of the screen
  17349. */
  17350. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  17351. bool keepCursorVisibleUntilOffscreen = false) throw();
  17352. /** Called when this component's size has been changed.
  17353. A component can implement this method to do things such as laying out its
  17354. child components when its width or height changes.
  17355. The method is called synchronously as a result of the setBounds or setSize
  17356. methods, so repeatedly changing a components size will repeatedly call its
  17357. resized method (unlike things like repainting, where multiple calls to repaint
  17358. are coalesced together).
  17359. If the component is a top-level window on the desktop, its size could also
  17360. be changed by operating-system factors beyond the application's control.
  17361. @see moved, setSize
  17362. */
  17363. virtual void resized();
  17364. /** Called when this component's position has been changed.
  17365. This is called when the position relative to its parent changes, not when
  17366. its absolute position on the screen changes (so it won't be called for
  17367. all child components when a parent component is moved).
  17368. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  17369. or any of the other repositioning methods, and like resized(), it will be
  17370. called each time those methods are called.
  17371. If the component is a top-level window on the desktop, its position could also
  17372. be changed by operating-system factors beyond the application's control.
  17373. @see resized, setBounds
  17374. */
  17375. virtual void moved();
  17376. /** Called when one of this component's children is moved or resized.
  17377. If the parent wants to know about changes to its immediate children (not
  17378. to children of its children), this is the method to override.
  17379. @see moved, resized, parentSizeChanged
  17380. */
  17381. virtual void childBoundsChanged (Component* child);
  17382. /** Called when this component's immediate parent has been resized.
  17383. If the component is a top-level window, this indicates that the screen size
  17384. has changed.
  17385. @see childBoundsChanged, moved, resized
  17386. */
  17387. virtual void parentSizeChanged();
  17388. /** Called when this component has been moved to the front of its siblings.
  17389. The component may have been brought to the front by the toFront() method, or
  17390. by the operating system if it's a top-level window.
  17391. @see toFront
  17392. */
  17393. virtual void broughtToFront();
  17394. /** Adds a listener to be told about changes to the component hierarchy or position.
  17395. Component listeners get called when this component's size, position or children
  17396. change - see the ComponentListener class for more details.
  17397. @param newListener the listener to register - if this is already registered, it
  17398. will be ignored.
  17399. @see ComponentListener, removeComponentListener
  17400. */
  17401. void addComponentListener (ComponentListener* const newListener) throw();
  17402. /** Removes a component listener.
  17403. @see addComponentListener
  17404. */
  17405. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  17406. /** Dispatches a numbered message to this component.
  17407. This is a quick and cheap way of allowing simple asynchronous messages to
  17408. be sent to components. It's also safe, because if the component that you
  17409. send the message to is a null or dangling pointer, this won't cause an error.
  17410. The command ID is later delivered to the component's handleCommandMessage() method by
  17411. the application's message queue.
  17412. @see handleCommandMessage
  17413. */
  17414. void postCommandMessage (const int commandId) throw();
  17415. /** Called to handle a command that was sent by postCommandMessage().
  17416. This is called by the message thread when a command message arrives, and
  17417. the component can override this method to process it in any way it needs to.
  17418. @see postCommandMessage
  17419. */
  17420. virtual void handleCommandMessage (int commandId);
  17421. /** Runs a component modally, waiting until the loop terminates.
  17422. This method first makes the component visible, brings it to the front and
  17423. gives it the keyboard focus.
  17424. It then runs a loop, dispatching messages from the system message queue, but
  17425. blocking all mouse or keyboard messages from reaching any components other
  17426. than this one and its children.
  17427. This loop continues until the component's exitModalState() method is called (or
  17428. the component is deleted), and then this method returns, returning the value
  17429. passed into exitModalState().
  17430. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  17431. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  17432. */
  17433. int runModalLoop();
  17434. /** Puts the component into a modal state.
  17435. This makes the component modal, so that messages are blocked from reaching
  17436. any components other than this one and its children, but unlike runModalLoop(),
  17437. this method returns immediately.
  17438. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  17439. get the focus, which is usually what you'll want it to do. If not, it will leave
  17440. the focus unchanged.
  17441. @see exitModalState, runModalLoop
  17442. */
  17443. void enterModalState (const bool takeKeyboardFocus = true);
  17444. /** Ends a component's modal state.
  17445. If this component is currently modal, this will turn of its modalness, and return
  17446. a value to the runModalLoop() method that might have be running its modal loop.
  17447. @see runModalLoop, enterModalState, isCurrentlyModal
  17448. */
  17449. void exitModalState (const int returnValue);
  17450. /** Returns true if this component is the modal one.
  17451. It's possible to have nested modal components, e.g. a pop-up dialog box
  17452. that launches another pop-up, but this will only return true for
  17453. the one at the top of the stack.
  17454. @see getCurrentlyModalComponent
  17455. */
  17456. bool isCurrentlyModal() const throw();
  17457. /** Returns the number of components that are currently in a modal state.
  17458. @see getCurrentlyModalComponent
  17459. */
  17460. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  17461. /** Returns one of the components that are currently modal.
  17462. The index specifies which of the possible modal components to return. The order
  17463. of the components in this list is the reverse of the order in which they became
  17464. modal - so the component at index 0 is always the active component, and the others
  17465. are progressively earlier ones that are themselves now blocked by later ones.
  17466. @returns the modal component, or null if no components are modal (or if the
  17467. index is out of range)
  17468. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  17469. */
  17470. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  17471. /** Checks whether there's a modal component somewhere that's stopping this one
  17472. from receiving messages.
  17473. If there is a modal component, its canModalEventBeSentToComponent() method
  17474. will be called to see if it will still allow this component to receive events.
  17475. @see runModalLoop, getCurrentlyModalComponent
  17476. */
  17477. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  17478. /** When a component is modal, this callback allows it to choose which other
  17479. components can still receive events.
  17480. When a modal component is active and the user clicks on a non-modal component,
  17481. this method is called on the modal component, and if it returns true, the
  17482. event is allowed to reach its target. If it returns false, the event is blocked
  17483. and the inputAttemptWhenModal() callback is made.
  17484. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  17485. implementation just returns false in all cases.
  17486. */
  17487. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  17488. /** Called when the user tries to click on a component that is blocked by another
  17489. modal component.
  17490. When a component is modal and the user clicks on one of the other components,
  17491. the modal component will receive this callback.
  17492. The default implementation of this method will play a beep, and bring the currently
  17493. modal component to the front, but it can be overridden to do other tasks.
  17494. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  17495. */
  17496. virtual void inputAttemptWhenModal();
  17497. /** Returns one of the component's properties as a string.
  17498. @param keyName the name of the property to retrieve
  17499. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17500. properties, then it will check whether the parent component has
  17501. the key.
  17502. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17503. */
  17504. const String getComponentProperty (const String& keyName,
  17505. const bool useParentComponentIfNotFound,
  17506. const String& defaultReturnValue = String::empty) const throw();
  17507. /** Returns one of the properties as an integer.
  17508. @param keyName the name of the property to retrieve
  17509. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17510. properties, then it will check whether the parent component has
  17511. the key.
  17512. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17513. */
  17514. int getComponentPropertyInt (const String& keyName,
  17515. const bool useParentComponentIfNotFound,
  17516. const int defaultReturnValue = 0) const throw();
  17517. /** Returns one of the properties as an double.
  17518. @param keyName the name of the property to retrieve
  17519. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17520. properties, then it will check whether the parent component has
  17521. the key.
  17522. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17523. */
  17524. double getComponentPropertyDouble (const String& keyName,
  17525. const bool useParentComponentIfNotFound,
  17526. const double defaultReturnValue = 0.0) const throw();
  17527. /** Returns one of the properties as an boolean.
  17528. The result will be true if the string found for this key name can be parsed as a non-zero
  17529. integer.
  17530. @param keyName the name of the property to retrieve
  17531. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17532. properties, then it will check whether the parent component has
  17533. the key.
  17534. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17535. */
  17536. bool getComponentPropertyBool (const String& keyName,
  17537. const bool useParentComponentIfNotFound,
  17538. const bool defaultReturnValue = false) const throw();
  17539. /** Returns one of the properties as an colour.
  17540. @param keyName the name of the property to retrieve
  17541. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17542. properties, then it will check whether the parent component has
  17543. the key.
  17544. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  17545. */
  17546. const Colour getComponentPropertyColour (const String& keyName,
  17547. const bool useParentComponentIfNotFound,
  17548. const Colour& defaultReturnValue = Colours::black) const throw();
  17549. /** Sets a named property as a string.
  17550. @param keyName the name of the property to set. (This mustn't be an empty string)
  17551. @param value the new value to set it to
  17552. @see removeComponentProperty
  17553. */
  17554. void setComponentProperty (const String& keyName, const String& value) throw();
  17555. /** Sets a named property to an integer.
  17556. @param keyName the name of the property to set. (This mustn't be an empty string)
  17557. @param value the new value to set it to
  17558. @see removeComponentProperty
  17559. */
  17560. void setComponentProperty (const String& keyName, const int value) throw();
  17561. /** Sets a named property to a double.
  17562. @param keyName the name of the property to set. (This mustn't be an empty string)
  17563. @param value the new value to set it to
  17564. @see removeComponentProperty
  17565. */
  17566. void setComponentProperty (const String& keyName, const double value) throw();
  17567. /** Sets a named property to a boolean.
  17568. @param keyName the name of the property to set. (This mustn't be an empty string)
  17569. @param value the new value to set it to
  17570. @see removeComponentProperty
  17571. */
  17572. void setComponentProperty (const String& keyName, const bool value) throw();
  17573. /** Sets a named property to a colour.
  17574. @param keyName the name of the property to set. (This mustn't be an empty string)
  17575. @param newColour the new colour to set it to
  17576. @see removeComponentProperty
  17577. */
  17578. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  17579. /** Deletes a named component property.
  17580. @param keyName the name of the property to delete. (This mustn't be an empty string)
  17581. @see setComponentProperty, getComponentProperty
  17582. */
  17583. void removeComponentProperty (const String& keyName) throw();
  17584. /** Returns the complete set of properties that have been set for this component.
  17585. If no properties have been set, this will return a null pointer.
  17586. @see getComponentProperty, setComponentProperty
  17587. */
  17588. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  17589. /** Looks for a colour that has been registered with the given colour ID number.
  17590. If a colour has been set for this ID number using setColour(), then it is
  17591. returned. If none has been set, the method will try calling the component's
  17592. LookAndFeel class's findColour() method. If none has been registered with the
  17593. look-and-feel either, it will just return black.
  17594. The colour IDs for various purposes are stored as enums in the components that
  17595. they are relevent to - for an example, see Slider::ColourIds,
  17596. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  17597. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  17598. */
  17599. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  17600. /** Registers a colour to be used for a particular purpose.
  17601. Changing a colour will cause a synchronous callback to the colourChanged()
  17602. method, which your component can override if it needs to do something when
  17603. colours are altered.
  17604. For more details about colour IDs, see the comments for findColour().
  17605. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  17606. */
  17607. void setColour (const int colourId, const Colour& colour);
  17608. /** If a colour has been set with setColour(), this will remove it.
  17609. This allows you to make a colour revert to its default state.
  17610. */
  17611. void removeColour (const int colourId);
  17612. /** Returns true if the specified colour ID has been explicitly set for this
  17613. component using the setColour() method.
  17614. */
  17615. bool isColourSpecified (const int colourId) const throw();
  17616. /** This looks for any colours that have been specified for this component,
  17617. and copies them to the specified target component.
  17618. */
  17619. void copyAllExplicitColoursTo (Component& target) const throw();
  17620. /** This method is called when a colour is changed by the setColour() method.
  17621. @see setColour, findColour
  17622. */
  17623. virtual void colourChanged();
  17624. /** Returns the underlying native window handle for this component.
  17625. This is platform-dependent and strictly for power-users only!
  17626. */
  17627. void* getWindowHandle() const throw();
  17628. /** When created, each component is given a number to uniquely identify it.
  17629. The number is incremented each time a new component is created, so it's a more
  17630. unique way of identifying a component than using its memory location (which
  17631. may be reused after the component is deleted, of course).
  17632. */
  17633. uint32 getComponentUID() const throw() { return componentUID; }
  17634. juce_UseDebuggingNewOperator
  17635. private:
  17636. friend class ComponentPeer;
  17637. friend class InternalDragRepeater;
  17638. static Component* currentlyFocusedComponent;
  17639. static Component* componentUnderMouse;
  17640. String componentName_;
  17641. Component* parentComponent_;
  17642. uint32 componentUID;
  17643. Rectangle bounds_;
  17644. unsigned short numDeepMouseListeners;
  17645. Array <Component*> childComponentList_;
  17646. LookAndFeel* lookAndFeel_;
  17647. MouseCursor cursor_;
  17648. ImageEffectFilter* effect_;
  17649. Image* bufferedImage_;
  17650. VoidArray* mouseListeners_;
  17651. VoidArray* keyListeners_;
  17652. VoidArray* componentListeners_;
  17653. PropertySet* propertySet_;
  17654. struct ComponentFlags
  17655. {
  17656. bool hasHeavyweightPeerFlag : 1;
  17657. bool visibleFlag : 1;
  17658. bool opaqueFlag : 1;
  17659. bool ignoresMouseClicksFlag : 1;
  17660. bool allowChildMouseClicksFlag : 1;
  17661. bool wantsFocusFlag : 1;
  17662. bool isFocusContainerFlag : 1;
  17663. bool dontFocusOnMouseClickFlag : 1;
  17664. bool alwaysOnTopFlag : 1;
  17665. bool bufferToImageFlag : 1;
  17666. bool bringToFrontOnClickFlag : 1;
  17667. bool repaintOnMouseActivityFlag : 1;
  17668. bool draggingFlag : 1;
  17669. bool mouseOverFlag : 1;
  17670. bool mouseInsideFlag : 1;
  17671. bool currentlyModalFlag : 1;
  17672. bool isDisabledFlag : 1;
  17673. bool childCompFocusedFlag : 1;
  17674. #ifdef JUCE_DEBUG
  17675. bool isInsidePaintCall : 1;
  17676. #endif
  17677. };
  17678. union
  17679. {
  17680. uint32 componentFlags_;
  17681. ComponentFlags flags;
  17682. };
  17683. void internalMouseEnter (int x, int y, const int64 time);
  17684. void internalMouseExit (int x, int y, const int64 time);
  17685. void internalMouseDown (int x, int y);
  17686. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  17687. void internalMouseDrag (int x, int y, const int64 time);
  17688. void internalMouseMove (int x, int y, const int64 time);
  17689. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  17690. void internalBroughtToFront();
  17691. void internalFocusGain (const FocusChangeType cause);
  17692. void internalFocusLoss (const FocusChangeType cause);
  17693. void internalChildFocusChange (FocusChangeType cause);
  17694. void internalModalInputAttempt();
  17695. void internalModifierKeysChanged();
  17696. void internalChildrenChanged();
  17697. void internalHierarchyChanged();
  17698. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  17699. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  17700. void repaintParent() throw();
  17701. void sendFakeMouseMove() const;
  17702. void takeKeyboardFocus (const FocusChangeType cause);
  17703. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  17704. static void giveAwayFocus();
  17705. void sendEnablementChangeMessage();
  17706. static void* runModalLoopCallback (void*);
  17707. static void bringModalComponentToFront();
  17708. void subtractObscuredRegions (RectangleList& result,
  17709. const int deltaX, const int deltaY,
  17710. const Rectangle& clipRect,
  17711. const Component* const compToAvoid) const throw();
  17712. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  17713. const int deltaX, const int deltaY) const throw();
  17714. // how much of the component is not off the edges of its parents
  17715. const Rectangle getUnclippedArea() const;
  17716. void sendVisibilityChangeMessage();
  17717. // This is included here just to cause a compile error if your code is still handling
  17718. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  17719. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  17720. // implement its methods instead of this Component method).
  17721. virtual void filesDropped (const StringArray&, int, int) {}
  17722. // components aren't allowed to have copy constructors, as this would mess up parent
  17723. // hierarchies. You might need to give your subclasses a private dummy constructor like
  17724. // this one to avoid compiler warnings.
  17725. Component (const Component&);
  17726. const Component& operator= (const Component&);
  17727. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  17728. // subclass to use the new parameters to keyStateChanged)
  17729. virtual void keyStateChanged() {};
  17730. protected:
  17731. /** @internal */
  17732. virtual void internalRepaint (int x, int y, int w, int h);
  17733. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  17734. /** Overridden from the MessageListener parent class.
  17735. You can override this if you really need to, but be sure to pass your unwanted messages up
  17736. to this base class implementation, as the Component class needs to send itself messages
  17737. to work properly.
  17738. */
  17739. void handleMessage (const Message&);
  17740. };
  17741. #endif // __JUCE_COMPONENT_JUCEHEADER__
  17742. /********* End of inlined file: juce_Component.h *********/
  17743. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  17744. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17745. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17746. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  17747. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17748. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17749. /** A type used to hold the unique ID for an application command.
  17750. This is a numeric type, so it can be stored as an integer.
  17751. @see ApplicationCommandInfo, ApplicationCommandManager,
  17752. ApplicationCommandTarget, KeyPressMappingSet
  17753. */
  17754. typedef int CommandID;
  17755. /** A set of general-purpose application command IDs.
  17756. Because these commands are likely to be used in most apps, they're defined
  17757. here to help different apps to use the same numeric values for them.
  17758. Of course you don't have to use these, but some of them are used internally by
  17759. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  17760. @see ApplicationCommandInfo, ApplicationCommandManager,
  17761. ApplicationCommandTarget, KeyPressMappingSet
  17762. */
  17763. namespace StandardApplicationCommandIDs
  17764. {
  17765. /** This command ID should be used to send a "Quit the App" command.
  17766. This command is recognised by the JUCEApplication class, so if it is invoked
  17767. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  17768. object will catch it and call JUCEApplication::systemRequestedQuit().
  17769. */
  17770. static const CommandID quit = 0x1001;
  17771. /** The command ID that should be used to send a "Delete" command. */
  17772. static const CommandID del = 0x1002;
  17773. /** The command ID that should be used to send a "Cut" command. */
  17774. static const CommandID cut = 0x1003;
  17775. /** The command ID that should be used to send a "Copy to clipboard" command. */
  17776. static const CommandID copy = 0x1004;
  17777. /** The command ID that should be used to send a "Paste from clipboard" command. */
  17778. static const CommandID paste = 0x1005;
  17779. /** The command ID that should be used to send a "Select all" command. */
  17780. static const CommandID selectAll = 0x1006;
  17781. /** The command ID that should be used to send a "Deselect all" command. */
  17782. static const CommandID deselectAll = 0x1007;
  17783. }
  17784. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17785. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  17786. /**
  17787. Holds information describing an application command.
  17788. This object is used to pass information about a particular command, such as its
  17789. name, description and other usage flags.
  17790. When an ApplicationCommandTarget is asked to provide information about the commands
  17791. it can perform, this is the structure gets filled-in to describe each one.
  17792. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  17793. ApplicationCommandManager
  17794. */
  17795. struct JUCE_API ApplicationCommandInfo
  17796. {
  17797. ApplicationCommandInfo (const CommandID commandID) throw();
  17798. /** Sets a number of the structures values at once.
  17799. The meanings of each of the parameters is described below, in the appropriate
  17800. member variable's description.
  17801. */
  17802. void setInfo (const String& shortName,
  17803. const String& description,
  17804. const String& categoryName,
  17805. const int flags) throw();
  17806. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17807. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17808. is false, the bit is set.
  17809. */
  17810. void setActive (const bool isActive) throw();
  17811. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17812. */
  17813. void setTicked (const bool isTicked) throw();
  17814. /** Handy method for adding a keypress to the defaultKeypresses array.
  17815. This is just so you can write things like:
  17816. @code
  17817. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17818. @endcode
  17819. instead of
  17820. @code
  17821. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17822. @endcode
  17823. */
  17824. void addDefaultKeypress (const int keyCode,
  17825. const ModifierKeys& modifiers) throw();
  17826. /** The command's unique ID number.
  17827. */
  17828. CommandID commandID;
  17829. /** A short name to describe the command.
  17830. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17831. You can use the setInfo() method to quickly set this and some of the command's
  17832. other properties.
  17833. */
  17834. String shortName;
  17835. /** A longer description of the command.
  17836. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17837. pop-up tooltip describing what the command does.
  17838. You can use the setInfo() method to quickly set this and some of the command's
  17839. other properties.
  17840. */
  17841. String description;
  17842. /** A named category that the command fits into.
  17843. You can give your commands any category you like, and these will be displayed in
  17844. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17845. commands together.
  17846. You can use the setInfo() method to quickly set this and some of the command's
  17847. other properties.
  17848. */
  17849. String categoryName;
  17850. /** A list of zero or more keypresses that should be used as the default keys for
  17851. this command.
  17852. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17853. this list to initialise the default set of key-to-command mappings.
  17854. @see addDefaultKeypress
  17855. */
  17856. Array <KeyPress> defaultKeypresses;
  17857. /** Flags describing the ways in which this command should be used.
  17858. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17859. variable.
  17860. */
  17861. enum CommandFlags
  17862. {
  17863. /** Indicates that the command can't currently be performed.
  17864. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17865. not currently permissable to perform the command. If the flag is set, then
  17866. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17867. command or show themselves as not being enabled.
  17868. @see ApplicationCommandInfo::setActive
  17869. */
  17870. isDisabled = 1 << 0,
  17871. /** Indicates that the command should have a tick next to it on a menu.
  17872. If your command is shown on a menu and this is set, it'll show a tick next to
  17873. it. Other components such as buttons may also use this flag to indicate that it
  17874. is a value that can be toggled, and is currently in the 'on' state.
  17875. @see ApplicationCommandInfo::setTicked
  17876. */
  17877. isTicked = 1 << 1,
  17878. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17879. it will call the command twice, once on key-down and again on key-up.
  17880. @see ApplicationCommandTarget::InvocationInfo
  17881. */
  17882. wantsKeyUpDownCallbacks = 1 << 2,
  17883. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17884. command in its list.
  17885. */
  17886. hiddenFromKeyEditor = 1 << 3,
  17887. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17888. command in its list, but won't allow the assigned keypress to be changed.
  17889. */
  17890. readOnlyInKeyEditor = 1 << 4,
  17891. /** If this flag is present and the command is invoked from a keypress, then any
  17892. buttons or menus that are also connected to the command will not flash to
  17893. indicate that they've been triggered.
  17894. */
  17895. dontTriggerVisualFeedback = 1 << 5
  17896. };
  17897. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17898. You can use the setInfo() method to quickly set this and some of the command's
  17899. other properties.
  17900. */
  17901. int flags;
  17902. };
  17903. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17904. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17905. /**
  17906. A command target publishes a list of command IDs that it can perform.
  17907. An ApplicationCommandManager despatches commands to targets, which must be
  17908. able to provide information about what commands they can handle.
  17909. To create a target, you'll need to inherit from this class, implementing all of
  17910. its pure virtual methods.
  17911. For info about how a target is chosen to receive a command, see
  17912. ApplicationCommandManager::getFirstCommandTarget().
  17913. @see ApplicationCommandManager, ApplicationCommandInfo
  17914. */
  17915. class JUCE_API ApplicationCommandTarget
  17916. {
  17917. public:
  17918. /** Creates a command target. */
  17919. ApplicationCommandTarget();
  17920. /** Destructor. */
  17921. virtual ~ApplicationCommandTarget();
  17922. /**
  17923. */
  17924. struct JUCE_API InvocationInfo
  17925. {
  17926. InvocationInfo (const CommandID commandID) throw();
  17927. /** The UID of the command that should be performed. */
  17928. CommandID commandID;
  17929. /** The command's flags.
  17930. See ApplicationCommandInfo for a description of these flag values.
  17931. */
  17932. int commandFlags;
  17933. /** The types of context in which the command might be called. */
  17934. enum InvocationMethod
  17935. {
  17936. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17937. fromKeyPress, /**< The command is being invoked by a key-press. */
  17938. fromMenu, /**< The command is being invoked by a menu selection. */
  17939. fromButton /**< The command is being invoked by a button click. */
  17940. };
  17941. /** The type of event that triggered this command. */
  17942. InvocationMethod invocationMethod;
  17943. /** If triggered by a keypress or menu, this will be the component that had the
  17944. keyboard focus at the time.
  17945. If triggered by a button, it may be set to that component, or it may be null.
  17946. */
  17947. Component* originatingComponent;
  17948. /** The keypress that was used to invoke it.
  17949. Note that this will be an invalid keypress if the command was invoked
  17950. by some other means than a keyboard shortcut.
  17951. */
  17952. KeyPress keyPress;
  17953. /** True if the callback is being invoked when the key is pressed,
  17954. false if the key is being released.
  17955. @see KeyPressMappingSet::addCommand()
  17956. */
  17957. bool isKeyDown;
  17958. /** If the key is being released, this indicates how long it had been held
  17959. down for.
  17960. (Only relevant if isKeyDown is false.)
  17961. */
  17962. int millisecsSinceKeyPressed;
  17963. };
  17964. /** This must return the next target to try after this one.
  17965. When a command is being sent, and the first target can't handle
  17966. that command, this method is used to determine the next target that should
  17967. be tried.
  17968. It may return 0 if it doesn't know of another target.
  17969. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17970. method to return a parent component that might want to handle it.
  17971. @see invoke
  17972. */
  17973. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17974. /** This must return a complete list of commands that this target can handle.
  17975. Your target should add all the command IDs that it handles to the array that is
  17976. passed-in.
  17977. */
  17978. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17979. /** This must provide details about one of the commands that this target can perform.
  17980. This will be called with one of the command IDs that the target provided in its
  17981. getAllCommands() methods.
  17982. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17983. suitable information about the command. (The commandID field will already have been filled-in
  17984. by the caller).
  17985. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17986. set all the fields at once.
  17987. If the command is currently inactive for some reason, this method must use
  17988. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17989. bit of the ApplicationCommandInfo::flags field).
  17990. Any default key-presses for the command should be appended to the
  17991. ApplicationCommandInfo::defaultKeypresses field.
  17992. Note that if you change something that affects the status of the commands
  17993. that would be returned by this method (e.g. something that makes some commands
  17994. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17995. to cause the manager to refresh its status.
  17996. */
  17997. virtual void getCommandInfo (const CommandID commandID,
  17998. ApplicationCommandInfo& result) = 0;
  17999. /** This must actually perform the specified command.
  18000. If this target is able to perform the command specified by the commandID field of the
  18001. InvocationInfo structure, then it should do so, and must return true.
  18002. If it can't handle this command, it should return false, which tells the caller to pass
  18003. the command on to the next target in line.
  18004. @see invoke, ApplicationCommandManager::invoke
  18005. */
  18006. virtual bool perform (const InvocationInfo& info) = 0;
  18007. /** Makes this target invoke a command.
  18008. Your code can call this method to invoke a command on this target, but normally
  18009. you'd call it indirectly via ApplicationCommandManager::invoke() or
  18010. ApplicationCommandManager::invokeDirectly().
  18011. If this target can perform the given command, it will call its perform() method to
  18012. do so. If not, then getNextCommandTarget() will be used to determine the next target
  18013. to try, and the command will be passed along to it.
  18014. @param invocationInfo this must be correctly filled-in, describing the context for
  18015. the invocation.
  18016. @param asynchronously if false, the command will be performed before this method returns.
  18017. If true, a message will be posted so that the command will be performed
  18018. later on the message thread, and this method will return immediately.
  18019. @see perform, ApplicationCommandManager::invoke
  18020. */
  18021. bool invoke (const InvocationInfo& invocationInfo,
  18022. const bool asynchronously);
  18023. /** Invokes a given command directly on this target.
  18024. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18025. structure.
  18026. */
  18027. bool invokeDirectly (const CommandID commandID,
  18028. const bool asynchronously);
  18029. /** Searches this target and all subsequent ones for the first one that can handle
  18030. the specified command.
  18031. This will use getNextCommandTarget() to determine the chain of targets to try
  18032. after this one.
  18033. */
  18034. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  18035. /** Checks whether this command can currently be performed by this target.
  18036. This will return true only if a call to getCommandInfo() doesn't set the
  18037. isDisabled flag to indicate that the command is inactive.
  18038. */
  18039. bool isCommandActive (const CommandID commandID);
  18040. /** If this object is a Component, this method will seach upwards in its current
  18041. UI hierarchy for the next parent component that implements the
  18042. ApplicationCommandTarget class.
  18043. If your target is a Component, this is a very handy method to use in your
  18044. getNextCommandTarget() implementation.
  18045. */
  18046. ApplicationCommandTarget* findFirstTargetParentComponent();
  18047. juce_UseDebuggingNewOperator
  18048. private:
  18049. // (for async invocation of commands)
  18050. class CommandTargetMessageInvoker : public MessageListener
  18051. {
  18052. public:
  18053. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  18054. ~CommandTargetMessageInvoker();
  18055. void handleMessage (const Message& message);
  18056. private:
  18057. ApplicationCommandTarget* const owner;
  18058. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  18059. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  18060. };
  18061. CommandTargetMessageInvoker* messageInvoker;
  18062. friend class CommandTargetMessageInvoker;
  18063. bool tryToInvoke (const InvocationInfo& info, const bool async);
  18064. };
  18065. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18066. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  18067. /********* Start of inlined file: juce_ActionListener.h *********/
  18068. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  18069. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  18070. /**
  18071. Receives callbacks to indicate that some kind of event has occurred.
  18072. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  18073. about something that's happened.
  18074. @see ActionListenerList, ActionBroadcaster, ChangeListener
  18075. */
  18076. class JUCE_API ActionListener
  18077. {
  18078. public:
  18079. /** Destructor. */
  18080. virtual ~ActionListener() {}
  18081. /** Overridden by your subclass to receive the callback.
  18082. @param message the string that was specified when the event was triggered
  18083. by a call to ActionListenerList::sendActionMessage()
  18084. */
  18085. virtual void actionListenerCallback (const String& message) = 0;
  18086. };
  18087. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  18088. /********* End of inlined file: juce_ActionListener.h *********/
  18089. /**
  18090. An instance of this class is used to specify initialisation and shutdown
  18091. code for the application.
  18092. An application that wants to run in the JUCE framework needs to declare a
  18093. subclass of JUCEApplication and implement its various pure virtual methods.
  18094. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  18095. to declare an instance of this class and generate a suitable platform-specific
  18096. main() function.
  18097. e.g. @code
  18098. class MyJUCEApp : public JUCEApplication
  18099. {
  18100. // NEVER put objects inside a JUCEApplication class - only use pointers to
  18101. // objects, which you must create in the initialise() method.
  18102. MyApplicationWindow* myMainWindow;
  18103. public:
  18104. MyJUCEApp()
  18105. : myMainWindow (0)
  18106. {
  18107. // never create any Juce objects in the constructor - do all your initialisation
  18108. // in the initialise() method.
  18109. }
  18110. ~MyJUCEApp()
  18111. {
  18112. // all your shutdown code must have already been done in the shutdown() method -
  18113. // nothing should happen in this destructor.
  18114. }
  18115. void initialise (const String& commandLine)
  18116. {
  18117. myMainWindow = new MyApplicationWindow();
  18118. myMainWindow->setBounds (100, 100, 400, 500);
  18119. myMainWindow->setVisible (true);
  18120. }
  18121. void shutdown()
  18122. {
  18123. delete myMainWindow;
  18124. }
  18125. const String getApplicationName()
  18126. {
  18127. return T("Super JUCE-o-matic");
  18128. }
  18129. const String getApplicationVersion()
  18130. {
  18131. return T("1.0");
  18132. }
  18133. };
  18134. // this creates wrapper code to actually launch the app properly.
  18135. START_JUCE_APPLICATION (MyJUCEApp)
  18136. @endcode
  18137. Because this object will be created before Juce has properly initialised, you must
  18138. NEVER add any member variable objects that will be automatically constructed. Likewise
  18139. don't put ANY code in the constructor that could call Juce functions. Any objects that
  18140. you want to add to the class must be pointers, which you should instantiate during the
  18141. initialise() method, and delete in the shutdown() method.
  18142. @see MessageManager, DeletedAtShutdown
  18143. */
  18144. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  18145. private ActionListener
  18146. {
  18147. protected:
  18148. /** Constructs a JUCE app object.
  18149. If subclasses implement a constructor or destructor, they shouldn't call any
  18150. JUCE code in there - put your startup/shutdown code in initialise() and
  18151. shutdown() instead.
  18152. */
  18153. JUCEApplication();
  18154. public:
  18155. /** Destructor.
  18156. If subclasses implement a constructor or destructor, they shouldn't call any
  18157. JUCE code in there - put your startup/shutdown code in initialise() and
  18158. shutdown() instead.
  18159. */
  18160. virtual ~JUCEApplication();
  18161. /** Returns the global instance of the application object being run. */
  18162. static JUCEApplication* getInstance() throw();
  18163. /** Called when the application starts.
  18164. This will be called once to let the application do whatever initialisation
  18165. it needs, create its windows, etc.
  18166. After the method returns, the normal event-dispatch loop will be run,
  18167. until the quit() method is called, at which point the shutdown()
  18168. method will be called to let the application clear up anything it needs
  18169. to delete.
  18170. If during the initialise() method, the application decides not to start-up
  18171. after all, it can just call the quit() method and the event loop won't be run.
  18172. @param commandLineParameters the line passed in does not include the
  18173. name of the executable, just the parameter list.
  18174. @see shutdown, quit
  18175. */
  18176. virtual void initialise (const String& commandLineParameters) = 0;
  18177. /** Returns true if the application hasn't yet completed its initialise() method
  18178. and entered the main event loop.
  18179. This is handy for things like splash screens to know when the app's up-and-running
  18180. properly.
  18181. */
  18182. bool isInitialising() const throw();
  18183. /* Called to allow the application to clear up before exiting.
  18184. After JUCEApplication::quit() has been called, the event-dispatch loop will
  18185. terminate, and this method will get called to allow the app to sort itself
  18186. out.
  18187. Be careful that nothing happens in this method that might rely on messages
  18188. being sent, or any kind of window activity, because the message loop is no
  18189. longer running at this point.
  18190. @see DeletedAtShutdown
  18191. */
  18192. virtual void shutdown() = 0;
  18193. /** Returns the application's name.
  18194. An application must implement this to name itself.
  18195. */
  18196. virtual const String getApplicationName() = 0;
  18197. /** Returns the application's version number.
  18198. An application can implement this to give itself a version.
  18199. (The default implementation of this just returns an empty string).
  18200. */
  18201. virtual const String getApplicationVersion();
  18202. /** Checks whether multiple instances of the app are allowed.
  18203. If you application class returns true for this, more than one instance is
  18204. permitted to run (except on the Mac where this isn't possible).
  18205. If it's false, the second instance won't start, but it you will still get a
  18206. callback to anotherInstanceStarted() to tell you about this - which
  18207. gives you a chance to react to what the user was trying to do.
  18208. */
  18209. virtual bool moreThanOneInstanceAllowed();
  18210. /** Indicates that the user has tried to start up another instance of the app.
  18211. This will get called even if moreThanOneInstanceAllowed() is false.
  18212. */
  18213. virtual void anotherInstanceStarted (const String& commandLine);
  18214. /** Called when the operating system is trying to close the application.
  18215. The default implementation of this method is to call quit(), but it may
  18216. be overloaded to ignore the request or do some other special behaviour
  18217. instead. For example, you might want to offer the user the chance to save
  18218. their changes before quitting, and give them the chance to cancel.
  18219. If you want to send a quit signal to your app, this is the correct method
  18220. to call, because it means that requests that come from the system get handled
  18221. in the same way as those from your own application code. So e.g. you'd
  18222. call this method from a "quit" item on a menu bar.
  18223. */
  18224. virtual void systemRequestedQuit();
  18225. /** If any unhandled exceptions make it through to the message dispatch loop, this
  18226. callback will be triggered, in case you want to log them or do some other
  18227. type of error-handling.
  18228. If the type of exception is derived from the std::exception class, the pointer
  18229. passed-in will be valid. If the exception is of unknown type, this pointer
  18230. will be null.
  18231. */
  18232. virtual void unhandledException (const std::exception* e,
  18233. const String& sourceFilename,
  18234. const int lineNumber);
  18235. /** Signals that the main message loop should stop and the application should terminate.
  18236. This isn't synchronous, it just posts a quit message to the main queue, and
  18237. when this message arrives, the message loop will stop, the shutdown() method
  18238. will be called, and the app will exit.
  18239. Note that this will cause an unconditional quit to happen, so if you need an
  18240. extra level before this, e.g. to give the user the chance to save their work
  18241. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  18242. method - see that method's help for more info.
  18243. @see MessageManager, DeletedAtShutdown
  18244. */
  18245. static void quit();
  18246. /** Sets the value that should be returned as the application's exit code when the
  18247. app quits.
  18248. This is the value that's returned by the main() function. Normally you'd leave this
  18249. as 0 unless you want to indicate an error code.
  18250. @see getApplicationReturnValue
  18251. */
  18252. void setApplicationReturnValue (const int newReturnValue) throw();
  18253. /** Returns the value that has been set as the application's exit code.
  18254. @see setApplicationReturnValue
  18255. */
  18256. int getApplicationReturnValue() const throw() { return appReturnValue; }
  18257. /** Returns the application's command line params.
  18258. */
  18259. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  18260. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  18261. /** @internal */
  18262. static int main (String& commandLine, JUCEApplication* const newApp);
  18263. /** @internal */
  18264. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  18265. /** @internal */
  18266. static void sendUnhandledException (const std::exception* const e,
  18267. const char* const sourceFile,
  18268. const int lineNumber);
  18269. /** @internal */
  18270. ApplicationCommandTarget* getNextCommandTarget();
  18271. /** @internal */
  18272. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  18273. /** @internal */
  18274. void getAllCommands (Array <CommandID>& commands);
  18275. /** @internal */
  18276. bool perform (const InvocationInfo& info);
  18277. /** @internal */
  18278. void actionListenerCallback (const String& message);
  18279. private:
  18280. String commandLineParameters;
  18281. int appReturnValue;
  18282. bool stillInitialising;
  18283. InterProcessLock* appLock;
  18284. public:
  18285. /** @internal */
  18286. bool initialiseApp (String& commandLine);
  18287. /** @internal */
  18288. static int shutdownAppAndClearUp();
  18289. };
  18290. #endif // __JUCE_APPLICATION_JUCEHEADER__
  18291. /********* End of inlined file: juce_Application.h *********/
  18292. #endif
  18293. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18294. #endif
  18295. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18296. #endif
  18297. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18298. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  18299. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18300. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18301. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  18302. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  18303. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  18304. /**
  18305. Has a callback method that is triggered asynchronously.
  18306. This object allows an asynchronous callback function to be triggered, for
  18307. tasks such as coalescing multiple updates into a single callback later on.
  18308. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  18309. message thread calling handleAsyncUpdate() as soon as it can.
  18310. */
  18311. class JUCE_API AsyncUpdater
  18312. {
  18313. public:
  18314. /** Creates an AsyncUpdater object. */
  18315. AsyncUpdater() throw();
  18316. /** Destructor.
  18317. If there are any pending callbacks when the object is deleted, these are lost.
  18318. */
  18319. virtual ~AsyncUpdater();
  18320. /** Causes the callback to be triggered at a later time.
  18321. This method returns immediately, having made sure that a callback
  18322. to the handleAsyncUpdate() method will occur as soon as possible.
  18323. If an update callback is already pending but hasn't happened yet, calls
  18324. to this method will be ignored.
  18325. It's thread-safe to call this method from any number of threads without
  18326. needing to worry about locking.
  18327. */
  18328. void triggerAsyncUpdate() throw();
  18329. /** This will stop any pending updates from happening.
  18330. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  18331. callback happens, this will cancel the handleAsyncUpdate() callback.
  18332. */
  18333. void cancelPendingUpdate() throw();
  18334. /** If an update has been triggered and is pending, this will invoke it
  18335. synchronously.
  18336. Use this as a kind of "flush" operation - if an update is pending, the
  18337. handleAsyncUpdate() method will be called immediately; if no update is
  18338. pending, then nothing will be done.
  18339. */
  18340. void handleUpdateNowIfNeeded();
  18341. /** Called back to do whatever your class needs to do.
  18342. This method is called by the message thread at the next convenient time
  18343. after the triggerAsyncUpdate() method has been called.
  18344. */
  18345. virtual void handleAsyncUpdate() = 0;
  18346. private:
  18347. class AsyncUpdaterInternal : public MessageListener
  18348. {
  18349. public:
  18350. AsyncUpdaterInternal() throw() {}
  18351. ~AsyncUpdaterInternal() {}
  18352. void handleMessage (const Message&);
  18353. AsyncUpdater* owner;
  18354. private:
  18355. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  18356. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  18357. };
  18358. AsyncUpdaterInternal internalAsyncHandler;
  18359. bool asyncMessagePending;
  18360. };
  18361. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  18362. /********* End of inlined file: juce_AsyncUpdater.h *********/
  18363. /********* Start of inlined file: juce_Desktop.h *********/
  18364. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  18365. #define __JUCE_DESKTOP_JUCEHEADER__
  18366. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  18367. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18368. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18369. /**
  18370. Classes derived from this will be automatically deleted when the application exits.
  18371. After JUCEApplication::shutdown() has been called, any objects derived from
  18372. DeletedAtShutdown which are still in existence will be deleted in the reverse
  18373. order to that in which they were created.
  18374. So if you've got a singleton and don't want to have to explicitly delete it, just
  18375. inherit from this and it'll be taken care of.
  18376. */
  18377. class JUCE_API DeletedAtShutdown
  18378. {
  18379. protected:
  18380. /** Creates a DeletedAtShutdown object. */
  18381. DeletedAtShutdown() throw();
  18382. /** Destructor.
  18383. It's ok to delete these objects explicitly - it's only the ones left
  18384. dangling at the end that will be deleted automatically.
  18385. */
  18386. virtual ~DeletedAtShutdown();
  18387. public:
  18388. /** Deletes all extant objects.
  18389. This shouldn't be used by applications, as it's called automatically
  18390. in the shutdown code of the JUCEApplication class.
  18391. */
  18392. static void deleteAll();
  18393. private:
  18394. DeletedAtShutdown (const DeletedAtShutdown&);
  18395. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  18396. };
  18397. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18398. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  18399. /********* Start of inlined file: juce_Timer.h *********/
  18400. #ifndef __JUCE_TIMER_JUCEHEADER__
  18401. #define __JUCE_TIMER_JUCEHEADER__
  18402. class InternalTimerThread;
  18403. /**
  18404. Repeatedly calls a user-defined method at a specified time interval.
  18405. A Timer's timerCallback() method will be repeatedly called at a given
  18406. interval. Initially when a Timer object is created, they will do nothing
  18407. until the startTimer() method is called, then the message thread will
  18408. start calling it back until stopTimer() is called.
  18409. The time interval isn't guaranteed to be precise to any more than maybe
  18410. 10-20ms, and the intervals may end up being much longer than requested if the
  18411. system is busy. Because it's the message thread that is doing the callbacks,
  18412. any messages that take a significant amount of time to process will block
  18413. all the timers for that period.
  18414. If you need to have a single callback that is shared by multiple timers with
  18415. different frequencies, then the MultiTimer class allows you to do that - its
  18416. structure is very similar to the Timer class, but contains multiple timers
  18417. internally, each one identified by an ID number.
  18418. @see MultiTimer
  18419. */
  18420. class JUCE_API Timer
  18421. {
  18422. protected:
  18423. /** Creates a Timer.
  18424. When created, the timer is stopped, so use startTimer() to get it going.
  18425. */
  18426. Timer() throw();
  18427. /** Creates a copy of another timer.
  18428. Note that this timer won't be started, even if the one you're copying
  18429. is running.
  18430. */
  18431. Timer (const Timer& other) throw();
  18432. public:
  18433. /** Destructor. */
  18434. virtual ~Timer();
  18435. /** The user-defined callback routine that actually gets called periodically.
  18436. It's perfectly ok to call startTimer() or stopTimer() from within this
  18437. callback to change the subsequent intervals.
  18438. */
  18439. virtual void timerCallback() = 0;
  18440. /** Starts the timer and sets the length of interval required.
  18441. If the timer is already started, this will reset it, so the
  18442. time between calling this method and the next timer callback
  18443. will not be less than the interval length passed in.
  18444. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  18445. rounded up to 1)
  18446. */
  18447. void startTimer (const int intervalInMilliseconds) throw();
  18448. /** Stops the timer.
  18449. No more callbacks will be made after this method returns.
  18450. If this is called from a different thread, any callbacks that may
  18451. be currently executing may be allowed to finish before the method
  18452. returns.
  18453. */
  18454. void stopTimer() throw();
  18455. /** Checks if the timer has been started.
  18456. @returns true if the timer is running.
  18457. */
  18458. bool isTimerRunning() const throw() { return periodMs > 0; }
  18459. /** Returns the timer's interval.
  18460. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  18461. */
  18462. int getTimerInterval() const throw() { return periodMs; }
  18463. private:
  18464. friend class InternalTimerThread;
  18465. int countdownMs, periodMs;
  18466. Timer* previous;
  18467. Timer* next;
  18468. const Timer& operator= (const Timer&);
  18469. };
  18470. #endif // __JUCE_TIMER_JUCEHEADER__
  18471. /********* End of inlined file: juce_Timer.h *********/
  18472. /**
  18473. Classes can implement this interface and register themselves with the Desktop class
  18474. to receive callbacks when the currently focused component changes.
  18475. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  18476. */
  18477. class JUCE_API FocusChangeListener
  18478. {
  18479. public:
  18480. /** Destructor. */
  18481. virtual ~FocusChangeListener() {}
  18482. /** Callback to indicate that the currently focused component has changed. */
  18483. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  18484. };
  18485. /**
  18486. Describes and controls aspects of the computer's desktop.
  18487. */
  18488. class JUCE_API Desktop : private DeletedAtShutdown,
  18489. private Timer,
  18490. private AsyncUpdater
  18491. {
  18492. public:
  18493. /** There's only one dektop object, and this method will return it.
  18494. */
  18495. static Desktop& JUCE_CALLTYPE getInstance() throw();
  18496. /** Returns a list of the positions of all the monitors available.
  18497. The first rectangle in the list will be the main monitor area.
  18498. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  18499. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  18500. */
  18501. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  18502. /** Returns the position and size of the main monitor.
  18503. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  18504. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  18505. */
  18506. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  18507. /** Returns the position and size of the monitor which contains this co-ordinate.
  18508. If none of the monitors contains the point, this will just return the
  18509. main monitor.
  18510. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  18511. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  18512. */
  18513. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  18514. /** Returns the mouse position.
  18515. The co-ordinates are relative to the top-left of the main monitor.
  18516. */
  18517. static void getMousePosition (int& x, int& y) throw();
  18518. /** Makes the mouse pointer jump to a given location.
  18519. The co-ordinates are relative to the top-left of the main monitor.
  18520. */
  18521. static void setMousePosition (int x, int y) throw();
  18522. /** Returns the last position at which a mouse button was pressed.
  18523. */
  18524. static void getLastMouseDownPosition (int& x, int& y) throw();
  18525. /** Returns the number of times the mouse button has been clicked since the
  18526. app started.
  18527. Each mouse-down event increments this number by 1.
  18528. */
  18529. static int getMouseButtonClickCounter() throw();
  18530. /** This lets you prevent the screensaver from becoming active.
  18531. Handy if you're running some sort of presentation app where having a screensaver
  18532. appear would be annoying.
  18533. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  18534. won't enable a screensaver unless the user has actually set one up).
  18535. The disablement will only happen while the Juce application is the foreground
  18536. process - if another task is running in front of it, then the screensaver will
  18537. be unaffected.
  18538. @see isScreenSaverEnabled
  18539. */
  18540. static void setScreenSaverEnabled (const bool isEnabled) throw();
  18541. /** Returns true if the screensaver has not been turned off.
  18542. This will return the last value passed into setScreenSaverEnabled(). Note that
  18543. it won't tell you whether the user is actually using a screen saver, just
  18544. whether this app is deliberately preventing one from running.
  18545. @see setScreenSaverEnabled
  18546. */
  18547. static bool isScreenSaverEnabled() throw();
  18548. /** Registers a MouseListener that will receive all mouse events that occur on
  18549. any component.
  18550. @see removeGlobalMouseListener
  18551. */
  18552. void addGlobalMouseListener (MouseListener* const listener) throw();
  18553. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  18554. method.
  18555. @see addGlobalMouseListener
  18556. */
  18557. void removeGlobalMouseListener (MouseListener* const listener) throw();
  18558. /** Registers a MouseListener that will receive a callback whenever the focused
  18559. component changes.
  18560. */
  18561. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  18562. /** Unregisters a listener that was added with addFocusChangeListener(). */
  18563. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  18564. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  18565. The component must already be on the desktop for this method to work. It will
  18566. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  18567. etc will be hidden.
  18568. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  18569. the component that's currently being used will be resized back to the size
  18570. and position it was in before being put into this mode.
  18571. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  18572. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  18573. to hide as much on-screen paraphenalia as possible.
  18574. */
  18575. void setKioskModeComponent (Component* componentToUse,
  18576. const bool allowMenusAndBars = true);
  18577. /** Returns the component that is currently being used in kiosk-mode.
  18578. This is the component that was last set by setKioskModeComponent(). If none
  18579. has been set, this returns 0.
  18580. */
  18581. Component* getKioskModeComponent() const { return kioskModeComponent; }
  18582. /** Returns the number of components that are currently active as top-level
  18583. desktop windows.
  18584. @see getComponent, Component::addToDesktop
  18585. */
  18586. int getNumComponents() const throw();
  18587. /** Returns one of the top-level desktop window components.
  18588. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  18589. index is out-of-range.
  18590. @see getNumComponents, Component::addToDesktop
  18591. */
  18592. Component* getComponent (const int index) const throw();
  18593. /** Finds the component at a given screen location.
  18594. This will drill down into top-level windows to find the child component at
  18595. the given position.
  18596. Returns 0 if the co-ordinates are inside a non-Juce window.
  18597. */
  18598. Component* findComponentAt (const int screenX,
  18599. const int screenY) const;
  18600. juce_UseDebuggingNewOperator
  18601. /** Tells this object to refresh its idea of what the screen resolution is.
  18602. (Called internally by the native code).
  18603. */
  18604. void refreshMonitorSizes() throw();
  18605. /** True if the OS supports semitransparent windows */
  18606. static bool canUseSemiTransparentWindows() throw();
  18607. private:
  18608. friend class Component;
  18609. friend class ComponentPeer;
  18610. SortedSet <void*> mouseListeners, focusListeners;
  18611. VoidArray desktopComponents;
  18612. friend class DeletedAtShutdown;
  18613. friend class TopLevelWindowManager;
  18614. Desktop() throw();
  18615. ~Desktop() throw();
  18616. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  18617. int lastMouseX, lastMouseY;
  18618. Component* kioskModeComponent;
  18619. Rectangle kioskComponentOriginalBounds;
  18620. void timerCallback();
  18621. void sendMouseMove();
  18622. void resetTimer() throw();
  18623. int getNumDisplayMonitors() const throw();
  18624. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  18625. void addDesktopComponent (Component* const c) throw();
  18626. void removeDesktopComponent (Component* const c) throw();
  18627. void componentBroughtToFront (Component* const c) throw();
  18628. void triggerFocusCallback() throw();
  18629. void handleAsyncUpdate();
  18630. Desktop (const Desktop&);
  18631. const Desktop& operator= (const Desktop&);
  18632. };
  18633. #endif // __JUCE_DESKTOP_JUCEHEADER__
  18634. /********* End of inlined file: juce_Desktop.h *********/
  18635. class KeyPressMappingSet;
  18636. class ApplicationCommandManagerListener;
  18637. /**
  18638. One of these objects holds a list of all the commands your app can perform,
  18639. and despatches these commands when needed.
  18640. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  18641. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  18642. to invoke automatically, which means you don't have to handle the result of a menu
  18643. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  18644. which can choose which events they want to handle.
  18645. This architecture also allows for nested ApplicationCommandTargets, so that for example
  18646. you could have two different objects, one inside the other, both of which can respond to
  18647. a "delete" command. Depending on which one has focus, the command will be sent to the
  18648. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  18649. method.
  18650. To set up your app to use commands, you'll need to do the following:
  18651. - Create a global ApplicationCommandManager to hold the list of all possible
  18652. commands. (This will also manage a set of key-mappings for them).
  18653. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  18654. This allows the object to provide a list of commands that it can perform, and
  18655. to handle them.
  18656. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  18657. or ApplicationCommandManager::registerCommand().
  18658. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  18659. method to access the key-mapper object, which you will need to register as a key-listener
  18660. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  18661. about setting this up.
  18662. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  18663. cause these commands to be invoked automatically.
  18664. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  18665. When a command is invoked, the ApplicationCommandManager will try to choose the best
  18666. ApplicationCommandTarget to receive the specified command. To do this it will use the
  18667. current keyboard focus to see which component might be interested, and will search the
  18668. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  18669. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  18670. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  18671. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  18672. point if the command still hasn't been performed, it will be passed to the current
  18673. JUCEApplication object (which is itself an ApplicationCommandTarget).
  18674. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  18675. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  18676. the object yourself.
  18677. @see ApplicationCommandTarget, ApplicationCommandInfo
  18678. */
  18679. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  18680. private FocusChangeListener
  18681. {
  18682. public:
  18683. /** Creates an ApplicationCommandManager.
  18684. Once created, you'll need to register all your app's commands with it, using
  18685. ApplicationCommandManager::registerAllCommandsForTarget() or
  18686. ApplicationCommandManager::registerCommand().
  18687. */
  18688. ApplicationCommandManager();
  18689. /** Destructor.
  18690. Make sure that you don't delete this if pointers to it are still being used by
  18691. objects such as PopupMenus or Buttons.
  18692. */
  18693. virtual ~ApplicationCommandManager();
  18694. /** Clears the current list of all commands.
  18695. Note that this will also clear the contents of the KeyPressMappingSet.
  18696. */
  18697. void clearCommands();
  18698. /** Adds a command to the list of registered commands.
  18699. @see registerAllCommandsForTarget
  18700. */
  18701. void registerCommand (const ApplicationCommandInfo& newCommand);
  18702. /** Adds all the commands that this target publishes to the manager's list.
  18703. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  18704. to get details about all the commands that this target can do, and will call
  18705. registerCommand() to add each one to the manger's list.
  18706. @see registerCommand
  18707. */
  18708. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  18709. /** Removes the command with a specified ID.
  18710. Note that this will also remove any key mappings that are mapped to the command.
  18711. */
  18712. void removeCommand (const CommandID commandID);
  18713. /** This should be called to tell the manager that one of its registered commands may have changed
  18714. its active status.
  18715. Because the command manager only finds out whether a command is active or inactive by querying
  18716. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  18717. allows things like buttons to update their enablement, etc.
  18718. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  18719. for any registered listeners.
  18720. */
  18721. void commandStatusChanged();
  18722. /** Returns the number of commands that have been registered.
  18723. @see registerCommand
  18724. */
  18725. int getNumCommands() const throw() { return commands.size(); }
  18726. /** Returns the details about one of the registered commands.
  18727. The index is between 0 and (getNumCommands() - 1).
  18728. */
  18729. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  18730. /** Returns the details about a given command ID.
  18731. This will search the list of registered commands for one with the given command
  18732. ID number, and return its associated info. If no matching command is found, this
  18733. will return 0.
  18734. */
  18735. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  18736. /** Returns the name field for a command.
  18737. An empty string is returned if no command with this ID has been registered.
  18738. @see getDescriptionOfCommand
  18739. */
  18740. const String getNameOfCommand (const CommandID commandID) const throw();
  18741. /** Returns the description field for a command.
  18742. An empty string is returned if no command with this ID has been registered. If the
  18743. command has no description, this will return its short name field instead.
  18744. @see getNameOfCommand
  18745. */
  18746. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  18747. /** Returns the list of categories.
  18748. This will go through all registered commands, and return a list of all the distict
  18749. categoryName values from their ApplicationCommandInfo structure.
  18750. @see getCommandsInCategory()
  18751. */
  18752. const StringArray getCommandCategories() const throw();
  18753. /** Returns a list of all the command UIDs in a particular category.
  18754. @see getCommandCategories()
  18755. */
  18756. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  18757. /** Returns the manager's internal set of key mappings.
  18758. This object can be used to edit the keypresses. To actually link this object up
  18759. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  18760. class.
  18761. @see KeyPressMappingSet
  18762. */
  18763. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  18764. /** Invokes the given command directly, sending it to the default target.
  18765. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18766. structure.
  18767. */
  18768. bool invokeDirectly (const CommandID commandID,
  18769. const bool asynchronously);
  18770. /** Sends a command to the default target.
  18771. This will choose a target using getFirstCommandTarget(), and send the specified command
  18772. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  18773. first target can't handle the command, it will be passed on to targets further down the
  18774. chain (see ApplicationCommandTarget::invoke() for more info).
  18775. @param invocationInfo this must be correctly filled-in, describing the context for
  18776. the invocation.
  18777. @param asynchronously if false, the command will be performed before this method returns.
  18778. If true, a message will be posted so that the command will be performed
  18779. later on the message thread, and this method will return immediately.
  18780. @see ApplicationCommandTarget::invoke
  18781. */
  18782. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  18783. const bool asynchronously);
  18784. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  18785. Whenever the manager needs to know which target a command should be sent to, it calls
  18786. this method to determine the first one to try.
  18787. By default, this method will return the target that was set by calling setFirstCommandTarget().
  18788. If no target is set, it will return the result of findDefaultComponentTarget().
  18789. If you need to make sure all commands go via your own custom target, then you can
  18790. either use setFirstCommandTarget() to specify a single target, or override this method
  18791. if you need more complex logic to choose one.
  18792. It may return 0 if no targets are available.
  18793. @see getTargetForCommand, invoke, invokeDirectly
  18794. */
  18795. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  18796. /** Sets a target to be returned by getFirstCommandTarget().
  18797. If this is set to 0, then getFirstCommandTarget() will by default return the
  18798. result of findDefaultComponentTarget().
  18799. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  18800. deleting the target object.
  18801. */
  18802. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  18803. /** Tries to find the best target to use to perform a given command.
  18804. This will call getFirstCommandTarget() to find the preferred target, and will
  18805. check whether that target can handle the given command. If it can't, then it'll use
  18806. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  18807. so on until no more are available.
  18808. If no targets are found that can perform the command, this method will return 0.
  18809. If a target is found, then it will get the target to fill-in the upToDateInfo
  18810. structure with the latest info about that command, so that the caller can see
  18811. whether the command is disabled, ticked, etc.
  18812. */
  18813. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18814. ApplicationCommandInfo& upToDateInfo);
  18815. /** Registers a listener that will be called when various events occur. */
  18816. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18817. /** Deregisters a previously-added listener. */
  18818. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18819. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18820. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18821. but is exposed here in case it's useful.
  18822. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18823. windows, etc., and using the findTargetForComponent() method.
  18824. */
  18825. static ApplicationCommandTarget* findDefaultComponentTarget();
  18826. /** Examines this component and all its parents in turn, looking for the first one
  18827. which is a ApplicationCommandTarget.
  18828. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18829. that class.
  18830. */
  18831. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18832. juce_UseDebuggingNewOperator
  18833. private:
  18834. OwnedArray <ApplicationCommandInfo> commands;
  18835. SortedSet <void*> listeners;
  18836. KeyPressMappingSet* keyMappings;
  18837. ApplicationCommandTarget* firstTarget;
  18838. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18839. void handleAsyncUpdate();
  18840. void globalFocusChanged (Component*);
  18841. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18842. // version of this method.
  18843. virtual short getFirstCommandTarget() { return 0; }
  18844. };
  18845. /**
  18846. A listener that receives callbacks from an ApplicationCommandManager when
  18847. commands are invoked or the command list is changed.
  18848. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18849. */
  18850. class JUCE_API ApplicationCommandManagerListener
  18851. {
  18852. public:
  18853. /** Destructor. */
  18854. virtual ~ApplicationCommandManagerListener() {}
  18855. /** Called when an app command is about to be invoked. */
  18856. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18857. /** Called when commands are registered or deregistered from the
  18858. command manager, or when commands are made active or inactive.
  18859. Note that if you're using this to watch for changes to whether a command is disabled,
  18860. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18861. whenever the status of your command might have changed.
  18862. */
  18863. virtual void applicationCommandListChanged() = 0;
  18864. };
  18865. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18866. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18867. #endif
  18868. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18869. #endif
  18870. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18871. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18872. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18873. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18874. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18875. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18876. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18877. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18878. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18879. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18880. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18881. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18882. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18883. /********* Start of inlined file: juce_ChangeListener.h *********/
  18884. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18885. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18886. /**
  18887. Receives callbacks about changes to some kind of object.
  18888. Many objects use a ChangeListenerList to keep a set of listeners which they
  18889. will inform when something changes. A subclass of ChangeListener
  18890. is used to receive these callbacks.
  18891. Note that the major difference between an ActionListener and a ChangeListener
  18892. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18893. callbacks, but ActionListeners perform one callback for every event posted.
  18894. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18895. */
  18896. class JUCE_API ChangeListener
  18897. {
  18898. public:
  18899. /** Destructor. */
  18900. virtual ~ChangeListener() {}
  18901. /** Overridden by your subclass to receive the callback.
  18902. @param objectThatHasChanged the value that was passed to the
  18903. ChangeListenerList::sendChangeMessage() method
  18904. */
  18905. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18906. };
  18907. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18908. /********* End of inlined file: juce_ChangeListener.h *********/
  18909. /**
  18910. A set of ChangeListeners.
  18911. Listeners can be added and removed from the list, and change messages can be
  18912. broadcast to all the listeners.
  18913. @see ChangeListener, ChangeBroadcaster
  18914. */
  18915. class JUCE_API ChangeListenerList : public MessageListener
  18916. {
  18917. public:
  18918. /** Creates an empty list. */
  18919. ChangeListenerList() throw();
  18920. /** Destructor. */
  18921. ~ChangeListenerList() throw();
  18922. /** Adds a listener to the list.
  18923. (Trying to add a listener that's already on the list will have no effect).
  18924. */
  18925. void addChangeListener (ChangeListener* const listener) throw();
  18926. /** Removes a listener from the list.
  18927. If the listener isn't on the list, this won't have any effect.
  18928. */
  18929. void removeChangeListener (ChangeListener* const listener) throw();
  18930. /** Removes all listeners from the list. */
  18931. void removeAllChangeListeners() throw();
  18932. /** Posts an asynchronous change message to all the listeners.
  18933. If a message has already been sent and hasn't yet been delivered, this
  18934. method won't send another - in this way it coalesces multiple frequent
  18935. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18936. with the ActionListener, which posts a new event for every call to its
  18937. sendActionMessage() method.
  18938. Only listeners which are on the list when the change event is delivered
  18939. will receive the event - and this may include listeners that weren't on
  18940. the list when the change message was sent.
  18941. @param objectThatHasChanged this pointer is passed to the
  18942. ChangeListener::changeListenerCallback() method,
  18943. and can be any value the application needs
  18944. @see sendSynchronousChangeMessage
  18945. */
  18946. void sendChangeMessage (void* objectThatHasChanged) throw();
  18947. /** This will synchronously callback all the ChangeListeners.
  18948. Use this if you need to synchronously force a call to all the
  18949. listeners' ChangeListener::changeListenerCallback() methods.
  18950. */
  18951. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18952. /** If a change message has been sent but not yet dispatched, this will
  18953. use sendSynchronousChangeMessage() to make the callback immediately.
  18954. */
  18955. void dispatchPendingMessages();
  18956. /** @internal */
  18957. void handleMessage (const Message&);
  18958. juce_UseDebuggingNewOperator
  18959. private:
  18960. SortedSet <void*> listeners;
  18961. CriticalSection lock;
  18962. void* lastChangedObject;
  18963. bool messagePending;
  18964. ChangeListenerList (const ChangeListenerList&);
  18965. const ChangeListenerList& operator= (const ChangeListenerList&);
  18966. };
  18967. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18968. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18969. /** Manages a list of ChangeListeners, and can send them messages.
  18970. To quickly add methods to your class that can add/remove change
  18971. listeners and broadcast to them, you can derive from this.
  18972. @see ChangeListenerList, ChangeListener
  18973. */
  18974. class JUCE_API ChangeBroadcaster
  18975. {
  18976. public:
  18977. /** Creates an ChangeBroadcaster. */
  18978. ChangeBroadcaster() throw();
  18979. /** Destructor. */
  18980. virtual ~ChangeBroadcaster();
  18981. /** Adds a listener to the list.
  18982. (Trying to add a listener that's already on the list will have no effect).
  18983. */
  18984. void addChangeListener (ChangeListener* const listener) throw();
  18985. /** Removes a listener from the list.
  18986. If the listener isn't on the list, this won't have any effect.
  18987. */
  18988. void removeChangeListener (ChangeListener* const listener) throw();
  18989. /** Removes all listeners from the list. */
  18990. void removeAllChangeListeners() throw();
  18991. /** Broadcasts a change message to all the registered listeners.
  18992. The message will be delivered asynchronously by the event thread, so this
  18993. method will not directly call any of the listeners. For a synchronous
  18994. message, use sendSynchronousChangeMessage().
  18995. @see ChangeListenerList::sendActionMessage
  18996. */
  18997. void sendChangeMessage (void* objectThatHasChanged) throw();
  18998. /** Sends a synchronous change message to all the registered listeners.
  18999. @see ChangeListenerList::sendSynchronousChangeMessage
  19000. */
  19001. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  19002. /** If a change message has been sent but not yet dispatched, this will
  19003. use sendSynchronousChangeMessage() to make the callback immediately.
  19004. */
  19005. void dispatchPendingMessages();
  19006. private:
  19007. ChangeListenerList changeListenerList;
  19008. ChangeBroadcaster (const ChangeBroadcaster&);
  19009. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  19010. };
  19011. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  19012. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  19013. /** Wrapper on a file that stores a list of key/value data pairs.
  19014. Useful for storing application settings, etc. See the PropertySet class for
  19015. the interfaces that read and write values.
  19016. Not designed for very large amounts of data, as it keeps all the values in
  19017. memory and writes them out to disk lazily when they are changed.
  19018. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  19019. with it, and these will be signalled when a value changes.
  19020. @see PropertySet
  19021. */
  19022. class JUCE_API PropertiesFile : public PropertySet,
  19023. public ChangeBroadcaster,
  19024. private Timer
  19025. {
  19026. public:
  19027. enum FileFormatOptions
  19028. {
  19029. ignoreCaseOfKeyNames = 1,
  19030. storeAsBinary = 2,
  19031. storeAsCompressedBinary = 4,
  19032. storeAsXML = 8
  19033. };
  19034. /**
  19035. Creates a PropertiesFile object.
  19036. @param file the file to use
  19037. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  19038. is changed, the object will wait for this amount
  19039. of time and then save the file. If zero, the file
  19040. will be written to disk immediately on being changed
  19041. (which might be slow, as it'll re-write synchronously
  19042. each time a value-change method is called). If it is
  19043. less than zero, the file won't be saved until
  19044. save() or saveIfNeeded() are explicitly called.
  19045. @param options a combination of the flags in the FileFormatOptions
  19046. enum, which specify the type of file to save, and other
  19047. options.
  19048. */
  19049. PropertiesFile (const File& file,
  19050. const int millisecondsBeforeSaving,
  19051. const int options) throw();
  19052. /** Destructor.
  19053. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  19054. */
  19055. ~PropertiesFile();
  19056. /** This will flush all the values to disk if they've changed since the last
  19057. time they were saved.
  19058. Returns false if it fails to write to the file for some reason (maybe because
  19059. it's read-only or the directory doesn't exist or something).
  19060. @see save
  19061. */
  19062. bool saveIfNeeded();
  19063. /** This will force a write-to-disk of the current values, regardless of whether
  19064. anything has changed since the last save.
  19065. Returns false if it fails to write to the file for some reason (maybe because
  19066. it's read-only or the directory doesn't exist or something).
  19067. @see saveIfNeeded
  19068. */
  19069. bool save();
  19070. /** Returns true if the properties have been altered since the last time they were
  19071. saved.
  19072. */
  19073. bool needsToBeSaved() const throw();
  19074. /** Returns the file that's being used. */
  19075. const File getFile() const throw();
  19076. /** Handy utility to create a properties file in whatever the standard OS-specific
  19077. location is for these things.
  19078. This uses getDefaultAppSettingsFile() to decide what file to create, then
  19079. creates a PropertiesFile object with the specified properties. See
  19080. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  19081. what the parameters do.
  19082. @see getDefaultAppSettingsFile
  19083. */
  19084. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  19085. const String& fileNameSuffix,
  19086. const String& folderName,
  19087. const bool commonToAllUsers,
  19088. const int millisecondsBeforeSaving,
  19089. const int propertiesFileOptions);
  19090. /** Handy utility to choose a file in the standard OS-dependent location for application
  19091. settings files.
  19092. So on a Mac, this will return a file called:
  19093. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  19094. On Windows it'll return something like:
  19095. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  19096. On Linux it'll return
  19097. ~/.[folderName]/[applicationName].[fileNameSuffix]
  19098. If you pass an empty string as the folder name, it'll use the app name for this (or
  19099. omit the folder name on the Mac).
  19100. If commonToAllUsers is true, then this will return the same file for all users of the
  19101. computer, regardless of the current user. If it is false, the file will be specific to
  19102. only the current user. Use this to choose whether you're saving settings that are common
  19103. or user-specific.
  19104. */
  19105. static const File getDefaultAppSettingsFile (const String& applicationName,
  19106. const String& fileNameSuffix,
  19107. const String& folderName,
  19108. const bool commonToAllUsers);
  19109. juce_UseDebuggingNewOperator
  19110. protected:
  19111. virtual void propertyChanged();
  19112. private:
  19113. File file;
  19114. int timerInterval;
  19115. const int options;
  19116. bool needsWriting;
  19117. void timerCallback();
  19118. PropertiesFile (const PropertiesFile&);
  19119. const PropertiesFile& operator= (const PropertiesFile&);
  19120. };
  19121. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  19122. /********* End of inlined file: juce_PropertiesFile.h *********/
  19123. /**
  19124. Manages a collection of properties.
  19125. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  19126. as a singleton.
  19127. It holds two different PropertiesFile objects internally, one for user-specific
  19128. settings (stored in your user directory), and one for settings that are common to
  19129. all users (stored in a folder accessible to all users).
  19130. The class manages the creation of these files on-demand, allowing access via the
  19131. getUserSettings() and getCommonSettings() methods. It also has a few handy
  19132. methods like testWriteAccess() to check that the files can be saved.
  19133. If you're using one of these as a singleton, then your app's start-up code should
  19134. first of all call setStorageParameters() to tell it the parameters to use to create
  19135. the properties files.
  19136. @see PropertiesFile
  19137. */
  19138. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  19139. {
  19140. public:
  19141. /**
  19142. Creates an ApplicationProperties object.
  19143. Before using it, you must call setStorageParameters() to give it the info
  19144. it needs to create the property files.
  19145. */
  19146. ApplicationProperties() throw();
  19147. /** Destructor.
  19148. */
  19149. ~ApplicationProperties();
  19150. juce_DeclareSingleton (ApplicationProperties, false)
  19151. /** Gives the object the information it needs to create the appropriate properties files.
  19152. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  19153. info about how these parameters are used.
  19154. */
  19155. void setStorageParameters (const String& applicationName,
  19156. const String& fileNameSuffix,
  19157. const String& folderName,
  19158. const int millisecondsBeforeSaving,
  19159. const int propertiesFileOptions) throw();
  19160. /** Tests whether the files can be successfully written to, and can show
  19161. an error message if not.
  19162. Returns true if none of the tests fail.
  19163. @param testUserSettings if true, the user settings file will be tested
  19164. @param testCommonSettings if true, the common settings file will be tested
  19165. @param showWarningDialogOnFailure if true, the method will show a helpful error
  19166. message box if either of the tests fail
  19167. */
  19168. bool testWriteAccess (const bool testUserSettings,
  19169. const bool testCommonSettings,
  19170. const bool showWarningDialogOnFailure);
  19171. /** Returns the user settings file.
  19172. The first time this is called, it will create and load the properties file.
  19173. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  19174. the common settings are used as a second-chance place to look. This is done via the
  19175. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  19176. to the fallback for the user settings.
  19177. @see getCommonSettings
  19178. */
  19179. PropertiesFile* getUserSettings() throw();
  19180. /** Returns the common settings file.
  19181. The first time this is called, it will create and load the properties file.
  19182. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  19183. read-only (e.g. because the user doesn't have permission to write
  19184. to shared files), then this will return the user settings instead,
  19185. (like getUserSettings() would do). This is handy if you'd like to
  19186. write a value to the common settings, but if that's no possible,
  19187. then you'd rather write to the user settings than none at all.
  19188. If returnUserPropsIfReadOnly is false, this method will always return
  19189. the common settings, even if any changes to them can't be saved.
  19190. @see getUserSettings
  19191. */
  19192. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  19193. /** Saves both files if they need to be saved.
  19194. @see PropertiesFile::saveIfNeeded
  19195. */
  19196. bool saveIfNeeded();
  19197. /** Flushes and closes both files if they are open.
  19198. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  19199. and closes both files. They will then be re-opened the next time getUserSettings()
  19200. or getCommonSettings() is called.
  19201. */
  19202. void closeFiles();
  19203. juce_UseDebuggingNewOperator
  19204. private:
  19205. PropertiesFile* userProps;
  19206. PropertiesFile* commonProps;
  19207. String appName, fileSuffix, folderName;
  19208. int msBeforeSaving, options;
  19209. int commonSettingsAreReadOnly;
  19210. ApplicationProperties (const ApplicationProperties&);
  19211. const ApplicationProperties& operator= (const ApplicationProperties&);
  19212. void openFiles() throw();
  19213. };
  19214. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19215. /********* End of inlined file: juce_ApplicationProperties.h *********/
  19216. #endif
  19217. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  19218. /********* Start of inlined file: juce_MidiBuffer.h *********/
  19219. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  19220. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  19221. /********* Start of inlined file: juce_MidiMessage.h *********/
  19222. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19223. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  19224. /**
  19225. Encapsulates a MIDI message.
  19226. @see MidiMessageSequence, MidiOutput, MidiInput
  19227. */
  19228. class JUCE_API MidiMessage
  19229. {
  19230. public:
  19231. /** Creates a 3-byte short midi message.
  19232. @param byte1 message byte 1
  19233. @param byte2 message byte 2
  19234. @param byte3 message byte 3
  19235. @param timeStamp the time to give the midi message - this value doesn't
  19236. use any particular units, so will be application-specific
  19237. */
  19238. MidiMessage (const int byte1,
  19239. const int byte2,
  19240. const int byte3,
  19241. const double timeStamp = 0) throw();
  19242. /** Creates a 2-byte short midi message.
  19243. @param byte1 message byte 1
  19244. @param byte2 message byte 2
  19245. @param timeStamp the time to give the midi message - this value doesn't
  19246. use any particular units, so will be application-specific
  19247. */
  19248. MidiMessage (const int byte1,
  19249. const int byte2,
  19250. const double timeStamp = 0) throw();
  19251. /** Creates a 1-byte short midi message.
  19252. @param byte1 message byte 1
  19253. @param timeStamp the time to give the midi message - this value doesn't
  19254. use any particular units, so will be application-specific
  19255. */
  19256. MidiMessage (const int byte1,
  19257. const double timeStamp = 0) throw();
  19258. /** Creates a midi message from a block of data. */
  19259. MidiMessage (const uint8* const data,
  19260. const int dataSize,
  19261. const double timeStamp = 0) throw();
  19262. /** Reads the next midi message from some data.
  19263. This will read as many bytes from a data stream as it needs to make a
  19264. complete message, and will return the number of bytes it used. This lets
  19265. you read a sequence of midi messages from a file or stream.
  19266. @param data the data to read from
  19267. @param size the maximum number of bytes it's allowed to read
  19268. @param numBytesUsed returns the number of bytes that were actually needed
  19269. @param lastStatusByte in a sequence of midi messages, the initial byte
  19270. can be dropped from a message if it's the same as the
  19271. first byte of the previous message, so this lets you
  19272. supply the byte to use if the first byte of the message
  19273. has in fact been dropped.
  19274. @param timeStamp the time to give the midi message - this value doesn't
  19275. use any particular units, so will be application-specific
  19276. */
  19277. MidiMessage (const uint8* data,
  19278. int size,
  19279. int& numBytesUsed,
  19280. uint8 lastStatusByte,
  19281. double timeStamp = 0) throw();
  19282. /** Creates a copy of another midi message. */
  19283. MidiMessage (const MidiMessage& other) throw();
  19284. /** Creates a copy of another midi message, with a different timestamp. */
  19285. MidiMessage (const MidiMessage& other,
  19286. const double newTimeStamp) throw();
  19287. /** Destructor. */
  19288. ~MidiMessage() throw();
  19289. /** Copies this message from another one. */
  19290. const MidiMessage& operator= (const MidiMessage& other) throw();
  19291. /** Returns a pointer to the raw midi data.
  19292. @see getRawDataSize
  19293. */
  19294. uint8* getRawData() const throw() { return data; }
  19295. /** Returns the number of bytes of data in the message.
  19296. @see getRawData
  19297. */
  19298. int getRawDataSize() const throw() { return size; }
  19299. /** Returns the timestamp associated with this message.
  19300. The exact meaning of this time and its units will vary, as messages are used in
  19301. a variety of different contexts.
  19302. If you're getting the message from a midi file, this could be a time in seconds, or
  19303. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  19304. If the message is being used in a MidiBuffer, it might indicate the number of
  19305. audio samples from the start of the buffer.
  19306. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  19307. for details of the way that it initialises this value.
  19308. @see setTimeStamp, addToTimeStamp
  19309. */
  19310. double getTimeStamp() const throw() { return timeStamp; }
  19311. /** Changes the message's associated timestamp.
  19312. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  19313. @see addToTimeStamp, getTimeStamp
  19314. */
  19315. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  19316. /** Adds a value to the message's timestamp.
  19317. The units for the timestamp will be application-specific.
  19318. */
  19319. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  19320. /** Returns the midi channel associated with the message.
  19321. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  19322. if it's a sysex)
  19323. @see isForChannel, setChannel
  19324. */
  19325. int getChannel() const throw();
  19326. /** Returns true if the message applies to the given midi channel.
  19327. @param channelNumber the channel number to look for, in the range 1 to 16
  19328. @see getChannel, setChannel
  19329. */
  19330. bool isForChannel (const int channelNumber) const throw();
  19331. /** Changes the message's midi channel.
  19332. This won't do anything for non-channel messages like sysexes.
  19333. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  19334. */
  19335. void setChannel (const int newChannelNumber) throw();
  19336. /** Returns true if this is a system-exclusive message.
  19337. */
  19338. bool isSysEx() const throw();
  19339. /** Returns a pointer to the sysex data inside the message.
  19340. If this event isn't a sysex event, it'll return 0.
  19341. @see getSysExDataSize
  19342. */
  19343. const uint8* getSysExData() const throw();
  19344. /** Returns the size of the sysex data.
  19345. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  19346. @see getSysExData
  19347. */
  19348. int getSysExDataSize() const throw();
  19349. /** Returns true if this message is a 'key-down' event.
  19350. This will return false for a note-on event with a velocity of 0.
  19351. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  19352. */
  19353. bool isNoteOn() const throw();
  19354. /** Creates a key-down message (using a floating-point velocity).
  19355. @param channel the midi channel, in the range 1 to 16
  19356. @param noteNumber the key number, 0 to 127
  19357. @param velocity in the range 0 to 1.0
  19358. @see isNoteOn
  19359. */
  19360. static const MidiMessage noteOn (const int channel,
  19361. const int noteNumber,
  19362. const float velocity) throw();
  19363. /** Creates a key-down message (using an integer velocity).
  19364. @param channel the midi channel, in the range 1 to 16
  19365. @param noteNumber the key number, 0 to 127
  19366. @param velocity in the range 0 to 127
  19367. @see isNoteOn
  19368. */
  19369. static const MidiMessage noteOn (const int channel,
  19370. const int noteNumber,
  19371. const uint8 velocity) throw();
  19372. /** Returns true if this message is a 'key-up' event.
  19373. This will also return true for a note-on event with a velocity of 0.
  19374. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  19375. */
  19376. bool isNoteOff() const throw();
  19377. /** Creates a key-up message.
  19378. @param channel the midi channel, in the range 1 to 16
  19379. @param noteNumber the key number, 0 to 127
  19380. @see isNoteOff
  19381. */
  19382. static const MidiMessage noteOff (const int channel,
  19383. const int noteNumber) throw();
  19384. /** Returns true if this message is a 'key-down' or 'key-up' event.
  19385. @see isNoteOn, isNoteOff
  19386. */
  19387. bool isNoteOnOrOff() const throw();
  19388. /** Returns the midi note number for note-on and note-off messages.
  19389. If the message isn't a note-on or off, the value returned will be
  19390. meaningless.
  19391. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  19392. */
  19393. int getNoteNumber() const throw();
  19394. /** Changes the midi note number of a note-on or note-off message.
  19395. If the message isn't a note on or off, this will do nothing.
  19396. */
  19397. void setNoteNumber (const int newNoteNumber) throw();
  19398. /** Returns the velocity of a note-on or note-off message.
  19399. The value returned will be in the range 0 to 127.
  19400. If the message isn't a note-on or off event, it will return 0.
  19401. @see getFloatVelocity
  19402. */
  19403. uint8 getVelocity() const throw();
  19404. /** Returns the velocity of a note-on or note-off message.
  19405. The value returned will be in the range 0 to 1.0
  19406. If the message isn't a note-on or off event, it will return 0.
  19407. @see getVelocity, setVelocity
  19408. */
  19409. float getFloatVelocity() const throw();
  19410. /** Changes the velocity of a note-on or note-off message.
  19411. If the message isn't a note on or off, this will do nothing.
  19412. @param newVelocity the new velocity, in the range 0 to 1.0
  19413. @see getFloatVelocity, multiplyVelocity
  19414. */
  19415. void setVelocity (const float newVelocity) throw();
  19416. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  19417. If the message isn't a note on or off, this will do nothing.
  19418. @param scaleFactor the value by which to multiply the velocity
  19419. @see setVelocity
  19420. */
  19421. void multiplyVelocity (const float scaleFactor) throw();
  19422. /** Returns true if the message is a program (patch) change message.
  19423. @see getProgramChangeNumber, getGMInstrumentName
  19424. */
  19425. bool isProgramChange() const throw();
  19426. /** Returns the new program number of a program change message.
  19427. If the message isn't a program change, the value returned will be
  19428. nonsense.
  19429. @see isProgramChange, getGMInstrumentName
  19430. */
  19431. int getProgramChangeNumber() const throw();
  19432. /** Creates a program-change message.
  19433. @param channel the midi channel, in the range 1 to 16
  19434. @param programNumber the midi program number, 0 to 127
  19435. @see isProgramChange, getGMInstrumentName
  19436. */
  19437. static const MidiMessage programChange (const int channel,
  19438. const int programNumber) throw();
  19439. /** Returns true if the message is a pitch-wheel move.
  19440. @see getPitchWheelValue, pitchWheel
  19441. */
  19442. bool isPitchWheel() const throw();
  19443. /** Returns the pitch wheel position from a pitch-wheel move message.
  19444. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  19445. If called for messages which aren't pitch wheel events, the number returned will be
  19446. nonsense.
  19447. @see isPitchWheel
  19448. */
  19449. int getPitchWheelValue() const throw();
  19450. /** Creates a pitch-wheel move message.
  19451. @param channel the midi channel, in the range 1 to 16
  19452. @param position the wheel position, in the range 0 to 16383
  19453. @see isPitchWheel
  19454. */
  19455. static const MidiMessage pitchWheel (const int channel,
  19456. const int position) throw();
  19457. /** Returns true if the message is an aftertouch event.
  19458. For aftertouch events, use the getNoteNumber() method to find out the key
  19459. that it applies to, and getAftertouchValue() to find out the amount. Use
  19460. getChannel() to find out the channel.
  19461. @see getAftertouchValue, getNoteNumber
  19462. */
  19463. bool isAftertouch() const throw();
  19464. /** Returns the amount of aftertouch from an aftertouch messages.
  19465. The value returned is in the range 0 to 127, and will be nonsense for messages
  19466. other than aftertouch messages.
  19467. @see isAftertouch
  19468. */
  19469. int getAfterTouchValue() const throw();
  19470. /** Creates an aftertouch message.
  19471. @param channel the midi channel, in the range 1 to 16
  19472. @param noteNumber the key number, 0 to 127
  19473. @param aftertouchAmount the amount of aftertouch, 0 to 127
  19474. @see isAftertouch
  19475. */
  19476. static const MidiMessage aftertouchChange (const int channel,
  19477. const int noteNumber,
  19478. const int aftertouchAmount) throw();
  19479. /** Returns true if the message is a channel-pressure change event.
  19480. This is like aftertouch, but common to the whole channel rather than a specific
  19481. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  19482. to find out the channel.
  19483. @see channelPressureChange
  19484. */
  19485. bool isChannelPressure() const throw();
  19486. /** Returns the pressure from a channel pressure change message.
  19487. @returns the pressure, in the range 0 to 127
  19488. @see isChannelPressure, channelPressureChange
  19489. */
  19490. int getChannelPressureValue() const throw();
  19491. /** Creates a channel-pressure change event.
  19492. @param channel the midi channel: 1 to 16
  19493. @param pressure the pressure, 0 to 127
  19494. @see isChannelPressure
  19495. */
  19496. static const MidiMessage channelPressureChange (const int channel,
  19497. const int pressure) throw();
  19498. /** Returns true if this is a midi controller message.
  19499. @see getControllerNumber, getControllerValue, controllerEvent
  19500. */
  19501. bool isController() const throw();
  19502. /** Returns the controller number of a controller message.
  19503. The name of the controller can be looked up using the getControllerName() method.
  19504. Note that the value returned is invalid for messages that aren't controller changes.
  19505. @see isController, getControllerName, getControllerValue
  19506. */
  19507. int getControllerNumber() const throw();
  19508. /** Returns the controller value from a controller message.
  19509. A value 0 to 127 is returned to indicate the new controller position.
  19510. Note that the value returned is invalid for messages that aren't controller changes.
  19511. @see isController, getControllerNumber
  19512. */
  19513. int getControllerValue() const throw();
  19514. /** Creates a controller message.
  19515. @param channel the midi channel, in the range 1 to 16
  19516. @param controllerType the type of controller
  19517. @param value the controller value
  19518. @see isController
  19519. */
  19520. static const MidiMessage controllerEvent (const int channel,
  19521. const int controllerType,
  19522. const int value) throw();
  19523. /** Checks whether this message is an all-notes-off message.
  19524. @see allNotesOff
  19525. */
  19526. bool isAllNotesOff() const throw();
  19527. /** Checks whether this message is an all-sound-off message.
  19528. @see allSoundOff
  19529. */
  19530. bool isAllSoundOff() const throw();
  19531. /** Creates an all-notes-off message.
  19532. @param channel the midi channel, in the range 1 to 16
  19533. @see isAllNotesOff
  19534. */
  19535. static const MidiMessage allNotesOff (const int channel) throw();
  19536. /** Creates an all-sound-off message.
  19537. @param channel the midi channel, in the range 1 to 16
  19538. @see isAllSoundOff
  19539. */
  19540. static const MidiMessage allSoundOff (const int channel) throw();
  19541. /** Creates an all-controllers-off message.
  19542. @param channel the midi channel, in the range 1 to 16
  19543. */
  19544. static const MidiMessage allControllersOff (const int channel) throw();
  19545. /** Returns true if this event is a meta-event.
  19546. Meta-events are things like tempo changes, track names, etc.
  19547. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  19548. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  19549. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  19550. */
  19551. bool isMetaEvent() const throw();
  19552. /** Returns a meta-event's type number.
  19553. If the message isn't a meta-event, this will return -1.
  19554. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  19555. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  19556. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  19557. */
  19558. int getMetaEventType() const throw();
  19559. /** Returns a pointer to the data in a meta-event.
  19560. @see isMetaEvent, getMetaEventLength
  19561. */
  19562. const uint8* getMetaEventData() const throw();
  19563. /** Returns the length of the data for a meta-event.
  19564. @see isMetaEvent, getMetaEventData
  19565. */
  19566. int getMetaEventLength() const throw();
  19567. /** Returns true if this is a 'track' meta-event. */
  19568. bool isTrackMetaEvent() const throw();
  19569. /** Returns true if this is an 'end-of-track' meta-event. */
  19570. bool isEndOfTrackMetaEvent() const throw();
  19571. /** Creates an end-of-track meta-event.
  19572. @see isEndOfTrackMetaEvent
  19573. */
  19574. static const MidiMessage endOfTrack() throw();
  19575. /** Returns true if this is an 'track name' meta-event.
  19576. You can use the getTextFromTextMetaEvent() method to get the track's name.
  19577. */
  19578. bool isTrackNameEvent() const throw();
  19579. /** Returns true if this is a 'text' meta-event.
  19580. @see getTextFromTextMetaEvent
  19581. */
  19582. bool isTextMetaEvent() const throw();
  19583. /** Returns the text from a text meta-event.
  19584. @see isTextMetaEvent
  19585. */
  19586. const String getTextFromTextMetaEvent() const throw();
  19587. /** Returns true if this is a 'tempo' meta-event.
  19588. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  19589. */
  19590. bool isTempoMetaEvent() const throw();
  19591. /** Returns the tick length from a tempo meta-event.
  19592. @param timeFormat the 16-bit time format value from the midi file's header.
  19593. @returns the tick length (in seconds).
  19594. @see isTempoMetaEvent
  19595. */
  19596. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  19597. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  19598. @see isTempoMetaEvent, getTempoMetaEventTickLength
  19599. */
  19600. double getTempoSecondsPerQuarterNote() const throw();
  19601. /** Creates a tempo meta-event.
  19602. @see isTempoMetaEvent
  19603. */
  19604. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  19605. /** Returns true if this is a 'time-signature' meta-event.
  19606. @see getTimeSignatureInfo
  19607. */
  19608. bool isTimeSignatureMetaEvent() const throw();
  19609. /** Returns the time-signature values from a time-signature meta-event.
  19610. @see isTimeSignatureMetaEvent
  19611. */
  19612. void getTimeSignatureInfo (int& numerator,
  19613. int& denominator) const throw();
  19614. /** Creates a time-signature meta-event.
  19615. @see isTimeSignatureMetaEvent
  19616. */
  19617. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  19618. const int denominator) throw();
  19619. /** Returns true if this is a 'key-signature' meta-event.
  19620. @see getKeySignatureNumberOfSharpsOrFlats
  19621. */
  19622. bool isKeySignatureMetaEvent() const throw();
  19623. /** Returns the key from a key-signature meta-event.
  19624. @see isKeySignatureMetaEvent
  19625. */
  19626. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  19627. /** Returns true if this is a 'channel' meta-event.
  19628. A channel meta-event specifies the midi channel that should be used
  19629. for subsequent meta-events.
  19630. @see getMidiChannelMetaEventChannel
  19631. */
  19632. bool isMidiChannelMetaEvent() const throw();
  19633. /** Returns the channel number from a channel meta-event.
  19634. @returns the channel, in the range 1 to 16.
  19635. @see isMidiChannelMetaEvent
  19636. */
  19637. int getMidiChannelMetaEventChannel() const throw();
  19638. /** Creates a midi channel meta-event.
  19639. @param channel the midi channel, in the range 1 to 16
  19640. @see isMidiChannelMetaEvent
  19641. */
  19642. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  19643. /** Returns true if this is an active-sense message. */
  19644. bool isActiveSense() const throw();
  19645. /** Returns true if this is a midi start event.
  19646. @see midiStart
  19647. */
  19648. bool isMidiStart() const throw();
  19649. /** Creates a midi start event. */
  19650. static const MidiMessage midiStart() throw();
  19651. /** Returns true if this is a midi continue event.
  19652. @see midiContinue
  19653. */
  19654. bool isMidiContinue() const throw();
  19655. /** Creates a midi continue event. */
  19656. static const MidiMessage midiContinue() throw();
  19657. /** Returns true if this is a midi stop event.
  19658. @see midiStop
  19659. */
  19660. bool isMidiStop() const throw();
  19661. /** Creates a midi stop event. */
  19662. static const MidiMessage midiStop() throw();
  19663. /** Returns true if this is a midi clock event.
  19664. @see midiClock, songPositionPointer
  19665. */
  19666. bool isMidiClock() const throw();
  19667. /** Creates a midi clock event. */
  19668. static const MidiMessage midiClock() throw();
  19669. /** Returns true if this is a song-position-pointer message.
  19670. @see getSongPositionPointerMidiBeat, songPositionPointer
  19671. */
  19672. bool isSongPositionPointer() const throw();
  19673. /** Returns the midi beat-number of a song-position-pointer message.
  19674. @see isSongPositionPointer, songPositionPointer
  19675. */
  19676. int getSongPositionPointerMidiBeat() const throw();
  19677. /** Creates a song-position-pointer message.
  19678. The position is a number of midi beats from the start of the song, where 1 midi
  19679. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  19680. are 4 midi beats in a quarter-note.
  19681. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  19682. */
  19683. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  19684. /** Returns true if this is a quarter-frame midi timecode message.
  19685. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  19686. */
  19687. bool isQuarterFrame() const throw();
  19688. /** Returns the sequence number of a quarter-frame midi timecode message.
  19689. This will be a value between 0 and 7.
  19690. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  19691. */
  19692. int getQuarterFrameSequenceNumber() const throw();
  19693. /** Returns the value from a quarter-frame message.
  19694. This will be the lower nybble of the message's data-byte, a value
  19695. between 0 and 15
  19696. */
  19697. int getQuarterFrameValue() const throw();
  19698. /** Creates a quarter-frame MTC message.
  19699. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  19700. @param value a value 0 to 15 for the lower nybble of the message's data byte
  19701. */
  19702. static const MidiMessage quarterFrame (const int sequenceNumber,
  19703. const int value) throw();
  19704. /** SMPTE timecode types.
  19705. Used by the getFullFrameParameters() and fullFrame() methods.
  19706. */
  19707. enum SmpteTimecodeType
  19708. {
  19709. fps24 = 0,
  19710. fps25 = 1,
  19711. fps30drop = 2,
  19712. fps30 = 3
  19713. };
  19714. /** Returns true if this is a full-frame midi timecode message.
  19715. */
  19716. bool isFullFrame() const throw();
  19717. /** Extracts the timecode information from a full-frame midi timecode message.
  19718. You should only call this on messages where you've used isFullFrame() to
  19719. check that they're the right kind.
  19720. */
  19721. void getFullFrameParameters (int& hours,
  19722. int& minutes,
  19723. int& seconds,
  19724. int& frames,
  19725. SmpteTimecodeType& timecodeType) const throw();
  19726. /** Creates a full-frame MTC message.
  19727. */
  19728. static const MidiMessage fullFrame (const int hours,
  19729. const int minutes,
  19730. const int seconds,
  19731. const int frames,
  19732. SmpteTimecodeType timecodeType);
  19733. /** Types of MMC command.
  19734. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  19735. */
  19736. enum MidiMachineControlCommand
  19737. {
  19738. mmc_stop = 1,
  19739. mmc_play = 2,
  19740. mmc_deferredplay = 3,
  19741. mmc_fastforward = 4,
  19742. mmc_rewind = 5,
  19743. mmc_recordStart = 6,
  19744. mmc_recordStop = 7,
  19745. mmc_pause = 9
  19746. };
  19747. /** Checks whether this is an MMC message.
  19748. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  19749. */
  19750. bool isMidiMachineControlMessage() const throw();
  19751. /** For an MMC message, this returns its type.
  19752. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  19753. calling this method.
  19754. */
  19755. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  19756. /** Creates an MMC message.
  19757. */
  19758. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  19759. /** Checks whether this is an MMC "goto" message.
  19760. If it is, the parameters passed-in are set to the time that the message contains.
  19761. @see midiMachineControlGoto
  19762. */
  19763. bool isMidiMachineControlGoto (int& hours,
  19764. int& minutes,
  19765. int& seconds,
  19766. int& frames) const throw();
  19767. /** Creates an MMC "goto" message.
  19768. This messages tells the device to go to a specific frame.
  19769. @see isMidiMachineControlGoto
  19770. */
  19771. static const MidiMessage midiMachineControlGoto (int hours,
  19772. int minutes,
  19773. int seconds,
  19774. int frames);
  19775. /** Creates a master-volume change message.
  19776. @param volume the volume, 0 to 1.0
  19777. */
  19778. static const MidiMessage masterVolume (const float volume) throw();
  19779. /** Creates a system-exclusive message.
  19780. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19781. */
  19782. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19783. const int dataSize) throw();
  19784. /** Reads a midi variable-length integer.
  19785. @param data the data to read the number from
  19786. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19787. */
  19788. static int readVariableLengthVal (const uint8* data,
  19789. int& numBytesUsed) throw();
  19790. /** Based on the first byte of a short midi message, this uses a lookup table
  19791. to return the message length (either 1, 2, or 3 bytes).
  19792. The value passed in must be 0x80 or higher.
  19793. */
  19794. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19795. /** Returns the name of a midi note number.
  19796. E.g "C", "D#", etc.
  19797. @param noteNumber the midi note number, 0 to 127
  19798. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19799. they'll be flattened, e.g. "Db"
  19800. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19801. e.g. "C#4"
  19802. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19803. number that will be used for middle C's octave
  19804. @see getMidiNoteInHertz
  19805. */
  19806. static const String getMidiNoteName (int noteNumber,
  19807. bool useSharps,
  19808. bool includeOctaveNumber,
  19809. int octaveNumForMiddleC) throw();
  19810. /** Returns the frequency of a midi note number.
  19811. @see getMidiNoteName
  19812. */
  19813. static const double getMidiNoteInHertz (int noteNumber) throw();
  19814. /** Returns the standard name of a GM instrument.
  19815. @param midiInstrumentNumber the program number 0 to 127
  19816. @see getProgramChangeNumber
  19817. */
  19818. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19819. /** Returns the name of a bank of GM instruments.
  19820. @param midiBankNumber the bank, 0 to 15
  19821. */
  19822. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19823. /** Returns the standard name of a channel 10 percussion sound.
  19824. @param midiNoteNumber the key number, 35 to 81
  19825. */
  19826. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19827. /** Returns the name of a controller type number.
  19828. @see getControllerNumber
  19829. */
  19830. static const String getControllerName (int controllerNumber) throw();
  19831. juce_UseDebuggingNewOperator
  19832. private:
  19833. double timeStamp;
  19834. uint8* data;
  19835. int message, size;
  19836. };
  19837. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19838. /********* End of inlined file: juce_MidiMessage.h *********/
  19839. /**
  19840. Holds a sequence of time-stamped midi events.
  19841. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19842. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19843. @see MidiMessage
  19844. */
  19845. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19846. {
  19847. public:
  19848. /** Creates an empty MidiBuffer. */
  19849. MidiBuffer() throw();
  19850. /** Creates a MidiBuffer containing a single midi message. */
  19851. MidiBuffer (const MidiMessage& message) throw();
  19852. /** Creates a copy of another MidiBuffer. */
  19853. MidiBuffer (const MidiBuffer& other) throw();
  19854. /** Makes a copy of another MidiBuffer. */
  19855. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19856. /** Destructor */
  19857. ~MidiBuffer() throw();
  19858. /** Removes all events from the buffer. */
  19859. void clear() throw();
  19860. /** Removes all events between two times from the buffer.
  19861. All events for which (start <= event position < start + numSamples) will
  19862. be removed.
  19863. */
  19864. void clear (const int start,
  19865. const int numSamples) throw();
  19866. /** Returns true if the buffer is empty.
  19867. To actually retrieve the events, use a MidiBuffer::Iterator object
  19868. */
  19869. bool isEmpty() const throw();
  19870. /** Counts the number of events in the buffer.
  19871. This is actually quite a slow operation, as it has to iterate through all
  19872. the events, so you might prefer to call isEmpty() if that's all you need
  19873. to know.
  19874. */
  19875. int getNumEvents() const throw();
  19876. /** Adds an event to the buffer.
  19877. The sample number will be used to determine the position of the event in
  19878. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19879. ignored.
  19880. If an event is added whose sample position is the same as one or more events
  19881. already in the buffer, the new event will be placed after the existing ones.
  19882. To retrieve events, use a MidiBuffer::Iterator object
  19883. */
  19884. void addEvent (const MidiMessage& midiMessage,
  19885. const int sampleNumber) throw();
  19886. /** Adds an event to the buffer from raw midi data.
  19887. The sample number will be used to determine the position of the event in
  19888. the buffer, which is always kept sorted.
  19889. If an event is added whose sample position is the same as one or more events
  19890. already in the buffer, the new event will be placed after the existing ones.
  19891. The event data will be inspected to calculate the number of bytes in length that
  19892. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19893. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19894. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19895. add an event at all.
  19896. To retrieve events, use a MidiBuffer::Iterator object
  19897. */
  19898. void addEvent (const uint8* const rawMidiData,
  19899. const int maxBytesOfMidiData,
  19900. const int sampleNumber) throw();
  19901. /** Adds some events from another buffer to this one.
  19902. @param otherBuffer the buffer containing the events you want to add
  19903. @param startSample the lowest sample number in the source buffer for which
  19904. events should be added. Any source events whose timestamp is
  19905. less than this will be ignored
  19906. @param numSamples the valid range of samples from the source buffer for which
  19907. events should be added - i.e. events in the source buffer whose
  19908. timestamp is greater than or equal to (startSample + numSamples)
  19909. will be ignored. If this value is less than 0, all events after
  19910. startSample will be taken.
  19911. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19912. that are added to this buffer
  19913. */
  19914. void addEvents (const MidiBuffer& otherBuffer,
  19915. const int startSample,
  19916. const int numSamples,
  19917. const int sampleDeltaToAdd) throw();
  19918. /** Returns the sample number of the first event in the buffer.
  19919. If the buffer's empty, this will just return 0.
  19920. */
  19921. int getFirstEventTime() const throw();
  19922. /** Returns the sample number of the last event in the buffer.
  19923. If the buffer's empty, this will just return 0.
  19924. */
  19925. int getLastEventTime() const throw();
  19926. /** Exchanges the contents of this buffer with another one.
  19927. This is a quick operation, because no memory allocating or copying is done, it
  19928. just swaps the internal state of the two buffers.
  19929. */
  19930. void swap (MidiBuffer& other);
  19931. /**
  19932. Used to iterate through the events in a MidiBuffer.
  19933. Note that altering the buffer while an iterator is using it isn't a
  19934. safe operation.
  19935. @see MidiBuffer
  19936. */
  19937. class Iterator
  19938. {
  19939. public:
  19940. /** Creates an Iterator for this MidiBuffer. */
  19941. Iterator (const MidiBuffer& buffer) throw();
  19942. /** Destructor. */
  19943. ~Iterator() throw();
  19944. /** Repositions the iterator so that the next event retrieved will be the first
  19945. one whose sample position is at greater than or equal to the given position.
  19946. */
  19947. void setNextSamplePosition (const int samplePosition) throw();
  19948. /** Retrieves a copy of the next event from the buffer.
  19949. @param result on return, this will be the message (the MidiMessage's timestamp
  19950. is not set)
  19951. @param samplePosition on return, this will be the position of the event
  19952. @returns true if an event was found, or false if the iterator has reached
  19953. the end of the buffer
  19954. */
  19955. bool getNextEvent (MidiMessage& result,
  19956. int& samplePosition) throw();
  19957. /** Retrieves the next event from the buffer.
  19958. @param midiData on return, this pointer will be set to a block of data containing
  19959. the midi message. Note that to make it fast, this is a pointer
  19960. directly into the MidiBuffer's internal data, so is only valid
  19961. temporarily until the MidiBuffer is altered.
  19962. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19963. midi message
  19964. @param samplePosition on return, this will be the position of the event
  19965. @returns true if an event was found, or false if the iterator has reached
  19966. the end of the buffer
  19967. */
  19968. bool getNextEvent (const uint8* &midiData,
  19969. int& numBytesOfMidiData,
  19970. int& samplePosition) throw();
  19971. juce_UseDebuggingNewOperator
  19972. private:
  19973. const MidiBuffer& buffer;
  19974. const uint8* data;
  19975. Iterator (const Iterator&);
  19976. const Iterator& operator= (const Iterator&);
  19977. };
  19978. juce_UseDebuggingNewOperator
  19979. private:
  19980. friend class MidiBuffer::Iterator;
  19981. int bytesUsed;
  19982. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19983. };
  19984. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19985. /********* End of inlined file: juce_MidiBuffer.h *********/
  19986. #endif
  19987. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19988. /********* Start of inlined file: juce_MidiFile.h *********/
  19989. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19990. #define __JUCE_MIDIFILE_JUCEHEADER__
  19991. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19992. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19993. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19994. /**
  19995. A sequence of timestamped midi messages.
  19996. This allows the sequence to be manipulated, and also to be read from and
  19997. written to a standard midi file.
  19998. @see MidiMessage, MidiFile
  19999. */
  20000. class JUCE_API MidiMessageSequence
  20001. {
  20002. public:
  20003. /** Creates an empty midi sequence object. */
  20004. MidiMessageSequence();
  20005. /** Creates a copy of another sequence. */
  20006. MidiMessageSequence (const MidiMessageSequence& other);
  20007. /** Replaces this sequence with another one. */
  20008. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  20009. /** Destructor. */
  20010. ~MidiMessageSequence();
  20011. /** Structure used to hold midi events in the sequence.
  20012. These structures act as 'handles' on the events as they are moved about in
  20013. the list, and make it quick to find the matching note-offs for note-on events.
  20014. @see MidiMessageSequence::getEventPointer
  20015. */
  20016. class MidiEventHolder
  20017. {
  20018. public:
  20019. /** Destructor. */
  20020. ~MidiEventHolder();
  20021. /** The message itself, whose timestamp is used to specify the event's time.
  20022. */
  20023. MidiMessage message;
  20024. /** The matching note-off event (if this is a note-on event).
  20025. If this isn't a note-on, this pointer will be null.
  20026. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  20027. note-offs up-to-date after events have been moved around in the sequence
  20028. or deleted.
  20029. */
  20030. MidiEventHolder* noteOffObject;
  20031. juce_UseDebuggingNewOperator
  20032. private:
  20033. friend class MidiMessageSequence;
  20034. MidiEventHolder (const MidiMessage& message);
  20035. };
  20036. /** Clears the sequence. */
  20037. void clear();
  20038. /** Returns the number of events in the sequence. */
  20039. int getNumEvents() const;
  20040. /** Returns a pointer to one of the events. */
  20041. MidiEventHolder* getEventPointer (const int index) const;
  20042. /** Returns the time of the note-up that matches the note-on at this index.
  20043. If the event at this index isn't a note-on, it'll just return 0.
  20044. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  20045. */
  20046. double getTimeOfMatchingKeyUp (const int index) const;
  20047. /** Returns the index of the note-up that matches the note-on at this index.
  20048. If the event at this index isn't a note-on, it'll just return -1.
  20049. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  20050. */
  20051. int getIndexOfMatchingKeyUp (const int index) const;
  20052. /** Returns the index of an event. */
  20053. int getIndexOf (MidiEventHolder* const event) const;
  20054. /** Returns the index of the first event on or after the given timestamp.
  20055. If the time is beyond the end of the sequence, this will return the
  20056. number of events.
  20057. */
  20058. int getNextIndexAtTime (const double timeStamp) const;
  20059. /** Returns the timestamp of the first event in the sequence.
  20060. @see getEndTime
  20061. */
  20062. double getStartTime() const;
  20063. /** Returns the timestamp of the last event in the sequence.
  20064. @see getStartTime
  20065. */
  20066. double getEndTime() const;
  20067. /** Returns the timestamp of the event at a given index.
  20068. If the index is out-of-range, this will return 0.0
  20069. */
  20070. double getEventTime (const int index) const;
  20071. /** Inserts a midi message into the sequence.
  20072. The index at which the new message gets inserted will depend on its timestamp,
  20073. because the sequence is kept sorted.
  20074. Remember to call updateMatchedPairs() after adding note-on events.
  20075. @param newMessage the new message to add (an internal copy will be made)
  20076. @param timeAdjustment an optional value to add to the timestamp of the message
  20077. that will be inserted
  20078. @see updateMatchedPairs
  20079. */
  20080. void addEvent (const MidiMessage& newMessage,
  20081. double timeAdjustment = 0);
  20082. /** Deletes one of the events in the sequence.
  20083. Remember to call updateMatchedPairs() after removing events.
  20084. @param index the index of the event to delete
  20085. @param deleteMatchingNoteUp whether to also remove the matching note-off
  20086. if the event you're removing is a note-on
  20087. */
  20088. void deleteEvent (const int index,
  20089. const bool deleteMatchingNoteUp);
  20090. /** Merges another sequence into this one.
  20091. Remember to call updateMatchedPairs() after using this method.
  20092. @param other the sequence to add from
  20093. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  20094. as they are read from the other sequence
  20095. @param firstAllowableDestTime events will not be added if their time is earlier
  20096. than this time. (This is after their time has been adjusted
  20097. by the timeAdjustmentDelta)
  20098. @param endOfAllowableDestTimes events will not be added if their time is equal to
  20099. or greater than this time. (This is after their time has
  20100. been adjusted by the timeAdjustmentDelta)
  20101. */
  20102. void addSequence (const MidiMessageSequence& other,
  20103. double timeAdjustmentDelta,
  20104. double firstAllowableDestTime,
  20105. double endOfAllowableDestTimes);
  20106. /** Makes sure all the note-on and note-off pairs are up-to-date.
  20107. Call this after moving messages about or deleting/adding messages, and it
  20108. will scan the list and make sure all the note-offs in the MidiEventHolder
  20109. structures are pointing at the correct ones.
  20110. */
  20111. void updateMatchedPairs();
  20112. /** Copies all the messages for a particular midi channel to another sequence.
  20113. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  20114. @param destSequence the sequence that the chosen events should be copied to
  20115. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  20116. channel) will also be copied across.
  20117. @see extractSysExMessages
  20118. */
  20119. void extractMidiChannelMessages (const int channelNumberToExtract,
  20120. MidiMessageSequence& destSequence,
  20121. const bool alsoIncludeMetaEvents) const;
  20122. /** Copies all midi sys-ex messages to another sequence.
  20123. @param destSequence this is the sequence to which any sys-exes in this sequence
  20124. will be added
  20125. @see extractMidiChannelMessages
  20126. */
  20127. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  20128. /** Removes any messages in this sequence that have a specific midi channel.
  20129. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  20130. */
  20131. void deleteMidiChannelMessages (const int channelNumberToRemove);
  20132. /** Removes any sys-ex messages from this sequence.
  20133. */
  20134. void deleteSysExMessages();
  20135. /** Adds an offset to the timestamps of all events in the sequence.
  20136. @param deltaTime the amount to add to each timestamp.
  20137. */
  20138. void addTimeToMessages (const double deltaTime);
  20139. /** Scans through the sequence to determine the state of any midi controllers at
  20140. a given time.
  20141. This will create a sequence of midi controller changes that can be
  20142. used to set all midi controllers to the state they would be in at the
  20143. specified time within this sequence.
  20144. As well as controllers, it will also recreate the midi program number
  20145. and pitch bend position.
  20146. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  20147. for other channels will be ignored.
  20148. @param time the time at which you want to find out the state - there are
  20149. no explicit units for this time measurement, it's the same units
  20150. as used for the timestamps of the messages
  20151. @param resultMessages an array to which midi controller-change messages will be added. This
  20152. will be the minimum number of controller changes to recreate the
  20153. state at the required time.
  20154. */
  20155. void createControllerUpdatesForTime (const int channelNumber,
  20156. const double time,
  20157. OwnedArray<MidiMessage>& resultMessages);
  20158. juce_UseDebuggingNewOperator
  20159. /** @internal */
  20160. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20161. const MidiMessageSequence::MidiEventHolder* const second) throw();
  20162. private:
  20163. friend class MidiComparator;
  20164. friend class MidiFile;
  20165. OwnedArray <MidiEventHolder> list;
  20166. void sort();
  20167. };
  20168. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20169. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  20170. /**
  20171. Reads/writes standard midi format files.
  20172. To read a midi file, create a MidiFile object and call its readFrom() method. You
  20173. can then get the individual midi tracks from it using the getTrack() method.
  20174. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  20175. to it using the addTrack() method, and then call its writeTo() method to stream
  20176. it out.
  20177. @see MidiMessageSequence
  20178. */
  20179. class JUCE_API MidiFile
  20180. {
  20181. public:
  20182. /** Creates an empty MidiFile object.
  20183. */
  20184. MidiFile() throw();
  20185. /** Destructor. */
  20186. ~MidiFile() throw();
  20187. /** Returns the number of tracks in the file.
  20188. @see getTrack, addTrack
  20189. */
  20190. int getNumTracks() const throw();
  20191. /** Returns a pointer to one of the tracks in the file.
  20192. @returns a pointer to the track, or 0 if the index is out-of-range
  20193. @see getNumTracks, addTrack
  20194. */
  20195. const MidiMessageSequence* getTrack (const int index) const throw();
  20196. /** Adds a midi track to the file.
  20197. This will make its own internal copy of the sequence that is passed-in.
  20198. @see getNumTracks, getTrack
  20199. */
  20200. void addTrack (const MidiMessageSequence& trackSequence) throw();
  20201. /** Removes all midi tracks from the file.
  20202. @see getNumTracks
  20203. */
  20204. void clear() throw();
  20205. /** Returns the raw time format code that will be written to a stream.
  20206. After reading a midi file, this method will return the time-format that
  20207. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  20208. or setSmpteTimeFormat() methods.
  20209. If the value returned is positive, it indicates the number of midi ticks
  20210. per quarter-note - see setTicksPerQuarterNote().
  20211. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  20212. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  20213. */
  20214. short getTimeFormat() const throw();
  20215. /** Sets the time format to use when this file is written to a stream.
  20216. If this is called, the file will be written as bars/beats using the
  20217. specified resolution, rather than SMPTE absolute times, as would be
  20218. used if setSmpteTimeFormat() had been called instead.
  20219. @param ticksPerQuarterNote e.g. 96, 960
  20220. @see setSmpteTimeFormat
  20221. */
  20222. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  20223. /** Sets the time format to use when this file is written to a stream.
  20224. If this is called, the file will be written using absolute times, rather
  20225. than bars/beats as would be the case if setTicksPerBeat() had been called
  20226. instead.
  20227. @param framesPerSecond must be 24, 25, 29 or 30
  20228. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  20229. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  20230. timing, setSmpteTimeFormat (25, 40)
  20231. @see setTicksPerBeat
  20232. */
  20233. void setSmpteTimeFormat (const int framesPerSecond,
  20234. const int subframeResolution) throw();
  20235. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  20236. Useful for finding the positions of all the tempo changes in a file.
  20237. @param tempoChangeEvents a list to which all the events will be added
  20238. */
  20239. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  20240. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  20241. Useful for finding the positions of all the tempo changes in a file.
  20242. @param timeSigEvents a list to which all the events will be added
  20243. */
  20244. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  20245. /** Returns the latest timestamp in any of the tracks.
  20246. (Useful for finding the length of the file).
  20247. */
  20248. double getLastTimestamp() const;
  20249. /** Reads a midi file format stream.
  20250. After calling this, you can get the tracks that were read from the file by using the
  20251. getNumTracks() and getTrack() methods.
  20252. The timestamps of the midi events in the tracks will represent their positions in
  20253. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  20254. method.
  20255. @returns true if the stream was read successfully
  20256. */
  20257. bool readFrom (InputStream& sourceStream);
  20258. /** Writes the midi tracks as a standard midi file.
  20259. @returns true if the operation succeeded.
  20260. */
  20261. bool writeTo (OutputStream& destStream);
  20262. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  20263. This will use the midi time format and tempo/time signature info in the
  20264. tracks to convert all the timestamps to absolute values in seconds.
  20265. */
  20266. void convertTimestampTicksToSeconds();
  20267. juce_UseDebuggingNewOperator
  20268. /** @internal */
  20269. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20270. const MidiMessageSequence::MidiEventHolder* const second) throw();
  20271. private:
  20272. MidiMessageSequence* tracks [128];
  20273. short numTracks, timeFormat;
  20274. MidiFile (const MidiFile&);
  20275. const MidiFile& operator= (const MidiFile&);
  20276. void readNextTrack (const char* data, int size);
  20277. void writeTrack (OutputStream& mainOut, const int trackNum);
  20278. };
  20279. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  20280. /********* End of inlined file: juce_MidiFile.h *********/
  20281. #endif
  20282. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20283. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  20284. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20285. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20286. class MidiKeyboardState;
  20287. /**
  20288. Receives events from a MidiKeyboardState object.
  20289. @see MidiKeyboardState
  20290. */
  20291. class JUCE_API MidiKeyboardStateListener
  20292. {
  20293. public:
  20294. MidiKeyboardStateListener() throw() {}
  20295. virtual ~MidiKeyboardStateListener() {}
  20296. /** Called when one of the MidiKeyboardState's keys is pressed.
  20297. This will be called synchronously when the state is either processing a
  20298. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  20299. when a note is being played with its MidiKeyboardState::noteOn() method.
  20300. Note that this callback could happen from an audio callback thread, so be
  20301. careful not to block, and avoid any UI activity in the callback.
  20302. */
  20303. virtual void handleNoteOn (MidiKeyboardState* source,
  20304. int midiChannel, int midiNoteNumber, float velocity) = 0;
  20305. /** Called when one of the MidiKeyboardState's keys is released.
  20306. This will be called synchronously when the state is either processing a
  20307. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  20308. when a note is being played with its MidiKeyboardState::noteOff() method.
  20309. Note that this callback could happen from an audio callback thread, so be
  20310. careful not to block, and avoid any UI activity in the callback.
  20311. */
  20312. virtual void handleNoteOff (MidiKeyboardState* source,
  20313. int midiChannel, int midiNoteNumber) = 0;
  20314. };
  20315. /**
  20316. Represents a piano keyboard, keeping track of which keys are currently pressed.
  20317. This object can parse a stream of midi events, using them to update its idea
  20318. of which keys are pressed for each individiual midi channel.
  20319. When keys go up or down, it can broadcast these events to listener objects.
  20320. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  20321. methods, and midi messages for these events will be merged into the
  20322. midi stream that gets processed by processNextMidiBuffer().
  20323. */
  20324. class JUCE_API MidiKeyboardState
  20325. {
  20326. public:
  20327. MidiKeyboardState();
  20328. ~MidiKeyboardState();
  20329. /** Resets the state of the object.
  20330. All internal data for all the channels is reset, but no events are sent as a
  20331. result.
  20332. If you want to release any keys that are currently down, and to send out note-up
  20333. midi messages for this, use the allNotesOff() method instead.
  20334. */
  20335. void reset();
  20336. /** Returns true if the given midi key is currently held down for the given midi channel.
  20337. The channel number must be between 1 and 16. If you want to see if any notes are
  20338. on for a range of channels, use the isNoteOnForChannels() method.
  20339. */
  20340. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  20341. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  20342. The channel mask has a bit set for each midi channel you want to test for - bit
  20343. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  20344. If a note is on for at least one of the specified channels, this returns true.
  20345. */
  20346. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  20347. /** Turns a specified note on.
  20348. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  20349. next call to processNextMidiBuffer().
  20350. It will also trigger a synchronous callback to the listeners to tell them that the key has
  20351. gone down.
  20352. */
  20353. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  20354. /** Turns a specified note off.
  20355. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  20356. next call to processNextMidiBuffer().
  20357. It will also trigger a synchronous callback to the listeners to tell them that the key has
  20358. gone up.
  20359. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  20360. */
  20361. void noteOff (const int midiChannel, const int midiNoteNumber);
  20362. /** This will turn off any currently-down notes for the given midi channel.
  20363. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  20364. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  20365. and events being added to the midi stream.
  20366. */
  20367. void allNotesOff (const int midiChannel);
  20368. /** Looks at a key-up/down event and uses it to update the state of this object.
  20369. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  20370. instead.
  20371. */
  20372. void processNextMidiEvent (const MidiMessage& message);
  20373. /** Scans a midi stream for up/down events and adds its own events to it.
  20374. This will look for any up/down events and use them to update the internal state,
  20375. synchronously making suitable callbacks to the listeners.
  20376. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  20377. and noteOff() calls will be added into the buffer.
  20378. Only the section of the buffer whose timestamps are between startSample and
  20379. (startSample + numSamples) will be affected, and any events added will be placed
  20380. between these times.
  20381. If you're going to use this method, you'll need to keep calling it regularly for
  20382. it to work satisfactorily.
  20383. To process a single midi event at a time, use the processNextMidiEvent() method
  20384. instead.
  20385. */
  20386. void processNextMidiBuffer (MidiBuffer& buffer,
  20387. const int startSample,
  20388. const int numSamples,
  20389. const bool injectIndirectEvents);
  20390. /** Registers a listener for callbacks when keys go up or down.
  20391. @see removeListener
  20392. */
  20393. void addListener (MidiKeyboardStateListener* const listener) throw();
  20394. /** Deregisters a listener.
  20395. @see addListener
  20396. */
  20397. void removeListener (MidiKeyboardStateListener* const listener) throw();
  20398. juce_UseDebuggingNewOperator
  20399. private:
  20400. CriticalSection lock;
  20401. uint16 noteStates [128];
  20402. MidiBuffer eventsToAdd;
  20403. VoidArray listeners;
  20404. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  20405. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  20406. MidiKeyboardState (const MidiKeyboardState&);
  20407. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  20408. };
  20409. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20410. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  20411. #endif
  20412. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  20413. #endif
  20414. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20415. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  20416. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20417. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20418. /********* Start of inlined file: juce_MidiInput.h *********/
  20419. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  20420. #define __JUCE_MIDIINPUT_JUCEHEADER__
  20421. class MidiInput;
  20422. /**
  20423. Receives midi messages from a midi input device.
  20424. This class is overridden to handle incoming midi messages. See the MidiInput
  20425. class for more details.
  20426. @see MidiInput
  20427. */
  20428. class JUCE_API MidiInputCallback
  20429. {
  20430. public:
  20431. /** Destructor. */
  20432. virtual ~MidiInputCallback() {}
  20433. /** Receives an incoming message.
  20434. A MidiInput object will call this method when a midi event arrives. It'll be
  20435. called on a high-priority system thread, so avoid doing anything time-consuming
  20436. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  20437. for queueing incoming messages for use later.
  20438. @param source the MidiInput object that generated the message
  20439. @param message the incoming message. The message's timestamp is set to a value
  20440. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  20441. time when the message arrived.
  20442. */
  20443. virtual void handleIncomingMidiMessage (MidiInput* source,
  20444. const MidiMessage& message) = 0;
  20445. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  20446. If a long sysex message is broken up into multiple packets, this callback is made
  20447. for each packet that arrives until the message is finished, at which point
  20448. the normal handleIncomingMidiMessage() callback will be made with the entire
  20449. message.
  20450. The message passed in will contain the start of a sysex, but won't be finished
  20451. with the terminating 0xf7 byte.
  20452. */
  20453. virtual void handlePartialSysexMessage (MidiInput* source,
  20454. const uint8* messageData,
  20455. const int numBytesSoFar,
  20456. const double timestamp)
  20457. {
  20458. // (this bit is just to avoid compiler warnings about unused variables)
  20459. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  20460. }
  20461. };
  20462. /**
  20463. Represents a midi input device.
  20464. To create one of these, use the static getDevices() method to find out what inputs are
  20465. available, and then use the openDevice() method to try to open one.
  20466. @see MidiOutput
  20467. */
  20468. class JUCE_API MidiInput
  20469. {
  20470. public:
  20471. /** Returns a list of the available midi input devices.
  20472. You can open one of the devices by passing its index into the
  20473. openDevice() method.
  20474. @see getDefaultDeviceIndex, openDevice
  20475. */
  20476. static const StringArray getDevices();
  20477. /** Returns the index of the default midi input device to use.
  20478. This refers to the index in the list returned by getDevices().
  20479. */
  20480. static int getDefaultDeviceIndex();
  20481. /** Tries to open one of the midi input devices.
  20482. This will return a MidiInput object if it manages to open it. You can then
  20483. call start() and stop() on this device, and delete it when no longer needed.
  20484. If the device can't be opened, this will return a null pointer.
  20485. @param deviceIndex the index of a device from the list returned by getDevices()
  20486. @param callback the object that will receive the midi messages from this device.
  20487. @see MidiInputCallback, getDevices
  20488. */
  20489. static MidiInput* openDevice (int deviceIndex,
  20490. MidiInputCallback* callback);
  20491. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  20492. /** This will try to create a new midi input device (Not available on Windows).
  20493. This will attempt to create a new midi input device with the specified name,
  20494. for other apps to connect to.
  20495. Returns 0 if a device can't be created.
  20496. @param deviceName the name to use for the new device
  20497. @param callback the object that will receive the midi messages from this device.
  20498. */
  20499. static MidiInput* createNewDevice (const String& deviceName,
  20500. MidiInputCallback* callback);
  20501. #endif
  20502. /** Destructor. */
  20503. virtual ~MidiInput();
  20504. /** Returns the name of this device.
  20505. */
  20506. virtual const String getName() const throw() { return name; }
  20507. /** Allows you to set a custom name for the device, in case you don't like the name
  20508. it was given when created.
  20509. */
  20510. virtual void setName (const String& newName) throw() { name = newName; }
  20511. /** Starts the device running.
  20512. After calling this, the device will start sending midi messages to the
  20513. MidiInputCallback object that was specified when the openDevice() method
  20514. was called.
  20515. @see stop
  20516. */
  20517. virtual void start();
  20518. /** Stops the device running.
  20519. @see start
  20520. */
  20521. virtual void stop();
  20522. juce_UseDebuggingNewOperator
  20523. protected:
  20524. String name;
  20525. void* internal;
  20526. MidiInput (const String& name);
  20527. MidiInput (const MidiInput&);
  20528. };
  20529. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  20530. /********* End of inlined file: juce_MidiInput.h *********/
  20531. /**
  20532. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  20533. processing by a block-based audio callback.
  20534. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  20535. so it can easily use a midi input or keyboard component as its source.
  20536. @see MidiMessage, MidiInput
  20537. */
  20538. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  20539. public MidiInputCallback
  20540. {
  20541. public:
  20542. /** Creates a MidiMessageCollector. */
  20543. MidiMessageCollector();
  20544. /** Destructor. */
  20545. ~MidiMessageCollector();
  20546. /** Clears any messages from the queue.
  20547. You need to call this method before starting to use the collector, so that
  20548. it knows the correct sample rate to use.
  20549. */
  20550. void reset (const double sampleRate);
  20551. /** Takes an incoming real-time message and adds it to the queue.
  20552. The message's timestamp is taken, and it will be ready for retrieval as part
  20553. of the block returned by the next call to removeNextBlockOfMessages().
  20554. This method is fully thread-safe when overlapping calls are made with
  20555. removeNextBlockOfMessages().
  20556. */
  20557. void addMessageToQueue (const MidiMessage& message);
  20558. /** Removes all the pending messages from the queue as a buffer.
  20559. This will also correct the messages' timestamps to make sure they're in
  20560. the range 0 to numSamples - 1.
  20561. This call should be made regularly by something like an audio processing
  20562. callback, because the time that it happens is used in calculating the
  20563. midi event positions.
  20564. This method is fully thread-safe when overlapping calls are made with
  20565. addMessageToQueue().
  20566. */
  20567. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20568. const int numSamples);
  20569. /** @internal */
  20570. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  20571. /** @internal */
  20572. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  20573. /** @internal */
  20574. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  20575. juce_UseDebuggingNewOperator
  20576. private:
  20577. double lastCallbackTime;
  20578. CriticalSection midiCallbackLock;
  20579. MidiBuffer incomingMessages;
  20580. double sampleRate;
  20581. MidiMessageCollector (const MidiMessageCollector&);
  20582. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  20583. };
  20584. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20585. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  20586. #endif
  20587. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20588. #endif
  20589. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20590. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  20591. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20592. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20593. /**
  20594. A set of routines to convert buffers of 32-bit floating point data to and from
  20595. various integer formats.
  20596. */
  20597. class JUCE_API AudioDataConverters
  20598. {
  20599. public:
  20600. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  20601. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  20602. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  20603. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  20604. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20605. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20606. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20607. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20608. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  20609. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  20610. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  20611. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  20612. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20613. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20614. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20615. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20616. enum DataFormat
  20617. {
  20618. int16LE,
  20619. int16BE,
  20620. int24LE,
  20621. int24BE,
  20622. int32LE,
  20623. int32BE,
  20624. float32LE,
  20625. float32BE,
  20626. };
  20627. static void convertFloatToFormat (const DataFormat destFormat,
  20628. const float* source, void* dest, int numSamples);
  20629. static void convertFormatToFloat (const DataFormat sourceFormat,
  20630. const void* source, float* dest, int numSamples);
  20631. static void interleaveSamples (const float** source, float* dest,
  20632. const int numSamples, const int numChannels);
  20633. static void deinterleaveSamples (const float* source, float** dest,
  20634. const int numSamples, const int numChannels);
  20635. };
  20636. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20637. /********* End of inlined file: juce_AudioDataConverters.h *********/
  20638. #endif
  20639. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20640. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20641. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20642. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20643. class AudioFormatReader;
  20644. class AudioFormatWriter;
  20645. /**
  20646. A multi-channel buffer of 32-bit floating point audio samples.
  20647. */
  20648. class JUCE_API AudioSampleBuffer
  20649. {
  20650. public:
  20651. /** Creates a buffer with a specified number of channels and samples.
  20652. The contents of the buffer will initially be undefined, so use clear() to
  20653. set all the samples to zero.
  20654. The buffer will allocate its memory internally, and this will be released
  20655. when the buffer is deleted.
  20656. */
  20657. AudioSampleBuffer (const int numChannels,
  20658. const int numSamples) throw();
  20659. /** Creates a buffer using a pre-allocated block of memory.
  20660. Note that if the buffer is resized or its number of channels is changed, it
  20661. will re-allocate memory internally and copy the existing data to this new area,
  20662. so it will then stop directly addressing this memory.
  20663. @param dataToReferTo a pre-allocated array containing pointers to the data
  20664. for each channel that should be used by this buffer. The
  20665. buffer will only refer to this memory, it won't try to delete
  20666. it when the buffer is deleted or resized.
  20667. @param numChannels the number of channels to use - this must correspond to the
  20668. number of elements in the array passed in
  20669. @param numSamples the number of samples to use - this must correspond to the
  20670. size of the arrays passed in
  20671. */
  20672. AudioSampleBuffer (float** dataToReferTo,
  20673. const int numChannels,
  20674. const int numSamples) throw();
  20675. /** Copies another buffer.
  20676. This buffer will make its own copy of the other's data, unless the buffer was created
  20677. using an external data buffer, in which case boths buffers will just point to the same
  20678. shared block of data.
  20679. */
  20680. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20681. /** Copies another buffer onto this one.
  20682. This buffer's size will be changed to that of the other buffer.
  20683. */
  20684. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20685. /** Destructor.
  20686. This will free any memory allocated by the buffer.
  20687. */
  20688. virtual ~AudioSampleBuffer() throw();
  20689. /** Returns the number of channels of audio data that this buffer contains.
  20690. @see getSampleData
  20691. */
  20692. int getNumChannels() const throw() { return numChannels; }
  20693. /** Returns the number of samples allocated in each of the buffer's channels.
  20694. @see getSampleData
  20695. */
  20696. int getNumSamples() const throw() { return size; }
  20697. /** Returns a pointer one of the buffer's channels.
  20698. For speed, this doesn't check whether the channel number is out of range,
  20699. so be careful when using it!
  20700. */
  20701. float* getSampleData (const int channelNumber) const throw()
  20702. {
  20703. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20704. return channels [channelNumber];
  20705. }
  20706. /** Returns a pointer to a sample in one of the buffer's channels.
  20707. For speed, this doesn't check whether the channel and sample number
  20708. are out-of-range, so be careful when using it!
  20709. */
  20710. float* getSampleData (const int channelNumber,
  20711. const int sampleOffset) const throw()
  20712. {
  20713. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20714. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  20715. return channels [channelNumber] + sampleOffset;
  20716. }
  20717. /** Returns an array of pointers to the channels in the buffer.
  20718. Don't modify any of the pointers that are returned, and bear in mind that
  20719. these will become invalid if the buffer is resized.
  20720. */
  20721. float** getArrayOfChannels() const throw() { return channels; }
  20722. /** Chages the buffer's size or number of channels.
  20723. This can expand or contract the buffer's length, and add or remove channels.
  20724. If keepExistingContent is true, it will try to preserve as much of the
  20725. old data as it can in the new buffer.
  20726. If clearExtraSpace is true, then any extra channels or space that is
  20727. allocated will be also be cleared. If false, then this space is left
  20728. uninitialised.
  20729. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20730. amount of memory that is currently allocated (but it will still increase it if
  20731. the new size is bigger than the amount it currently has). If this is false, then
  20732. a new allocation will be done so that the buffer uses takes up the minimum amount
  20733. of memory that it needs.
  20734. */
  20735. void setSize (const int newNumChannels,
  20736. const int newNumSamples,
  20737. const bool keepExistingContent = false,
  20738. const bool clearExtraSpace = false,
  20739. const bool avoidReallocating = false) throw();
  20740. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20741. There's also a constructor that lets you specify arrays like this, but this
  20742. lets you change the channels dynamically.
  20743. Note that if the buffer is resized or its number of channels is changed, it
  20744. will re-allocate memory internally and copy the existing data to this new area,
  20745. so it will then stop directly addressing this memory.
  20746. @param dataToReferTo a pre-allocated array containing pointers to the data
  20747. for each channel that should be used by this buffer. The
  20748. buffer will only refer to this memory, it won't try to delete
  20749. it when the buffer is deleted or resized.
  20750. @param numChannels the number of channels to use - this must correspond to the
  20751. number of elements in the array passed in
  20752. @param numSamples the number of samples to use - this must correspond to the
  20753. size of the arrays passed in
  20754. */
  20755. void setDataToReferTo (float** dataToReferTo,
  20756. const int numChannels,
  20757. const int numSamples) throw();
  20758. /** Clears all the samples in all channels. */
  20759. void clear() throw();
  20760. /** Clears a specified region of all the channels.
  20761. For speed, this doesn't check whether the channel and sample number
  20762. are in-range, so be careful!
  20763. */
  20764. void clear (const int startSample,
  20765. const int numSamples) throw();
  20766. /** Clears a specified region of just one channel.
  20767. For speed, this doesn't check whether the channel and sample number
  20768. are in-range, so be careful!
  20769. */
  20770. void clear (const int channel,
  20771. const int startSample,
  20772. const int numSamples) throw();
  20773. /** Applies a gain multiple to a region of one channel.
  20774. For speed, this doesn't check whether the channel and sample number
  20775. are in-range, so be careful!
  20776. */
  20777. void applyGain (const int channel,
  20778. const int startSample,
  20779. int numSamples,
  20780. const float gain) throw();
  20781. /** Applies a gain multiple to a region of all the channels.
  20782. For speed, this doesn't check whether the sample numbers
  20783. are in-range, so be careful!
  20784. */
  20785. void applyGain (const int startSample,
  20786. const int numSamples,
  20787. const float gain) throw();
  20788. /** Applies a range of gains to a region of a channel.
  20789. The gain that is applied to each sample will vary from
  20790. startGain on the first sample to endGain on the last Sample,
  20791. so it can be used to do basic fades.
  20792. For speed, this doesn't check whether the sample numbers
  20793. are in-range, so be careful!
  20794. */
  20795. void applyGainRamp (const int channel,
  20796. const int startSample,
  20797. int numSamples,
  20798. float startGain,
  20799. float endGain) throw();
  20800. /** Adds samples from another buffer to this one.
  20801. @param destChannel the channel within this buffer to add the samples to
  20802. @param destStartSample the start sample within this buffer's channel
  20803. @param source the source buffer to add from
  20804. @param sourceChannel the channel within the source buffer to read from
  20805. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20806. @param numSamples the number of samples to process
  20807. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20808. added to this buffer's samples
  20809. @see copyFrom
  20810. */
  20811. void addFrom (const int destChannel,
  20812. const int destStartSample,
  20813. const AudioSampleBuffer& source,
  20814. const int sourceChannel,
  20815. const int sourceStartSample,
  20816. int numSamples,
  20817. const float gainToApplyToSource = 1.0f) throw();
  20818. /** Adds samples from an array of floats to one of the channels.
  20819. @param destChannel the channel within this buffer to add the samples to
  20820. @param destStartSample the start sample within this buffer's channel
  20821. @param source the source data to use
  20822. @param numSamples the number of samples to process
  20823. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20824. added to this buffer's samples
  20825. @see copyFrom
  20826. */
  20827. void addFrom (const int destChannel,
  20828. const int destStartSample,
  20829. const float* source,
  20830. int numSamples,
  20831. const float gainToApplyToSource = 1.0f) throw();
  20832. /** Adds samples from an array of floats, applying a gain ramp to them.
  20833. @param destChannel the channel within this buffer to add the samples to
  20834. @param destStartSample the start sample within this buffer's channel
  20835. @param source the source data to use
  20836. @param numSamples the number of samples to process
  20837. @param startGain the gain to apply to the first sample (this is multiplied with
  20838. the source samples before they are added to this buffer)
  20839. @param endGain the gain to apply to the final sample. The gain is linearly
  20840. interpolated between the first and last samples.
  20841. */
  20842. void addFromWithRamp (const int destChannel,
  20843. const int destStartSample,
  20844. const float* source,
  20845. int numSamples,
  20846. float startGain,
  20847. float endGain) throw();
  20848. /** Copies samples from another buffer to this one.
  20849. @param destChannel the channel within this buffer to copy the samples to
  20850. @param destStartSample the start sample within this buffer's channel
  20851. @param source the source buffer to read from
  20852. @param sourceChannel the channel within the source buffer to read from
  20853. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20854. @param numSamples the number of samples to process
  20855. @see addFrom
  20856. */
  20857. void copyFrom (const int destChannel,
  20858. const int destStartSample,
  20859. const AudioSampleBuffer& source,
  20860. const int sourceChannel,
  20861. const int sourceStartSample,
  20862. int numSamples) throw();
  20863. /** Copies samples from an array of floats into one of the channels.
  20864. @param destChannel the channel within this buffer to copy the samples to
  20865. @param destStartSample the start sample within this buffer's channel
  20866. @param source the source buffer to read from
  20867. @param numSamples the number of samples to process
  20868. @see addFrom
  20869. */
  20870. void copyFrom (const int destChannel,
  20871. const int destStartSample,
  20872. const float* source,
  20873. int numSamples) throw();
  20874. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20875. @param destChannel the channel within this buffer to copy the samples to
  20876. @param destStartSample the start sample within this buffer's channel
  20877. @param source the source buffer to read from
  20878. @param numSamples the number of samples to process
  20879. @param gain the gain to apply
  20880. @see addFrom
  20881. */
  20882. void copyFrom (const int destChannel,
  20883. const int destStartSample,
  20884. const float* source,
  20885. int numSamples,
  20886. const float gain) throw();
  20887. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20888. @param destChannel the channel within this buffer to copy the samples to
  20889. @param destStartSample the start sample within this buffer's channel
  20890. @param source the source buffer to read from
  20891. @param numSamples the number of samples to process
  20892. @param startGain the gain to apply to the first sample (this is multiplied with
  20893. the source samples before they are copied to this buffer)
  20894. @param endGain the gain to apply to the final sample. The gain is linearly
  20895. interpolated between the first and last samples.
  20896. @see addFrom
  20897. */
  20898. void copyFromWithRamp (const int destChannel,
  20899. const int destStartSample,
  20900. const float* source,
  20901. int numSamples,
  20902. float startGain,
  20903. float endGain) throw();
  20904. /** Finds the highest and lowest sample values in a given range.
  20905. @param channel the channel to read from
  20906. @param startSample the start sample within the channel
  20907. @param numSamples the number of samples to check
  20908. @param minVal on return, the lowest value that was found
  20909. @param maxVal on return, the highest value that was found
  20910. */
  20911. void findMinMax (const int channel,
  20912. const int startSample,
  20913. int numSamples,
  20914. float& minVal,
  20915. float& maxVal) const throw();
  20916. /** Finds the highest absolute sample value within a region of a channel.
  20917. */
  20918. float getMagnitude (const int channel,
  20919. const int startSample,
  20920. const int numSamples) const throw();
  20921. /** Finds the highest absolute sample value within a region on all channels.
  20922. */
  20923. float getMagnitude (const int startSample,
  20924. const int numSamples) const throw();
  20925. /** Returns the root mean squared level for a region of a channel.
  20926. */
  20927. float getRMSLevel (const int channel,
  20928. const int startSample,
  20929. const int numSamples) const throw();
  20930. /** Fills a section of the buffer using an AudioReader as its source.
  20931. This will convert the reader's fixed- or floating-point data to
  20932. the buffer's floating-point format, and will try to intelligently
  20933. cope with mismatches between the number of channels in the reader
  20934. and the buffer.
  20935. @see writeToAudioWriter
  20936. */
  20937. void readFromAudioReader (AudioFormatReader* reader,
  20938. const int startSample,
  20939. const int numSamples,
  20940. const int readerStartSample,
  20941. const bool useReaderLeftChan,
  20942. const bool useReaderRightChan) throw();
  20943. /** Writes a section of this buffer to an audio writer.
  20944. This saves you having to mess about with channels or floating/fixed
  20945. point conversion.
  20946. @see readFromAudioReader
  20947. */
  20948. void writeToAudioWriter (AudioFormatWriter* writer,
  20949. const int startSample,
  20950. const int numSamples) const throw();
  20951. juce_UseDebuggingNewOperator
  20952. private:
  20953. int numChannels, size, allocatedBytes;
  20954. float** channels;
  20955. float* allocatedData;
  20956. float* preallocatedChannelSpace [32];
  20957. };
  20958. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20959. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20960. #endif
  20961. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20962. /********* Start of inlined file: juce_IIRFilter.h *********/
  20963. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20964. #define __JUCE_IIRFILTER_JUCEHEADER__
  20965. /**
  20966. An IIR filter that can perform low, high, or band-pass filtering on an
  20967. audio signal.
  20968. @see IIRFilterAudioSource
  20969. */
  20970. class JUCE_API IIRFilter
  20971. {
  20972. public:
  20973. /** Creates a filter.
  20974. Initially the filter is inactive, so will have no effect on samples that
  20975. you process with it. Use the appropriate method to turn it into the type
  20976. of filter needed.
  20977. */
  20978. IIRFilter() throw();
  20979. /** Creates a copy of another filter. */
  20980. IIRFilter (const IIRFilter& other) throw();
  20981. /** Destructor. */
  20982. ~IIRFilter() throw();
  20983. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20984. Note that this clears the processing state, but the type of filter and
  20985. its coefficients aren't changed. To put a filter into an inactive state, use
  20986. the makeInactive() method.
  20987. */
  20988. void reset() throw();
  20989. /** Performs the filter operation on the given set of samples.
  20990. */
  20991. void processSamples (float* const samples,
  20992. const int numSamples) throw();
  20993. /** Processes a single sample, without any locking or checking.
  20994. Use this if you need fast processing of a single value, but be aware that
  20995. this isn't thread-safe in the way that processSamples() is.
  20996. */
  20997. float processSingleSampleRaw (const float sample) throw();
  20998. /** Sets the filter up to act as a low-pass filter.
  20999. */
  21000. void makeLowPass (const double sampleRate,
  21001. const double frequency) throw();
  21002. /** Sets the filter up to act as a high-pass filter.
  21003. */
  21004. void makeHighPass (const double sampleRate,
  21005. const double frequency) throw();
  21006. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  21007. The gain is a scale factor that the low frequencies are multiplied by, so values
  21008. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  21009. attenuate them.
  21010. */
  21011. void makeLowShelf (const double sampleRate,
  21012. const double cutOffFrequency,
  21013. const double Q,
  21014. const float gainFactor) throw();
  21015. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  21016. The gain is a scale factor that the high frequencies are multiplied by, so values
  21017. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  21018. attenuate them.
  21019. */
  21020. void makeHighShelf (const double sampleRate,
  21021. const double cutOffFrequency,
  21022. const double Q,
  21023. const float gainFactor) throw();
  21024. /** Sets the filter up to act as a band pass filter centred around a
  21025. frequency, with a variable Q and gain.
  21026. The gain is a scale factor that the centre frequencies are multiplied by, so
  21027. values greater than 1.0 will boost the centre frequencies, values less than
  21028. 1.0 will attenuate them.
  21029. */
  21030. void makeBandPass (const double sampleRate,
  21031. const double centreFrequency,
  21032. const double Q,
  21033. const float gainFactor) throw();
  21034. /** Clears the filter's coefficients so that it becomes inactive.
  21035. */
  21036. void makeInactive() throw();
  21037. /** Makes this filter duplicate the set-up of another one.
  21038. */
  21039. void copyCoefficientsFrom (const IIRFilter& other) throw();
  21040. juce_UseDebuggingNewOperator
  21041. protected:
  21042. CriticalSection processLock;
  21043. void setCoefficients (double c1, double c2, double c3,
  21044. double c4, double c5, double c6) throw();
  21045. bool active;
  21046. float coefficients[6];
  21047. float x1, x2, y1, y2;
  21048. // (use the copyCoefficientsFrom() method instead of this operator)
  21049. const IIRFilter& operator= (const IIRFilter&);
  21050. };
  21051. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  21052. /********* End of inlined file: juce_IIRFilter.h *********/
  21053. #endif
  21054. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21055. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  21056. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21057. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21058. /**
  21059. A subclass of AudioPlayHead can supply information about the position and
  21060. status of a moving play head during audio playback.
  21061. One of these can be supplied to an AudioProcessor object so that it can find
  21062. out about the position of the audio that it is rendering.
  21063. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  21064. */
  21065. class JUCE_API AudioPlayHead
  21066. {
  21067. protected:
  21068. AudioPlayHead() {}
  21069. public:
  21070. virtual ~AudioPlayHead() {}
  21071. /** Frame rate types. */
  21072. enum FrameRateType
  21073. {
  21074. fps24 = 0,
  21075. fps25 = 1,
  21076. fps2997 = 2,
  21077. fps30 = 3,
  21078. fps2997drop = 4,
  21079. fps30drop = 5,
  21080. fpsUnknown = 99
  21081. };
  21082. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  21083. */
  21084. struct CurrentPositionInfo
  21085. {
  21086. /** The tempo in BPM */
  21087. double bpm;
  21088. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  21089. int timeSigNumerator;
  21090. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  21091. int timeSigDenominator;
  21092. /** The current play position, in seconds from the start of the edit. */
  21093. double timeInSeconds;
  21094. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  21095. double editOriginTime;
  21096. /** The current play position in pulses-per-quarter-note.
  21097. This is the number of quarter notes since the edit start.
  21098. */
  21099. double ppqPosition;
  21100. /** The position of the start of the last bar, in pulses-per-quarter-note.
  21101. This is the number of quarter notes from the start of the edit to the
  21102. start of the current bar.
  21103. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  21104. it's not available, the value will be 0.
  21105. */
  21106. double ppqPositionOfLastBarStart;
  21107. /** The video frame rate, if applicable. */
  21108. FrameRateType frameRate;
  21109. /** True if the transport is currently playing. */
  21110. bool isPlaying;
  21111. /** True if the transport is currently recording.
  21112. (When isRecording is true, then isPlaying will also be true).
  21113. */
  21114. bool isRecording;
  21115. };
  21116. /** Fills-in the given structure with details about the transport's
  21117. position at the start of the current processing block.
  21118. */
  21119. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  21120. };
  21121. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21122. /********* End of inlined file: juce_AudioPlayHead.h *********/
  21123. #endif
  21124. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21125. /********* Start of inlined file: juce_AudioProcessor.h *********/
  21126. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21127. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21128. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  21129. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21130. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21131. class AudioProcessor;
  21132. /**
  21133. Base class for the component that acts as the GUI for an AudioProcessor.
  21134. Derive your editor component from this class, and create an instance of it
  21135. by overriding the AudioProcessor::createEditor() method.
  21136. @see AudioProcessor, GenericAudioProcessorEditor
  21137. */
  21138. class JUCE_API AudioProcessorEditor : public Component
  21139. {
  21140. protected:
  21141. /** Creates an editor for the specified processor.
  21142. */
  21143. AudioProcessorEditor (AudioProcessor* const owner);
  21144. public:
  21145. /** Destructor. */
  21146. ~AudioProcessorEditor();
  21147. /** Returns a pointer to the processor that this editor represents. */
  21148. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  21149. private:
  21150. AudioProcessor* const owner;
  21151. };
  21152. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21153. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  21154. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  21155. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21156. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21157. class AudioProcessor;
  21158. /**
  21159. Base class for listeners that want to know about changes to an AudioProcessor.
  21160. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  21161. @see AudioProcessor
  21162. */
  21163. class JUCE_API AudioProcessorListener
  21164. {
  21165. public:
  21166. /** Destructor. */
  21167. virtual ~AudioProcessorListener() {}
  21168. /** Receives a callback when a parameter is changed.
  21169. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  21170. many audio processors will change their parameter during their audio callback.
  21171. This means that not only has your handler code got to be completely thread-safe,
  21172. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  21173. this event on your message thread, use this callback to trigger an AsyncUpdater
  21174. or ChangeBroadcaster which you can respond to on the message thread.
  21175. */
  21176. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  21177. int parameterIndex,
  21178. float newValue) = 0;
  21179. /** Called to indicate that something else in the plugin has changed, like its
  21180. program, number of parameters, etc.
  21181. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  21182. call it during their audio callback. This means that not only has your handler code
  21183. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  21184. blocking. If you need to handle this event on your message thread, use this callback
  21185. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  21186. message thread.
  21187. */
  21188. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  21189. /** Indicates that a parameter change gesture has started.
  21190. E.g. if the user is dragging a slider, this would be called when they first
  21191. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  21192. called when they release it.
  21193. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  21194. call it during their audio callback. This means that not only has your handler code
  21195. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  21196. blocking. If you need to handle this event on your message thread, use this callback
  21197. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  21198. message thread.
  21199. @see audioProcessorParameterChangeGestureEnd
  21200. */
  21201. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  21202. int parameterIndex);
  21203. /** Indicates that a parameter change gesture has finished.
  21204. E.g. if the user is dragging a slider, this would be called when they release
  21205. the mouse button.
  21206. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  21207. call it during their audio callback. This means that not only has your handler code
  21208. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  21209. blocking. If you need to handle this event on your message thread, use this callback
  21210. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  21211. message thread.
  21212. @see audioPluginParameterChangeGestureStart
  21213. */
  21214. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  21215. int parameterIndex);
  21216. };
  21217. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21218. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  21219. /**
  21220. Base class for audio processing filters or plugins.
  21221. This is intended to act as a base class of audio filter that is general enough to
  21222. be wrapped as a VST, AU, RTAS, etc, or used internally.
  21223. It is also used by the plugin hosting code as the wrapper around an instance
  21224. of a loaded plugin.
  21225. Derive your filter class from this base class, and if you're building a plugin,
  21226. you should implement a global function called createPluginFilter() which creates
  21227. and returns a new instance of your subclass.
  21228. */
  21229. class JUCE_API AudioProcessor
  21230. {
  21231. protected:
  21232. /** Constructor.
  21233. You can also do your initialisation tasks in the initialiseFilterInfo()
  21234. call, which will be made after this object has been created.
  21235. */
  21236. AudioProcessor();
  21237. public:
  21238. /** Destructor. */
  21239. virtual ~AudioProcessor();
  21240. /** Returns the name of this processor.
  21241. */
  21242. virtual const String getName() const = 0;
  21243. /** Called before playback starts, to let the filter prepare itself.
  21244. The sample rate is the target sample rate, and will remain constant until
  21245. playback stops.
  21246. The estimatedSamplesPerBlock value is a HINT about the typical number of
  21247. samples that will be processed for each callback, but isn't any kind
  21248. of guarantee. The actual block sizes that the host uses may be different
  21249. each time the callback happens, and may be more or less than this value.
  21250. */
  21251. virtual void prepareToPlay (double sampleRate,
  21252. int estimatedSamplesPerBlock) = 0;
  21253. /** Called after playback has stopped, to let the filter free up any resources it
  21254. no longer needs.
  21255. */
  21256. virtual void releaseResources() = 0;
  21257. /** Renders the next block.
  21258. When this method is called, the buffer contains a number of channels which is
  21259. at least as great as the maximum number of input and output channels that
  21260. this filter is using. It will be filled with the filter's input data and
  21261. should be replaced with the filter's output.
  21262. So for example if your filter has 2 input channels and 4 output channels, then
  21263. the buffer will contain 4 channels, the first two being filled with the
  21264. input data. Your filter should read these, do its processing, and replace
  21265. the contents of all 4 channels with its output.
  21266. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  21267. all filled with data, and your filter should overwrite the first 2 of these
  21268. with its output. But be VERY careful not to write anything to the last 3
  21269. channels, as these might be mapped to memory that the host assumes is read-only!
  21270. Note that if you have more outputs than inputs, then only those channels that
  21271. correspond to an input channel are guaranteed to contain sensible data - e.g.
  21272. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  21273. but the last two channels may contain garbage, so you should be careful not to
  21274. let this pass through without being overwritten or cleared.
  21275. Also note that the buffer may have more channels than are strictly necessary,
  21276. but your should only read/write from the ones that your filter is supposed to
  21277. be using.
  21278. The number of samples in these buffers is NOT guaranteed to be the same for every
  21279. callback, and may be more or less than the estimated value given to prepareToPlay().
  21280. Your code must be able to cope with variable-sized blocks, or you're going to get
  21281. clicks and crashes!
  21282. If the filter is receiving a midi input, then the midiMessages array will be filled
  21283. with the midi messages for this block. Each message's timestamp will indicate the
  21284. message's time, as a number of samples from the start of the block.
  21285. Any messages left in the midi buffer when this method has finished are assumed to
  21286. be the filter's midi output. This means that your filter should be careful to
  21287. clear any incoming messages from the array if it doesn't want them to be passed-on.
  21288. Be very careful about what you do in this callback - it's going to be called by
  21289. the audio thread, so any kind of interaction with the UI is absolutely
  21290. out of the question. If you change a parameter in here and need to tell your UI to
  21291. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  21292. the UI components register as listeners, and then call sendChangeMessage() inside the
  21293. processBlock() method to send out an asynchronous message. You could also use
  21294. the AsyncUpdater class in a similar way.
  21295. */
  21296. virtual void processBlock (AudioSampleBuffer& buffer,
  21297. MidiBuffer& midiMessages) = 0;
  21298. /** Returns the current AudioPlayHead object that should be used to find
  21299. out the state and position of the playhead.
  21300. You can call this from your processBlock() method, and use the AudioPlayHead
  21301. object to get the details about the time of the start of the block currently
  21302. being processed.
  21303. If the host hasn't supplied a playhead object, this will return 0.
  21304. */
  21305. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  21306. /** Returns the current sample rate.
  21307. This can be called from your processBlock() method - it's not guaranteed
  21308. to be valid at any other time, and may return 0 if it's unknown.
  21309. */
  21310. double getSampleRate() const throw() { return sampleRate; }
  21311. /** Returns the current typical block size that is being used.
  21312. This can be called from your processBlock() method - it's not guaranteed
  21313. to be valid at any other time.
  21314. Remember it's not the ONLY block size that may be used when calling
  21315. processBlock, it's just the normal one. The actual block sizes used may be
  21316. larger or smaller than this, and will vary between successive calls.
  21317. */
  21318. int getBlockSize() const throw() { return blockSize; }
  21319. /** Returns the number of input channels that the host will be sending the filter.
  21320. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  21321. number of channels that your filter would prefer to have, and this method lets
  21322. you know how many the host is actually using.
  21323. Note that this method is only valid during or after the prepareToPlay()
  21324. method call. Until that point, the number of channels will be unknown.
  21325. */
  21326. int getNumInputChannels() const throw() { return numInputChannels; }
  21327. /** Returns the number of output channels that the host will be sending the filter.
  21328. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  21329. number of channels that your filter would prefer to have, and this method lets
  21330. you know how many the host is actually using.
  21331. Note that this method is only valid during or after the prepareToPlay()
  21332. method call. Until that point, the number of channels will be unknown.
  21333. */
  21334. int getNumOutputChannels() const throw() { return numOutputChannels; }
  21335. /** Returns the name of one of the input channels, as returned by the host.
  21336. The host might not supply very useful names for channels, and this might be
  21337. something like "1", "2", "left", "right", etc.
  21338. */
  21339. virtual const String getInputChannelName (const int channelIndex) const = 0;
  21340. /** Returns the name of one of the output channels, as returned by the host.
  21341. The host might not supply very useful names for channels, and this might be
  21342. something like "1", "2", "left", "right", etc.
  21343. */
  21344. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  21345. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  21346. virtual bool isInputChannelStereoPair (int index) const = 0;
  21347. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  21348. virtual bool isOutputChannelStereoPair (int index) const = 0;
  21349. /** This returns the number of samples delay that the filter imposes on the audio
  21350. passing through it.
  21351. The host will call this to find the latency - the filter itself should set this value
  21352. by calling setLatencySamples() as soon as it can during its initialisation.
  21353. */
  21354. int getLatencySamples() const throw() { return latencySamples; }
  21355. /** The filter should call this to set the number of samples delay that it introduces.
  21356. The filter should call this as soon as it can during initialisation, and can call it
  21357. later if the value changes.
  21358. */
  21359. void setLatencySamples (const int newLatency);
  21360. /** Returns true if the processor wants midi messages. */
  21361. virtual bool acceptsMidi() const = 0;
  21362. /** Returns true if the processor produces midi messages. */
  21363. virtual bool producesMidi() const = 0;
  21364. /** This returns a critical section that will automatically be locked while the host
  21365. is calling the processBlock() method.
  21366. Use it from your UI or other threads to lock access to variables that are used
  21367. by the process callback, but obviously be careful not to keep it locked for
  21368. too long, because that could cause stuttering playback. If you need to do something
  21369. that'll take a long time and need the processing to stop while it happens, use the
  21370. suspendProcessing() method instead.
  21371. @see suspendProcessing
  21372. */
  21373. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  21374. /** Enables and disables the processing callback.
  21375. If you need to do something time-consuming on a thread and would like to make sure
  21376. the audio processing callback doesn't happen until you've finished, use this
  21377. to disable the callback and re-enable it again afterwards.
  21378. E.g.
  21379. @code
  21380. void loadNewPatch()
  21381. {
  21382. suspendProcessing (true);
  21383. ..do something that takes ages..
  21384. suspendProcessing (false);
  21385. }
  21386. @endcode
  21387. If the host tries to make an audio callback while processing is suspended, the
  21388. filter will return an empty buffer, but won't block the audio thread like it would
  21389. do if you use the getCallbackLock() critical section to synchronise access.
  21390. If you're going to use this, your processBlock() method must call isSuspended() and
  21391. check whether it's suspended or not. If it is, then it should skip doing any real
  21392. processing, either emitting silence or passing the input through unchanged.
  21393. @see getCallbackLock
  21394. */
  21395. void suspendProcessing (const bool shouldBeSuspended);
  21396. /** Returns true if processing is currently suspended.
  21397. @see suspendProcessing
  21398. */
  21399. bool isSuspended() const throw() { return suspended; }
  21400. /** A plugin can override this to be told when it should reset any playing voices.
  21401. The default implementation does nothing, but a host may call this to tell the
  21402. plugin that it should stop any tails or sounds that have been left running.
  21403. */
  21404. virtual void reset();
  21405. /** Returns true if the processor is being run in an offline mode for rendering.
  21406. If the processor is being run live on realtime signals, this returns false.
  21407. If the mode is unknown, this will assume it's realtime and return false.
  21408. This value may be unreliable until the prepareToPlay() method has been called,
  21409. and could change each time prepareToPlay() is called.
  21410. @see setNonRealtime()
  21411. */
  21412. bool isNonRealtime() const throw() { return nonRealtime; }
  21413. /** Called by the host to tell this processor whether it's being used in a non-realime
  21414. capacity for offline rendering or bouncing.
  21415. Whatever value is passed-in will be
  21416. */
  21417. void setNonRealtime (const bool isNonRealtime) throw();
  21418. /** Creates the filter's UI.
  21419. This can return 0 if you want a UI-less filter, in which case the host may create
  21420. a generic UI that lets the user twiddle the parameters directly.
  21421. If you do want to pass back a component, the component should be created and set to
  21422. the correct size before returning it.
  21423. Remember not to do anything silly like allowing your filter to keep a pointer to
  21424. the component that gets created - it could be deleted later without any warning, which
  21425. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  21426. The correct way to handle the connection between an editor component and its
  21427. filter is to use something like a ChangeBroadcaster so that the editor can
  21428. register itself as a listener, and be told when a change occurs. This lets them
  21429. safely unregister themselves when they are deleted.
  21430. Here are a few things to bear in mind when writing an editor:
  21431. - Initially there won't be an editor, until the user opens one, or they might
  21432. not open one at all. Your filter mustn't rely on it being there.
  21433. - An editor object may be deleted and a replacement one created again at any time.
  21434. - It's safe to assume that an editor will be deleted before its filter.
  21435. */
  21436. virtual AudioProcessorEditor* createEditor() = 0;
  21437. /** Returns the active editor, if there is one.
  21438. Bear in mind this can return 0, even if an editor has previously been
  21439. opened.
  21440. */
  21441. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  21442. /** Returns the active editor, or if there isn't one, it will create one.
  21443. This may call createEditor() internally to create the component.
  21444. */
  21445. AudioProcessorEditor* createEditorIfNeeded();
  21446. /** This must return the correct value immediately after the object has been
  21447. created, and mustn't change the number of parameters later.
  21448. */
  21449. virtual int getNumParameters() = 0;
  21450. /** Returns the name of a particular parameter. */
  21451. virtual const String getParameterName (int parameterIndex) = 0;
  21452. /** Called by the host to find out the value of one of the filter's parameters.
  21453. The host will expect the value returned to be between 0 and 1.0.
  21454. This could be called quite frequently, so try to make your code efficient.
  21455. It's also likely to be called by non-UI threads, so the code in here should
  21456. be thread-aware.
  21457. */
  21458. virtual float getParameter (int parameterIndex) = 0;
  21459. /** Returns the value of a parameter as a text string. */
  21460. virtual const String getParameterText (int parameterIndex) = 0;
  21461. /** The host will call this method to change the value of one of the filter's parameters.
  21462. The host may call this at any time, including during the audio processing
  21463. callback, so the filter has to process this very fast and avoid blocking.
  21464. If you want to set the value of a parameter internally, e.g. from your
  21465. editor component, then don't call this directly - instead, use the
  21466. setParameterNotifyingHost() method, which will also send a message to
  21467. the host telling it about the change. If the message isn't sent, the host
  21468. won't be able to automate your parameters properly.
  21469. The value passed will be between 0 and 1.0.
  21470. */
  21471. virtual void setParameter (int parameterIndex,
  21472. float newValue) = 0;
  21473. /** Your filter can call this when it needs to change one of its parameters.
  21474. This could happen when the editor or some other internal operation changes
  21475. a parameter. This method will call the setParameter() method to change the
  21476. value, and will then send a message to the host telling it about the change.
  21477. Note that to make sure the host correctly handles automation, you should call
  21478. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  21479. tell the host when the user has started and stopped changing the parameter.
  21480. */
  21481. void setParameterNotifyingHost (int parameterIndex,
  21482. float newValue);
  21483. /** Returns true if the host can automate this parameter.
  21484. By default, this returns true for all parameters.
  21485. */
  21486. virtual bool isParameterAutomatable (int parameterIndex) const;
  21487. /** Should return true if this parameter is a "meta" parameter.
  21488. A meta-parameter is a parameter that changes other params. It is used
  21489. by some hosts (e.g. AudioUnit hosts).
  21490. By default this returns false.
  21491. */
  21492. virtual bool isMetaParameter (int parameterIndex) const;
  21493. /** Sends a signal to the host to tell it that the user is about to start changing this
  21494. parameter.
  21495. This allows the host to know when a parameter is actively being held by the user, and
  21496. it may use this information to help it record automation.
  21497. If you call this, it must be matched by a later call to endParameterChangeGesture().
  21498. */
  21499. void beginParameterChangeGesture (int parameterIndex);
  21500. /** Tells the host that the user has finished changing this parameter.
  21501. This allows the host to know when a parameter is actively being held by the user, and
  21502. it may use this information to help it record automation.
  21503. A call to this method must follow a call to beginParameterChangeGesture().
  21504. */
  21505. void endParameterChangeGesture (int parameterIndex);
  21506. /** The filter can call this when something (apart from a parameter value) has changed.
  21507. It sends a hint to the host that something like the program, number of parameters,
  21508. etc, has changed, and that it should update itself.
  21509. */
  21510. void updateHostDisplay();
  21511. /** Returns the number of preset programs the filter supports.
  21512. The value returned must be valid as soon as this object is created, and
  21513. must not change over its lifetime.
  21514. This value shouldn't be less than 1.
  21515. */
  21516. virtual int getNumPrograms() = 0;
  21517. /** Returns the number of the currently active program.
  21518. */
  21519. virtual int getCurrentProgram() = 0;
  21520. /** Called by the host to change the current program.
  21521. */
  21522. virtual void setCurrentProgram (int index) = 0;
  21523. /** Must return the name of a given program. */
  21524. virtual const String getProgramName (int index) = 0;
  21525. /** Called by the host to rename a program.
  21526. */
  21527. virtual void changeProgramName (int index, const String& newName) = 0;
  21528. /** The host will call this method when it wants to save the filter's internal state.
  21529. This must copy any info about the filter's state into the block of memory provided,
  21530. so that the host can store this and later restore it using setStateInformation().
  21531. Note that there's also a getCurrentProgramStateInformation() method, which only
  21532. stores the current program, not the state of the entire filter.
  21533. See also the helper function copyXmlToBinary() for storing settings as XML.
  21534. @see getCurrentProgramStateInformation
  21535. */
  21536. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  21537. /** The host will call this method if it wants to save the state of just the filter's
  21538. current program.
  21539. Unlike getStateInformation, this should only return the current program's state.
  21540. Not all hosts support this, and if you don't implement it, the base class
  21541. method just calls getStateInformation() instead. If you do implement it, be
  21542. sure to also implement getCurrentProgramStateInformation.
  21543. @see getStateInformation, setCurrentProgramStateInformation
  21544. */
  21545. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21546. /** This must restore the filter's state from a block of data previously created
  21547. using getStateInformation().
  21548. Note that there's also a setCurrentProgramStateInformation() method, which tries
  21549. to restore just the current program, not the state of the entire filter.
  21550. See also the helper function getXmlFromBinary() for loading settings as XML.
  21551. @see setCurrentProgramStateInformation
  21552. */
  21553. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  21554. /** The host will call this method if it wants to restore the state of just the filter's
  21555. current program.
  21556. Not all hosts support this, and if you don't implement it, the base class
  21557. method just calls setStateInformation() instead. If you do implement it, be
  21558. sure to also implement getCurrentProgramStateInformation.
  21559. @see setStateInformation, getCurrentProgramStateInformation
  21560. */
  21561. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21562. /** Adds a listener that will be called when an aspect of this processor changes. */
  21563. void addListener (AudioProcessorListener* const newListener) throw();
  21564. /** Removes a previously added listener. */
  21565. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  21566. /** Not for public use - this is called before deleting an editor component. */
  21567. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  21568. /** Not for public use - this is called to initialise the processor. */
  21569. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  21570. /** Not for public use - this is called to initialise the processor before playing. */
  21571. void setPlayConfigDetails (const int numIns, const int numOuts,
  21572. const double sampleRate,
  21573. const int blockSize) throw();
  21574. juce_UseDebuggingNewOperator
  21575. protected:
  21576. /** Helper function that just converts an xml element into a binary blob.
  21577. Use this in your filter's getStateInformation() method if you want to
  21578. store its state as xml.
  21579. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  21580. from a binary blob.
  21581. */
  21582. static void copyXmlToBinary (const XmlElement& xml,
  21583. JUCE_NAMESPACE::MemoryBlock& destData);
  21584. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  21585. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  21586. an XmlElement object that the caller must delete when no longer needed.
  21587. */
  21588. static XmlElement* getXmlFromBinary (const void* data,
  21589. const int sizeInBytes);
  21590. /** @internal */
  21591. AudioPlayHead* playHead;
  21592. /** @internal */
  21593. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  21594. private:
  21595. VoidArray listeners;
  21596. AudioProcessorEditor* activeEditor;
  21597. double sampleRate;
  21598. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  21599. bool suspended, nonRealtime;
  21600. CriticalSection callbackLock, listenerLock;
  21601. #ifdef JUCE_DEBUG
  21602. BitArray changingParams;
  21603. #endif
  21604. AudioProcessor (const AudioProcessor&);
  21605. const AudioProcessor& operator= (const AudioProcessor&);
  21606. };
  21607. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21608. /********* End of inlined file: juce_AudioProcessor.h *********/
  21609. #endif
  21610. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21611. #endif
  21612. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21613. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  21614. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21615. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21616. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  21617. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21618. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21619. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  21620. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21621. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21622. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  21623. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21624. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21625. /********* Start of inlined file: juce_PluginDescription.h *********/
  21626. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21627. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21628. /**
  21629. A small class to represent some facts about a particular type of plugin.
  21630. This class is for storing and managing the details about a plugin without
  21631. actually having to load an instance of it.
  21632. A KnownPluginList contains a list of PluginDescription objects.
  21633. @see KnownPluginList
  21634. */
  21635. class JUCE_API PluginDescription
  21636. {
  21637. public:
  21638. PluginDescription() throw();
  21639. PluginDescription (const PluginDescription& other) throw();
  21640. const PluginDescription& operator= (const PluginDescription& other) throw();
  21641. ~PluginDescription() throw();
  21642. /** The name of the plugin. */
  21643. String name;
  21644. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  21645. */
  21646. String pluginFormatName;
  21647. /** A category, such as "Dynamics", "Reverbs", etc.
  21648. */
  21649. String category;
  21650. /** The manufacturer. */
  21651. String manufacturerName;
  21652. /** The version. This string doesn't have any particular format. */
  21653. String version;
  21654. /** Either the file containing the plugin module, or some other unique way
  21655. of identifying it.
  21656. E.g. for an AU, this would be an ID string that the component manager
  21657. could use to retrieve the plugin. For a VST, it's the file path.
  21658. */
  21659. String fileOrIdentifier;
  21660. /** The last time the plugin file was changed.
  21661. This is handy when scanning for new or changed plugins.
  21662. */
  21663. Time lastFileModTime;
  21664. /** A unique ID for the plugin.
  21665. Note that this might not be unique between formats, e.g. a VST and some
  21666. other format might actually have the same id.
  21667. @see createIdentifierString
  21668. */
  21669. int uid;
  21670. /** True if the plugin identifies itself as a synthesiser. */
  21671. bool isInstrument;
  21672. /** The number of inputs. */
  21673. int numInputChannels;
  21674. /** The number of outputs. */
  21675. int numOutputChannels;
  21676. /** Returns true if the two descriptions refer the the same plugin.
  21677. This isn't quite as simple as them just having the same file (because of
  21678. shell plugins).
  21679. */
  21680. bool isDuplicateOf (const PluginDescription& other) const;
  21681. /** Returns a string that can be saved and used to uniquely identify the
  21682. plugin again.
  21683. This contains less info than the XML encoding, and is independent of the
  21684. plugin's file location, so can be used to store a plugin ID for use
  21685. across different machines.
  21686. */
  21687. const String createIdentifierString() const throw();
  21688. /** Creates an XML object containing these details.
  21689. @see loadFromXml
  21690. */
  21691. XmlElement* createXml() const;
  21692. /** Reloads the info in this structure from an XML record that was previously
  21693. saved with createXML().
  21694. Returns true if the XML was a valid plugin description.
  21695. */
  21696. bool loadFromXml (const XmlElement& xml);
  21697. juce_UseDebuggingNewOperator
  21698. };
  21699. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21700. /********* End of inlined file: juce_PluginDescription.h *********/
  21701. /**
  21702. Base class for an active instance of a plugin.
  21703. This derives from the AudioProcessor class, and adds some extra functionality
  21704. that helps when wrapping dynamically loaded plugins.
  21705. @see AudioProcessor, AudioPluginFormat
  21706. */
  21707. class JUCE_API AudioPluginInstance : public AudioProcessor
  21708. {
  21709. public:
  21710. /** Destructor.
  21711. Make sure that you delete any UI components that belong to this plugin before
  21712. deleting the plugin.
  21713. */
  21714. virtual ~AudioPluginInstance();
  21715. /** Fills-in the appropriate parts of this plugin description object.
  21716. */
  21717. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  21718. juce_UseDebuggingNewOperator
  21719. protected:
  21720. AudioPluginInstance();
  21721. AudioPluginInstance (const AudioPluginInstance&);
  21722. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  21723. };
  21724. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21725. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  21726. class PluginDescription;
  21727. /**
  21728. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  21729. Use the static getNumFormats() and getFormat() calls to find the types
  21730. of format that are available.
  21731. */
  21732. class JUCE_API AudioPluginFormat
  21733. {
  21734. public:
  21735. /** Destructor. */
  21736. virtual ~AudioPluginFormat();
  21737. /** Returns the format name.
  21738. E.g. "VST", "AudioUnit", etc.
  21739. */
  21740. virtual const String getName() const = 0;
  21741. /** This tries to create descriptions for all the plugin types available in
  21742. a binary module file.
  21743. The file will be some kind of DLL or bundle.
  21744. Normally there will only be one type returned, but some plugins
  21745. (e.g. VST shells) can use a single DLL to create a set of different plugin
  21746. subtypes, so in that case, each subtype is returned as a separate object.
  21747. */
  21748. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  21749. const String& fileOrIdentifier) = 0;
  21750. /** Tries to recreate a type from a previously generated PluginDescription.
  21751. @see PluginDescription::createInstance
  21752. */
  21753. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  21754. /** Should do a quick check to see if this file or directory might be a plugin of
  21755. this format.
  21756. This is for searching for potential files, so it shouldn't actually try to
  21757. load the plugin or do anything time-consuming.
  21758. */
  21759. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  21760. /** Returns a readable version of the name of the plugin that this identifier refers to.
  21761. */
  21762. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  21763. /** Checks whether this plugin could possibly be loaded.
  21764. It doesn't actually need to load it, just to check whether the file or component
  21765. still exists.
  21766. */
  21767. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  21768. /** Searches a suggested set of directories for any plugins in this format.
  21769. The path might be ignored, e.g. by AUs, which are found by the OS rather
  21770. than manually.
  21771. */
  21772. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  21773. const bool recursive) = 0;
  21774. /** Returns the typical places to look for this kind of plugin.
  21775. Note that if this returns no paths, it means that the format can't be scanned-for
  21776. (i.e. it's an internal format that doesn't live in files)
  21777. */
  21778. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  21779. juce_UseDebuggingNewOperator
  21780. protected:
  21781. AudioPluginFormat() throw();
  21782. AudioPluginFormat (const AudioPluginFormat&);
  21783. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  21784. };
  21785. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21786. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  21787. /**
  21788. This maintains a list of known AudioPluginFormats.
  21789. @see AudioPluginFormat
  21790. */
  21791. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  21792. {
  21793. public:
  21794. AudioPluginFormatManager() throw();
  21795. /** Destructor. */
  21796. ~AudioPluginFormatManager() throw();
  21797. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  21798. /** Adds any formats that it knows about, e.g. VST.
  21799. */
  21800. void addDefaultFormats();
  21801. /** Returns the number of types of format that are available.
  21802. Use getFormat() to get one of them.
  21803. */
  21804. int getNumFormats() throw();
  21805. /** Returns one of the available formats.
  21806. @see getNumFormats
  21807. */
  21808. AudioPluginFormat* getFormat (const int index) throw();
  21809. /** Adds a format to the list.
  21810. The object passed in will be owned and deleted by the manager.
  21811. */
  21812. void addFormat (AudioPluginFormat* const format) throw();
  21813. /** Tries to load the type for this description, by trying all the formats
  21814. that this manager knows about.
  21815. The caller is responsible for deleting the object that is returned.
  21816. If it can't load the plugin, it returns 0 and leaves a message in the
  21817. errorMessage string.
  21818. */
  21819. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  21820. String& errorMessage) const;
  21821. /** Checks that the file or component for this plugin actually still exists.
  21822. (This won't try to load the plugin)
  21823. */
  21824. bool doesPluginStillExist (const PluginDescription& description) const;
  21825. juce_UseDebuggingNewOperator
  21826. private:
  21827. OwnedArray <AudioPluginFormat> formats;
  21828. AudioPluginFormatManager (const AudioPluginFormatManager&);
  21829. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  21830. };
  21831. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21832. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21833. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21834. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21835. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21836. /********* Start of inlined file: juce_PopupMenu.h *********/
  21837. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21838. #define __JUCE_POPUPMENU_JUCEHEADER__
  21839. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21840. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21841. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21842. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21843. @see PopupMenu::addCustomItem
  21844. */
  21845. class JUCE_API PopupMenuCustomComponent : public Component
  21846. {
  21847. public:
  21848. /** Destructor. */
  21849. ~PopupMenuCustomComponent();
  21850. /** Chooses the size that this component would like to have.
  21851. Note that the size which this method returns isn't necessarily the one that
  21852. the menu will give it, as it will be stretched to fit the other items in
  21853. the menu.
  21854. */
  21855. virtual void getIdealSize (int& idealWidth,
  21856. int& idealHeight) = 0;
  21857. /** Dismisses the menu indicating that this item has been chosen.
  21858. This will cause the menu to exit from its modal state, returning
  21859. this item's id as the result.
  21860. */
  21861. void triggerMenuItem();
  21862. /** Returns true if this item should be highlighted because the mouse is
  21863. over it.
  21864. You can call this method in your paint() method to find out whether
  21865. to draw a highlight.
  21866. */
  21867. bool isItemHighlighted() const throw() { return isHighlighted; }
  21868. protected:
  21869. /** Constructor.
  21870. If isTriggeredAutomatically is true, then the menu will automatically detect
  21871. a click on this component and use that to trigger it. If it's false, then it's
  21872. up to your class to manually trigger the item if it wants to.
  21873. */
  21874. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21875. private:
  21876. friend class MenuItemInfo;
  21877. friend class MenuItemComponent;
  21878. friend class PopupMenuWindow;
  21879. int refCount_;
  21880. bool isHighlighted, isTriggeredAutomatically;
  21881. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21882. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21883. };
  21884. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21885. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21886. /** Creates and displays a popup-menu.
  21887. To show a popup-menu, you create one of these, add some items to it, then
  21888. call its show() method, which returns the id of the item the user selects.
  21889. E.g. @code
  21890. void MyWidget::mouseDown (const MouseEvent& e)
  21891. {
  21892. PopupMenu m;
  21893. m.addItem (1, "item 1");
  21894. m.addItem (2, "item 2");
  21895. const int result = m.show();
  21896. if (result == 0)
  21897. {
  21898. // user dismissed the menu without picking anything
  21899. }
  21900. else if (result == 1)
  21901. {
  21902. // user picked item 1
  21903. }
  21904. else if (result == 2)
  21905. {
  21906. // user picked item 2
  21907. }
  21908. }
  21909. @endcode
  21910. Submenus are easy too: @code
  21911. void MyWidget::mouseDown (const MouseEvent& e)
  21912. {
  21913. PopupMenu subMenu;
  21914. subMenu.addItem (1, "item 1");
  21915. subMenu.addItem (2, "item 2");
  21916. PopupMenu mainMenu;
  21917. mainMenu.addItem (3, "item 3");
  21918. mainMenu.addSubMenu ("other choices", subMenu);
  21919. const int result = m.show();
  21920. ...etc
  21921. }
  21922. @endcode
  21923. */
  21924. class JUCE_API PopupMenu
  21925. {
  21926. public:
  21927. /** Creates an empty popup menu. */
  21928. PopupMenu() throw();
  21929. /** Creates a copy of another menu. */
  21930. PopupMenu (const PopupMenu& other) throw();
  21931. /** Destructor. */
  21932. ~PopupMenu() throw();
  21933. /** Copies this menu from another one. */
  21934. const PopupMenu& operator= (const PopupMenu& other) throw();
  21935. /** Resets the menu, removing all its items. */
  21936. void clear() throw();
  21937. /** Appends a new text item for this menu to show.
  21938. @param itemResultId the number that will be returned from the show() method
  21939. if the user picks this item. The value should never be
  21940. zero, because that's used to indicate that the user didn't
  21941. select anything.
  21942. @param itemText the text to show.
  21943. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21944. picked
  21945. @param isTicked if true, the item will be shown with a tick next to it
  21946. @param iconToUse if this is non-zero, it should be an image that will be
  21947. displayed to the left of the item. This method will take its
  21948. own copy of the image passed-in, so there's no need to keep
  21949. it hanging around.
  21950. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21951. */
  21952. void addItem (const int itemResultId,
  21953. const String& itemText,
  21954. const bool isActive = true,
  21955. const bool isTicked = false,
  21956. const Image* const iconToUse = 0) throw();
  21957. /** Adds an item that represents one of the commands in a command manager object.
  21958. @param commandManager the manager to use to trigger the command and get information
  21959. about it
  21960. @param commandID the ID of the command
  21961. @param displayName if this is non-empty, then this string will be used instead of
  21962. the command's registered name
  21963. */
  21964. void addCommandItem (ApplicationCommandManager* commandManager,
  21965. const int commandID,
  21966. const String& displayName = String::empty) throw();
  21967. /** Appends a text item with a special colour.
  21968. This is the same as addItem(), but specifies a colour to use for the
  21969. text, which will override the default colours that are used by the
  21970. current look-and-feel. See addItem() for a description of the parameters.
  21971. */
  21972. void addColouredItem (const int itemResultId,
  21973. const String& itemText,
  21974. const Colour& itemTextColour,
  21975. const bool isActive = true,
  21976. const bool isTicked = false,
  21977. const Image* const iconToUse = 0) throw();
  21978. /** Appends a custom menu item.
  21979. This will add a user-defined component to use as a menu item. The component
  21980. passed in will be deleted by this menu when it's no longer needed.
  21981. @see PopupMenuCustomComponent
  21982. */
  21983. void addCustomItem (const int itemResultId,
  21984. PopupMenuCustomComponent* const customComponent) throw();
  21985. /** Appends a custom menu item that can't be used to trigger a result.
  21986. This will add a user-defined component to use as a menu item. Unlike the
  21987. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21988. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21989. delete the component when it's finished, so it's the caller's responsibility
  21990. to manage the component that is passed-in.
  21991. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21992. detection of a mouse-click on your component, and use that to trigger the
  21993. menu ID specified in itemResultId. If this is false, the menu item can't
  21994. be triggered, so itemResultId is not used.
  21995. @see PopupMenuCustomComponent
  21996. */
  21997. void addCustomItem (const int itemResultId,
  21998. Component* customComponent,
  21999. int idealWidth, int idealHeight,
  22000. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  22001. /** Appends a sub-menu.
  22002. If the menu that's passed in is empty, it will appear as an inactive item.
  22003. */
  22004. void addSubMenu (const String& subMenuName,
  22005. const PopupMenu& subMenu,
  22006. const bool isActive = true,
  22007. Image* const iconToUse = 0,
  22008. const bool isTicked = false) throw();
  22009. /** Appends a separator to the menu, to help break it up into sections.
  22010. The menu class is smart enough not to display separators at the top or bottom
  22011. of the menu, and it will replace mutliple adjacent separators with a single
  22012. one, so your code can be quite free and easy about adding these, and it'll
  22013. always look ok.
  22014. */
  22015. void addSeparator() throw();
  22016. /** Adds a non-clickable text item to the menu.
  22017. This is a bold-font items which can be used as a header to separate the items
  22018. into named groups.
  22019. */
  22020. void addSectionHeader (const String& title) throw();
  22021. /** Returns the number of items that the menu currently contains.
  22022. (This doesn't count separators).
  22023. */
  22024. int getNumItems() const throw();
  22025. /** Returns true if the menu contains a command item that triggers the given command. */
  22026. bool containsCommandItem (const int commandID) const throw();
  22027. /** Returns true if the menu contains any items that can be used. */
  22028. bool containsAnyActiveItems() const throw();
  22029. /** Displays the menu and waits for the user to pick something.
  22030. This will display the menu modally, and return the ID of the item that the
  22031. user picks. If they click somewhere off the menu to get rid of it without
  22032. choosing anything, this will return 0.
  22033. The current location of the mouse will be used as the position to show the
  22034. menu - to explicitly set the menu's position, use showAt() instead. Depending
  22035. on where this point is on the screen, the menu will appear above, below or
  22036. to the side of the point.
  22037. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  22038. then when the menu first appears, it will make sure
  22039. that this item is visible. So if the menu has too many
  22040. items to fit on the screen, it will be scrolled to a
  22041. position where this item is visible.
  22042. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  22043. than this if some items are too long to fit.
  22044. @param maximumNumColumns if there are too many items to fit on-screen in a single
  22045. vertical column, the menu may be laid out as a series of
  22046. columns - this is the maximum number allowed. To use the
  22047. default value for this (probably about 7), you can pass
  22048. in zero.
  22049. @param standardItemHeight if this is non-zero, it will be used as the standard
  22050. height for menu items (apart from custom items)
  22051. @see showAt
  22052. */
  22053. int show (const int itemIdThatMustBeVisible = 0,
  22054. const int minimumWidth = 0,
  22055. const int maximumNumColumns = 0,
  22056. const int standardItemHeight = 0);
  22057. /** Displays the menu at a specific location.
  22058. This is the same as show(), but uses a specific location (in global screen
  22059. co-ordinates) rather than the current mouse position.
  22060. Note that the co-ordinates don't specify the top-left of the menu - they
  22061. indicate a point of interest, and the menu will position itself nearby to
  22062. this point, trying to keep it fully on-screen.
  22063. @see show()
  22064. */
  22065. int showAt (const int screenX,
  22066. const int screenY,
  22067. const int itemIdThatMustBeVisible = 0,
  22068. const int minimumWidth = 0,
  22069. const int maximumNumColumns = 0,
  22070. const int standardItemHeight = 0);
  22071. /** Displays the menu as if it's attached to a component such as a button.
  22072. This is similar to showAt(), but will position it next to the given component, e.g.
  22073. so that the menu's edge is aligned with that of the component. This is intended for
  22074. things like buttons that trigger a pop-up menu.
  22075. */
  22076. int showAt (Component* componentToAttachTo,
  22077. const int itemIdThatMustBeVisible = 0,
  22078. const int minimumWidth = 0,
  22079. const int maximumNumColumns = 0,
  22080. const int standardItemHeight = 0);
  22081. /** Closes any menus that are currently open.
  22082. This might be useful if you have a situation where your window is being closed
  22083. by some means other than a user action, and you'd like to make sure that menus
  22084. aren't left hanging around.
  22085. */
  22086. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  22087. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  22088. This can be called before show() if you need a customised menu. Be careful
  22089. not to delete the LookAndFeel object before the menu has been deleted.
  22090. */
  22091. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  22092. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  22093. These constants can be used either via the LookAndFeel::setColour()
  22094. method for the look and feel that is set for this menu with setLookAndFeel()
  22095. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  22096. */
  22097. enum ColourIds
  22098. {
  22099. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  22100. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  22101. colour is specified when the item is added). */
  22102. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  22103. addSectionHeader() method). */
  22104. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  22105. highlighted menu item. */
  22106. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  22107. highlighted item. */
  22108. };
  22109. /**
  22110. Allows you to iterate through the items in a pop-up menu, and examine
  22111. their properties.
  22112. To use this, just create one and repeatedly call its next() method. When this
  22113. returns true, all the member variables of the iterator are filled-out with
  22114. information describing the menu item. When it returns false, the end of the
  22115. list has been reached.
  22116. */
  22117. class JUCE_API MenuItemIterator
  22118. {
  22119. public:
  22120. /** Creates an iterator that will scan through the items in the specified
  22121. menu.
  22122. Be careful not to add any items to a menu while it is being iterated,
  22123. or things could get out of step.
  22124. */
  22125. MenuItemIterator (const PopupMenu& menu) throw();
  22126. /** Destructor. */
  22127. ~MenuItemIterator() throw();
  22128. /** Returns true if there is another item, and sets up all this object's
  22129. member variables to reflect that item's properties.
  22130. */
  22131. bool next() throw();
  22132. String itemName;
  22133. const PopupMenu* subMenu;
  22134. int itemId;
  22135. bool isSeparator;
  22136. bool isTicked;
  22137. bool isEnabled;
  22138. bool isCustomComponent;
  22139. bool isSectionHeader;
  22140. const Colour* customColour;
  22141. const Image* customImage;
  22142. ApplicationCommandManager* commandManager;
  22143. juce_UseDebuggingNewOperator
  22144. private:
  22145. const PopupMenu& menu;
  22146. int index;
  22147. MenuItemIterator (const MenuItemIterator&);
  22148. const MenuItemIterator& operator= (const MenuItemIterator&);
  22149. };
  22150. juce_UseDebuggingNewOperator
  22151. private:
  22152. friend class PopupMenuWindow;
  22153. friend class MenuItemIterator;
  22154. VoidArray items;
  22155. LookAndFeel* lookAndFeel;
  22156. bool separatorPending;
  22157. void addSeparatorIfPending();
  22158. int showMenu (const int x, const int y, const int w, const int h,
  22159. const int itemIdThatMustBeVisible,
  22160. const int minimumWidth,
  22161. const int maximumNumColumns,
  22162. const int standardItemHeight,
  22163. const bool alignToRectangle,
  22164. Component* const componentAttachedTo) throw();
  22165. friend class MenuBarComponent;
  22166. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  22167. const int itemIdThatMustBeVisible,
  22168. const int minimumWidth,
  22169. const int maximumNumColumns,
  22170. const int standardItemHeight,
  22171. const bool alignToRectangle,
  22172. Component* menuBarComponent,
  22173. ApplicationCommandManager** managerOfChosenCommand,
  22174. Component* const componentAttachedTo) throw();
  22175. };
  22176. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  22177. /********* End of inlined file: juce_PopupMenu.h *********/
  22178. /**
  22179. Manages a list of plugin types.
  22180. This can be easily edited, saved and loaded, and used to create instances of
  22181. the plugin types in it.
  22182. @see PluginListComponent
  22183. */
  22184. class JUCE_API KnownPluginList : public ChangeBroadcaster
  22185. {
  22186. public:
  22187. /** Creates an empty list.
  22188. */
  22189. KnownPluginList();
  22190. /** Destructor. */
  22191. ~KnownPluginList();
  22192. /** Clears the list. */
  22193. void clear();
  22194. /** Returns the number of types currently in the list.
  22195. @see getType
  22196. */
  22197. int getNumTypes() const throw() { return types.size(); }
  22198. /** Returns one of the types.
  22199. @see getNumTypes
  22200. */
  22201. PluginDescription* getType (const int index) const throw() { return types [index]; }
  22202. /** Looks for a type in the list which comes from this file.
  22203. */
  22204. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  22205. /** Looks for a type in the list which matches a plugin type ID.
  22206. The identifierString parameter must have been created by
  22207. PluginDescription::createIdentifierString().
  22208. */
  22209. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  22210. /** Adds a type manually from its description. */
  22211. bool addType (const PluginDescription& type);
  22212. /** Removes a type. */
  22213. void removeType (const int index) throw();
  22214. /** Looks for all types that can be loaded from a given file, and adds them
  22215. to the list.
  22216. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  22217. re-tested if it's not already in the list, or if the file's modification
  22218. time has changed since the list was created. If dontRescanIfAlreadyInList is
  22219. false, the file will always be reloaded and tested.
  22220. Returns true if any new types were added, and all the types found in this
  22221. file (even if it was already known and hasn't been re-scanned) get returned
  22222. in the array.
  22223. */
  22224. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  22225. const bool dontRescanIfAlreadyInList,
  22226. OwnedArray <PluginDescription>& typesFound,
  22227. AudioPluginFormat& formatToUse);
  22228. /** Returns true if the specified file is already known about and if it
  22229. hasn't been modified since our entry was created.
  22230. */
  22231. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  22232. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  22233. If any types are found in the files, their descriptions are returned in the array.
  22234. */
  22235. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  22236. OwnedArray <PluginDescription>& typesFound);
  22237. /** Sort methods used to change the order of the plugins in the list.
  22238. */
  22239. enum SortMethod
  22240. {
  22241. defaultOrder = 0,
  22242. sortAlphabetically,
  22243. sortByCategory,
  22244. sortByManufacturer,
  22245. sortByFileSystemLocation
  22246. };
  22247. /** Adds all the plugin types to a popup menu so that the user can select one.
  22248. Depending on the sort method, it may add sub-menus for categories,
  22249. manufacturers, etc.
  22250. Use getIndexChosenByMenu() to find out the type that was chosen.
  22251. */
  22252. void addToMenu (PopupMenu& menu,
  22253. const SortMethod sortMethod) const;
  22254. /** Converts a menu item index that has been chosen into its index in this list.
  22255. Returns -1 if it's not an ID that was used.
  22256. @see addToMenu
  22257. */
  22258. int getIndexChosenByMenu (const int menuResultCode) const;
  22259. /** Sorts the list. */
  22260. void sort (const SortMethod method);
  22261. /** Creates some XML that can be used to store the state of this list.
  22262. */
  22263. XmlElement* createXml() const;
  22264. /** Recreates the state of this list from its stored XML format.
  22265. */
  22266. void recreateFromXml (const XmlElement& xml);
  22267. juce_UseDebuggingNewOperator
  22268. private:
  22269. OwnedArray <PluginDescription> types;
  22270. KnownPluginList (const KnownPluginList&);
  22271. const KnownPluginList& operator= (const KnownPluginList&);
  22272. };
  22273. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  22274. /********* End of inlined file: juce_KnownPluginList.h *********/
  22275. /**
  22276. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  22277. Use one of these objects if you want to wire-up a set of AudioProcessors
  22278. and play back the result.
  22279. Processors can be added to the graph as "nodes" using addNode(), and once
  22280. added, you can connect any of their input or output channels to other
  22281. nodes using addConnection().
  22282. To play back a graph through an audio device, you might want to use an
  22283. AudioProcessorPlayer object.
  22284. */
  22285. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  22286. public AsyncUpdater
  22287. {
  22288. public:
  22289. /** Creates an empty graph.
  22290. */
  22291. AudioProcessorGraph();
  22292. /** Destructor.
  22293. Any processor objects that have been added to the graph will also be deleted.
  22294. */
  22295. ~AudioProcessorGraph();
  22296. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  22297. To create a node, call AudioProcessorGraph::addNode().
  22298. */
  22299. class JUCE_API Node : public ReferenceCountedObject
  22300. {
  22301. public:
  22302. /** Destructor.
  22303. */
  22304. ~Node();
  22305. /** The ID number assigned to this node.
  22306. This is assigned by the graph that owns it, and can't be changed.
  22307. */
  22308. const uint32 id;
  22309. /** The actual processor object that this node represents.
  22310. */
  22311. AudioProcessor* const processor;
  22312. /** A set of user-definable properties that are associated with this node.
  22313. This can be used to attach values to the node for whatever purpose seems
  22314. useful. For example, you might store an x and y position if your application
  22315. is displaying the nodes on-screen.
  22316. */
  22317. PropertySet properties;
  22318. /** A convenient typedef for referring to a pointer to a node object.
  22319. */
  22320. typedef ReferenceCountedObjectPtr <Node> Ptr;
  22321. juce_UseDebuggingNewOperator
  22322. private:
  22323. friend class AudioProcessorGraph;
  22324. bool isPrepared;
  22325. Node (const uint32 id, AudioProcessor* const processor) throw();
  22326. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  22327. void unprepare();
  22328. Node (const Node&);
  22329. const Node& operator= (const Node&);
  22330. };
  22331. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  22332. To create a connection, use AudioProcessorGraph::addConnection().
  22333. */
  22334. struct JUCE_API Connection
  22335. {
  22336. public:
  22337. /** The ID number of the node which is the input source for this connection.
  22338. @see AudioProcessorGraph::getNodeForId
  22339. */
  22340. uint32 sourceNodeId;
  22341. /** The index of the output channel of the source node from which this
  22342. connection takes its data.
  22343. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  22344. it is referring to the source node's midi output. Otherwise, it is the zero-based
  22345. index of an audio output channel in the source node.
  22346. */
  22347. int sourceChannelIndex;
  22348. /** The ID number of the node which is the destination for this connection.
  22349. @see AudioProcessorGraph::getNodeForId
  22350. */
  22351. uint32 destNodeId;
  22352. /** The index of the input channel of the destination node to which this
  22353. connection delivers its data.
  22354. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  22355. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  22356. index of an audio input channel in the destination node.
  22357. */
  22358. int destChannelIndex;
  22359. juce_UseDebuggingNewOperator
  22360. private:
  22361. };
  22362. /** Deletes all nodes and connections from this graph.
  22363. Any processor objects in the graph will be deleted.
  22364. */
  22365. void clear();
  22366. /** Returns the number of nodes in the graph. */
  22367. int getNumNodes() const throw() { return nodes.size(); }
  22368. /** Returns a pointer to one of the nodes in the graph.
  22369. This will return 0 if the index is out of range.
  22370. @see getNodeForId
  22371. */
  22372. Node* getNode (const int index) const throw() { return nodes [index]; }
  22373. /** Searches the graph for a node with the given ID number and returns it.
  22374. If no such node was found, this returns 0.
  22375. @see getNode
  22376. */
  22377. Node* getNodeForId (const uint32 nodeId) const throw();
  22378. /** Adds a node to the graph.
  22379. This creates a new node in the graph, for the specified processor. Once you have
  22380. added a processor to the graph, the graph owns it and will delete it later when
  22381. it is no longer needed.
  22382. The optional nodeId parameter lets you specify an ID to use for the node, but
  22383. if the value is already in use, this new node will overwrite the old one.
  22384. If this succeeds, it returns a pointer to the newly-created node.
  22385. */
  22386. Node* addNode (AudioProcessor* const newProcessor,
  22387. uint32 nodeId = 0);
  22388. /** Deletes a node within the graph which has the specified ID.
  22389. This will also delete any connections that are attached to this node.
  22390. */
  22391. bool removeNode (const uint32 nodeId);
  22392. /** Returns the number of connections in the graph. */
  22393. int getNumConnections() const throw() { return connections.size(); }
  22394. /** Returns a pointer to one of the connections in the graph. */
  22395. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  22396. /** Searches for a connection between some specified channels.
  22397. If no such connection is found, this returns 0.
  22398. */
  22399. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  22400. const int sourceChannelIndex,
  22401. const uint32 destNodeId,
  22402. const int destChannelIndex) const throw();
  22403. /** Returns true if there is a connection between any of the channels of
  22404. two specified nodes.
  22405. */
  22406. bool isConnected (const uint32 possibleSourceNodeId,
  22407. const uint32 possibleDestNodeId) const throw();
  22408. /** Returns true if it would be legal to connect the specified points.
  22409. */
  22410. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  22411. const uint32 destNodeId, const int destChannelIndex) const throw();
  22412. /** Attempts to connect two specified channels of two nodes.
  22413. If this isn't allowed (e.g. because you're trying to connect a midi channel
  22414. to an audio one or other such nonsense), then it'll return false.
  22415. */
  22416. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22417. const uint32 destNodeId, const int destChannelIndex);
  22418. /** Deletes the connection with the specified index.
  22419. Returns true if a connection was actually deleted.
  22420. */
  22421. void removeConnection (const int index);
  22422. /** Deletes any connection between two specified points.
  22423. Returns true if a connection was actually deleted.
  22424. */
  22425. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22426. const uint32 destNodeId, const int destChannelIndex);
  22427. /** Removes all connections from the specified node.
  22428. */
  22429. bool disconnectNode (const uint32 nodeId);
  22430. /** Performs a sanity checks of all the connections.
  22431. This might be useful if some of the processors are doing things like changing
  22432. their channel counts, which could render some connections obsolete.
  22433. */
  22434. bool removeIllegalConnections();
  22435. /** A special number that represents the midi channel of a node.
  22436. This is used as a channel index value if you want to refer to the midi input
  22437. or output instead of an audio channel.
  22438. */
  22439. static const int midiChannelIndex;
  22440. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  22441. in order to use the audio that comes into and out of the graph itself.
  22442. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  22443. node in the graph which delivers the audio that is coming into the parent
  22444. graph. This allows you to stream the data to other nodes and process the
  22445. incoming audio.
  22446. Likewise, one of these in "output" mode can be sent data which it will add to
  22447. the sum of data being sent to the graph's output.
  22448. @see AudioProcessorGraph
  22449. */
  22450. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  22451. {
  22452. public:
  22453. /** Specifies the mode in which this processor will operate.
  22454. */
  22455. enum IODeviceType
  22456. {
  22457. audioInputNode, /**< In this mode, the processor has output channels
  22458. representing all the audio input channels that are
  22459. coming into its parent audio graph. */
  22460. audioOutputNode, /**< In this mode, the processor has input channels
  22461. representing all the audio output channels that are
  22462. going out of its parent audio graph. */
  22463. midiInputNode, /**< In this mode, the processor has a midi output which
  22464. delivers the same midi data that is arriving at its
  22465. parent graph. */
  22466. midiOutputNode /**< In this mode, the processor has a midi input and
  22467. any data sent to it will be passed out of the parent
  22468. graph. */
  22469. };
  22470. /** Returns the mode of this processor. */
  22471. IODeviceType getType() const throw() { return type; }
  22472. /** Returns the parent graph to which this processor belongs, or 0 if it
  22473. hasn't yet been added to one. */
  22474. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  22475. /** True if this is an audio or midi input. */
  22476. bool isInput() const throw();
  22477. /** True if this is an audio or midi output. */
  22478. bool isOutput() const throw();
  22479. AudioGraphIOProcessor (const IODeviceType type);
  22480. ~AudioGraphIOProcessor();
  22481. const String getName() const;
  22482. void fillInPluginDescription (PluginDescription& d) const;
  22483. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22484. void releaseResources();
  22485. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  22486. const String getInputChannelName (const int channelIndex) const;
  22487. const String getOutputChannelName (const int channelIndex) const;
  22488. bool isInputChannelStereoPair (int index) const;
  22489. bool isOutputChannelStereoPair (int index) const;
  22490. bool acceptsMidi() const;
  22491. bool producesMidi() const;
  22492. AudioProcessorEditor* createEditor();
  22493. int getNumParameters();
  22494. const String getParameterName (int);
  22495. float getParameter (int);
  22496. const String getParameterText (int);
  22497. void setParameter (int, float);
  22498. int getNumPrograms();
  22499. int getCurrentProgram();
  22500. void setCurrentProgram (int);
  22501. const String getProgramName (int);
  22502. void changeProgramName (int, const String&);
  22503. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22504. void setStateInformation (const void* data, int sizeInBytes);
  22505. /** @internal */
  22506. void setParentGraph (AudioProcessorGraph* const graph) throw();
  22507. juce_UseDebuggingNewOperator
  22508. private:
  22509. const IODeviceType type;
  22510. AudioProcessorGraph* graph;
  22511. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  22512. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  22513. };
  22514. // AudioProcessor methods:
  22515. const String getName() const;
  22516. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22517. void releaseResources();
  22518. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  22519. const String getInputChannelName (const int channelIndex) const;
  22520. const String getOutputChannelName (const int channelIndex) const;
  22521. bool isInputChannelStereoPair (int index) const;
  22522. bool isOutputChannelStereoPair (int index) const;
  22523. bool acceptsMidi() const;
  22524. bool producesMidi() const;
  22525. AudioProcessorEditor* createEditor() { return 0; }
  22526. int getNumParameters() { return 0; }
  22527. const String getParameterName (int) { return String::empty; }
  22528. float getParameter (int) { return 0; }
  22529. const String getParameterText (int) { return String::empty; }
  22530. void setParameter (int, float) { }
  22531. int getNumPrograms() { return 0; }
  22532. int getCurrentProgram() { return 0; }
  22533. void setCurrentProgram (int) { }
  22534. const String getProgramName (int) { return String::empty; }
  22535. void changeProgramName (int, const String&) { }
  22536. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22537. void setStateInformation (const void* data, int sizeInBytes);
  22538. /** @internal */
  22539. void handleAsyncUpdate();
  22540. juce_UseDebuggingNewOperator
  22541. private:
  22542. ReferenceCountedArray <Node> nodes;
  22543. OwnedArray <Connection> connections;
  22544. int lastNodeId;
  22545. AudioSampleBuffer renderingBuffers;
  22546. OwnedArray <MidiBuffer> midiBuffers;
  22547. CriticalSection renderLock;
  22548. VoidArray renderingOps;
  22549. friend class AudioGraphIOProcessor;
  22550. AudioSampleBuffer* currentAudioInputBuffer;
  22551. AudioSampleBuffer currentAudioOutputBuffer;
  22552. MidiBuffer* currentMidiInputBuffer;
  22553. MidiBuffer currentMidiOutputBuffer;
  22554. void clearRenderingSequence();
  22555. void buildRenderingSequence();
  22556. bool isAnInputTo (const uint32 possibleInputId,
  22557. const uint32 possibleDestinationId,
  22558. const int recursionCheck) const throw();
  22559. AudioProcessorGraph (const AudioProcessorGraph&);
  22560. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  22561. };
  22562. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  22563. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  22564. #endif
  22565. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  22566. #endif
  22567. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22568. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  22569. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22570. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22571. /********* Start of inlined file: juce_AudioIODevice.h *********/
  22572. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22573. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22574. class AudioIODevice;
  22575. /**
  22576. One of these is passed to an AudioIODevice object to stream the audio data
  22577. in and out.
  22578. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  22579. method on its own high-priority audio thread, when it needs to send or receive
  22580. the next block of data.
  22581. @see AudioIODevice, AudioDeviceManager
  22582. */
  22583. class JUCE_API AudioIODeviceCallback
  22584. {
  22585. public:
  22586. /** Destructor. */
  22587. virtual ~AudioIODeviceCallback() {}
  22588. /** Processes a block of incoming and outgoing audio data.
  22589. The subclass's implementation should use the incoming audio for whatever
  22590. purposes it needs to, and must fill all the output channels with the next
  22591. block of output data before returning.
  22592. The channel data is arranged with the same array indices as the channel name
  22593. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  22594. that aren't specified in AudioIODevice::open() will have a null pointer for their
  22595. associated channel, so remember to check for this.
  22596. @param inputChannelData a set of arrays containing the audio data for each
  22597. incoming channel - this data is valid until the function
  22598. returns. There will be one channel of data for each input
  22599. channel that was enabled when the audio device was opened
  22600. (see AudioIODevice::open())
  22601. @param numInputChannels the number of pointers to channel data in the
  22602. inputChannelData array.
  22603. @param outputChannelData a set of arrays which need to be filled with the data
  22604. that should be sent to each outgoing channel of the device.
  22605. There will be one channel of data for each output channel
  22606. that was enabled when the audio device was opened (see
  22607. AudioIODevice::open())
  22608. The initial contents of the array is undefined, so the
  22609. callback function must fill all the channels with zeros if
  22610. its output is silence. Failing to do this could cause quite
  22611. an unpleasant noise!
  22612. @param numOutputChannels the number of pointers to channel data in the
  22613. outputChannelData array.
  22614. @param numSamples the number of samples in each channel of the input and
  22615. output arrays. The number of samples will depend on the
  22616. audio device's buffer size and will usually remain constant,
  22617. although this isn't guaranteed, so make sure your code can
  22618. cope with reasonable changes in the buffer size from one
  22619. callback to the next.
  22620. */
  22621. virtual void audioDeviceIOCallback (const float** inputChannelData,
  22622. int numInputChannels,
  22623. float** outputChannelData,
  22624. int numOutputChannels,
  22625. int numSamples) = 0;
  22626. /** Called to indicate that the device is about to start calling back.
  22627. This will be called just before the audio callbacks begin, either when this
  22628. callback has just been added to an audio device, or after the device has been
  22629. restarted because of a sample-rate or block-size change.
  22630. You can use this opportunity to find out the sample rate and block size
  22631. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  22632. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  22633. @param device the audio IO device that will be used to drive the callback.
  22634. Note that if you're going to store this this pointer, it is
  22635. only valid until the next time that audioDeviceStopped is called.
  22636. */
  22637. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  22638. /** Called to indicate that the device has stopped.
  22639. */
  22640. virtual void audioDeviceStopped() = 0;
  22641. };
  22642. /**
  22643. Base class for an audio device with synchronised input and output channels.
  22644. Subclasses of this are used to implement different protocols such as DirectSound,
  22645. ASIO, CoreAudio, etc.
  22646. To create one of these, you'll need to use the AudioIODeviceType class - see the
  22647. documentation for that class for more info.
  22648. For an easier way of managing audio devices and their settings, have a look at the
  22649. AudioDeviceManager class.
  22650. @see AudioIODeviceType, AudioDeviceManager
  22651. */
  22652. class JUCE_API AudioIODevice
  22653. {
  22654. public:
  22655. /** Destructor. */
  22656. virtual ~AudioIODevice();
  22657. /** Returns the device's name, (as set in the constructor). */
  22658. const String& getName() const throw() { return name; }
  22659. /** Returns the type of the device.
  22660. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  22661. */
  22662. const String& getTypeName() const throw() { return typeName; }
  22663. /** Returns the names of all the available output channels on this device.
  22664. To find out which of these are currently in use, call getActiveOutputChannels().
  22665. */
  22666. virtual const StringArray getOutputChannelNames() = 0;
  22667. /** Returns the names of all the available input channels on this device.
  22668. To find out which of these are currently in use, call getActiveInputChannels().
  22669. */
  22670. virtual const StringArray getInputChannelNames() = 0;
  22671. /** Returns the number of sample-rates this device supports.
  22672. To find out which rates are available on this device, use this method to
  22673. find out how many there are, and getSampleRate() to get the rates.
  22674. @see getSampleRate
  22675. */
  22676. virtual int getNumSampleRates() = 0;
  22677. /** Returns one of the sample-rates this device supports.
  22678. To find out which rates are available on this device, use getNumSampleRates() to
  22679. find out how many there are, and getSampleRate() to get the individual rates.
  22680. The sample rate is set by the open() method.
  22681. (Note that for DirectSound some rates might not work, depending on combinations
  22682. of i/o channels that are being opened).
  22683. @see getNumSampleRates
  22684. */
  22685. virtual double getSampleRate (int index) = 0;
  22686. /** Returns the number of sizes of buffer that are available.
  22687. @see getBufferSizeSamples, getDefaultBufferSize
  22688. */
  22689. virtual int getNumBufferSizesAvailable() = 0;
  22690. /** Returns one of the possible buffer-sizes.
  22691. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  22692. @returns a number of samples
  22693. @see getNumBufferSizesAvailable, getDefaultBufferSize
  22694. */
  22695. virtual int getBufferSizeSamples (int index) = 0;
  22696. /** Returns the default buffer-size to use.
  22697. @returns a number of samples
  22698. @see getNumBufferSizesAvailable, getBufferSizeSamples
  22699. */
  22700. virtual int getDefaultBufferSize() = 0;
  22701. /** Tries to open the device ready to play.
  22702. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  22703. input channel should be enabled
  22704. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  22705. output channel should be enabled
  22706. @param sampleRate the sample rate to try to use - to find out which rates are
  22707. available, see getNumSampleRates() and getSampleRate()
  22708. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  22709. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  22710. @returns an error description if there's a problem, or an empty string if it succeeds in
  22711. opening the device
  22712. @see close
  22713. */
  22714. virtual const String open (const BitArray& inputChannels,
  22715. const BitArray& outputChannels,
  22716. double sampleRate,
  22717. int bufferSizeSamples) = 0;
  22718. /** Closes and releases the device if it's open. */
  22719. virtual void close() = 0;
  22720. /** Returns true if the device is still open.
  22721. A device might spontaneously close itself if something goes wrong, so this checks if
  22722. it's still open.
  22723. */
  22724. virtual bool isOpen() = 0;
  22725. /** Starts the device actually playing.
  22726. This must be called after the device has been opened.
  22727. @param callback the callback to use for streaming the data.
  22728. @see AudioIODeviceCallback, open
  22729. */
  22730. virtual void start (AudioIODeviceCallback* callback) = 0;
  22731. /** Stops the device playing.
  22732. Once a device has been started, this will stop it. Any pending calls to the
  22733. callback class will be flushed before this method returns.
  22734. */
  22735. virtual void stop() = 0;
  22736. /** Returns true if the device is still calling back.
  22737. The device might mysteriously stop, so this checks whether it's
  22738. still playing.
  22739. */
  22740. virtual bool isPlaying() = 0;
  22741. /** Returns the last error that happened if anything went wrong. */
  22742. virtual const String getLastError() = 0;
  22743. /** Returns the buffer size that the device is currently using.
  22744. If the device isn't actually open, this value doesn't really mean much.
  22745. */
  22746. virtual int getCurrentBufferSizeSamples() = 0;
  22747. /** Returns the sample rate that the device is currently using.
  22748. If the device isn't actually open, this value doesn't really mean much.
  22749. */
  22750. virtual double getCurrentSampleRate() = 0;
  22751. /** Returns the device's current physical bit-depth.
  22752. If the device isn't actually open, this value doesn't really mean much.
  22753. */
  22754. virtual int getCurrentBitDepth() = 0;
  22755. /** Returns a mask showing which of the available output channels are currently
  22756. enabled.
  22757. @see getOutputChannelNames
  22758. */
  22759. virtual const BitArray getActiveOutputChannels() const = 0;
  22760. /** Returns a mask showing which of the available input channels are currently
  22761. enabled.
  22762. @see getInputChannelNames
  22763. */
  22764. virtual const BitArray getActiveInputChannels() const = 0;
  22765. /** Returns the device's output latency.
  22766. This is the delay in samples between a callback getting a block of data, and
  22767. that data actually getting played.
  22768. */
  22769. virtual int getOutputLatencyInSamples() = 0;
  22770. /** Returns the device's input latency.
  22771. This is the delay in samples between some audio actually arriving at the soundcard,
  22772. and the callback getting passed this block of data.
  22773. */
  22774. virtual int getInputLatencyInSamples() = 0;
  22775. /** True if this device can show a pop-up control panel for editing its settings.
  22776. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22777. to display it.
  22778. */
  22779. virtual bool hasControlPanel() const;
  22780. /** Shows a device-specific control panel if there is one.
  22781. This should only be called for devices which return true from hasControlPanel().
  22782. */
  22783. virtual bool showControlPanel();
  22784. protected:
  22785. /** Creates a device, setting its name and type member variables. */
  22786. AudioIODevice (const String& deviceName,
  22787. const String& typeName);
  22788. /** @internal */
  22789. String name, typeName;
  22790. };
  22791. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22792. /********* End of inlined file: juce_AudioIODevice.h *********/
  22793. /**
  22794. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  22795. To use one of these, just make it the callback used by your AudioIODevice, and
  22796. give it a processor to use by calling setProcessor().
  22797. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  22798. input to send both streams through the processor.
  22799. @see AudioProcessor, AudioProcessorGraph
  22800. */
  22801. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  22802. public MidiInputCallback
  22803. {
  22804. public:
  22805. /**
  22806. */
  22807. AudioProcessorPlayer();
  22808. /** Destructor. */
  22809. virtual ~AudioProcessorPlayer();
  22810. /** Sets the processor that should be played.
  22811. The processor that is passed in will not be deleted or owned by this object.
  22812. To stop anything playing, pass in 0 to this method.
  22813. */
  22814. void setProcessor (AudioProcessor* const processorToPlay);
  22815. /** Returns the current audio processor that is being played.
  22816. */
  22817. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  22818. /** Returns a midi message collector that you can pass midi messages to if you
  22819. want them to be injected into the midi stream that is being sent to the
  22820. processor.
  22821. */
  22822. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  22823. /** @internal */
  22824. void audioDeviceIOCallback (const float** inputChannelData,
  22825. int totalNumInputChannels,
  22826. float** outputChannelData,
  22827. int totalNumOutputChannels,
  22828. int numSamples);
  22829. /** @internal */
  22830. void audioDeviceAboutToStart (AudioIODevice* device);
  22831. /** @internal */
  22832. void audioDeviceStopped();
  22833. /** @internal */
  22834. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22835. juce_UseDebuggingNewOperator
  22836. private:
  22837. AudioProcessor* processor;
  22838. CriticalSection lock;
  22839. double sampleRate;
  22840. int blockSize;
  22841. bool isPrepared;
  22842. int numInputChans, numOutputChans;
  22843. float* channels [128];
  22844. AudioSampleBuffer tempBuffer;
  22845. MidiBuffer incomingMidi;
  22846. MidiMessageCollector messageCollector;
  22847. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22848. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22849. };
  22850. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22851. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22852. #endif
  22853. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22854. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22855. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22856. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22857. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22858. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22859. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22860. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22861. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22862. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22863. class EditableProperty;
  22864. /********* Start of inlined file: juce_TooltipClient.h *********/
  22865. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22866. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22867. /**
  22868. Components that want to use pop-up tooltips should implement this interface.
  22869. A TooltipWindow will wait for the mouse to hover over a component that
  22870. implements the TooltipClient interface, and when it finds one, it will display
  22871. the tooltip returned by its getTooltip() method.
  22872. @see TooltipWindow, SettableTooltipClient
  22873. */
  22874. class JUCE_API TooltipClient
  22875. {
  22876. public:
  22877. /** Destructor. */
  22878. virtual ~TooltipClient() {}
  22879. /** Returns the string that this object wants to show as its tooltip. */
  22880. virtual const String getTooltip() = 0;
  22881. };
  22882. /**
  22883. An implementation of TooltipClient that stores the tooltip string and a method
  22884. for changing it.
  22885. This makes it easy to add a tooltip to a custom component, by simply adding this
  22886. as a base class and calling setTooltip().
  22887. Many of the Juce widgets already use this as a base class to implement their
  22888. tooltips.
  22889. @see TooltipClient, TooltipWindow
  22890. */
  22891. class JUCE_API SettableTooltipClient : public TooltipClient
  22892. {
  22893. public:
  22894. /** Destructor. */
  22895. virtual ~SettableTooltipClient() {}
  22896. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22897. virtual const String getTooltip() { return tooltipString; }
  22898. juce_UseDebuggingNewOperator
  22899. protected:
  22900. String tooltipString;
  22901. };
  22902. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22903. /********* End of inlined file: juce_TooltipClient.h *********/
  22904. /**
  22905. A base class for a component that goes in a PropertyPanel and displays one of
  22906. an item's properties.
  22907. Subclasses of this are used to display a property in various forms, e.g. a
  22908. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22909. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22910. A subclass must implement the refresh() method which will be called to tell the
  22911. component to update itself, and is also responsible for calling this it when the
  22912. item that it refers to is changed.
  22913. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22914. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22915. */
  22916. class JUCE_API PropertyComponent : public Component,
  22917. public SettableTooltipClient
  22918. {
  22919. public:
  22920. /** Creates a PropertyComponent.
  22921. @param propertyName the name is stored as this component's name, and is
  22922. used as the name displayed next to this component in
  22923. a property panel
  22924. @param preferredHeight the height that the component should be given - some
  22925. items may need to be larger than a normal row height.
  22926. This value can also be set if a subclass changes the
  22927. preferredHeight member variable.
  22928. */
  22929. PropertyComponent (const String& propertyName,
  22930. const int preferredHeight = 25);
  22931. /** Destructor. */
  22932. ~PropertyComponent();
  22933. /** Returns this item's preferred height.
  22934. This value is specified either in the constructor or by a subclass changing the
  22935. preferredHeight member variable.
  22936. */
  22937. int getPreferredHeight() const throw() { return preferredHeight; }
  22938. /** Updates the property component if the item it refers to has changed.
  22939. A subclass must implement this method, and other objects may call it to
  22940. force it to refresh itself.
  22941. The subclass should be economical in the amount of work is done, so for
  22942. example it should check whether it really needs to do a repaint rather than
  22943. just doing one every time this method is called, as it may be called when
  22944. the value being displayed hasn't actually changed.
  22945. */
  22946. virtual void refresh() = 0;
  22947. /** The default paint method fills the background and draws a label for the
  22948. item's name.
  22949. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22950. */
  22951. void paint (Graphics& g);
  22952. /** The default resize method positions any child component to the right of this
  22953. one, based on the look and feel's default label size.
  22954. */
  22955. void resized();
  22956. /** By default, this just repaints the component. */
  22957. void enablementChanged();
  22958. juce_UseDebuggingNewOperator
  22959. protected:
  22960. /** Used by the PropertyPanel to determine how high this component needs to be.
  22961. A subclass can update this value in its constructor but shouldn't alter it later
  22962. as changes won't necessarily be picked up.
  22963. */
  22964. int preferredHeight;
  22965. };
  22966. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22967. /********* End of inlined file: juce_PropertyComponent.h *********/
  22968. /********* Start of inlined file: juce_Viewport.h *********/
  22969. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22970. #define __JUCE_VIEWPORT_JUCEHEADER__
  22971. /********* Start of inlined file: juce_ScrollBar.h *********/
  22972. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22973. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22974. /********* Start of inlined file: juce_Button.h *********/
  22975. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22976. #define __JUCE_BUTTON_JUCEHEADER__
  22977. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22978. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22979. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22980. /**
  22981. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22982. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22983. object.
  22984. The TooltipWindow object will then stay invisible, waiting until the mouse
  22985. hovers for the specified length of time - it will then see if it's currently
  22986. over a component which implements the TooltipClient interface, and if so,
  22987. it will make itself visible to show the tooltip in the appropriate place.
  22988. @see TooltipClient, SettableTooltipClient
  22989. */
  22990. class JUCE_API TooltipWindow : public Component,
  22991. private Timer
  22992. {
  22993. public:
  22994. /** Creates a tooltip window.
  22995. Make sure your app only creates one instance of this class, otherwise you'll
  22996. get multiple overlaid tooltips appearing. The window will initially be invisible
  22997. and will make itself visible when it needs to display a tip.
  22998. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22999. methods.
  23000. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  23001. otherwise the tooltip will be added to the given parent
  23002. component.
  23003. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  23004. before a tooltip will be shown
  23005. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  23006. */
  23007. TooltipWindow (Component* parentComponent = 0,
  23008. const int millisecondsBeforeTipAppears = 700);
  23009. /** Destructor. */
  23010. ~TooltipWindow();
  23011. /** Changes the time before the tip appears.
  23012. This lets you change the value that was set in the constructor.
  23013. */
  23014. void setMillisecondsBeforeTipAppears (const int newTimeMs = 700) throw();
  23015. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  23016. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23017. methods.
  23018. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23019. */
  23020. enum ColourIds
  23021. {
  23022. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  23023. textColourId = 0x1001c00, /**< The colour to use for the text. */
  23024. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  23025. };
  23026. juce_UseDebuggingNewOperator
  23027. private:
  23028. int millisecondsBeforeTipAppears;
  23029. int mouseX, mouseY, mouseClicks;
  23030. unsigned int lastCompChangeTime, lastHideTime;
  23031. Component* lastComponentUnderMouse;
  23032. bool changedCompsSinceShown;
  23033. String tipShowing, lastTipUnderMouse;
  23034. void paint (Graphics& g);
  23035. void mouseEnter (const MouseEvent& e);
  23036. void timerCallback();
  23037. static const String getTipFor (Component* const c);
  23038. void showFor (Component* const c, const String& tip);
  23039. void hide();
  23040. TooltipWindow (const TooltipWindow&);
  23041. const TooltipWindow& operator= (const TooltipWindow&);
  23042. };
  23043. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23044. /********* End of inlined file: juce_TooltipWindow.h *********/
  23045. class Button;
  23046. /**
  23047. Used to receive callbacks when a button is clicked.
  23048. @see Button::addButtonListener, Button::removeButtonListener
  23049. */
  23050. class JUCE_API ButtonListener
  23051. {
  23052. public:
  23053. /** Destructor. */
  23054. virtual ~ButtonListener() {}
  23055. /** Called when the button is clicked. */
  23056. virtual void buttonClicked (Button* button) = 0;
  23057. /** Called when the button's state changes. */
  23058. virtual void buttonStateChanged (Button*) {}
  23059. };
  23060. /**
  23061. A base class for buttons.
  23062. This contains all the logic for button behaviours such as enabling/disabling,
  23063. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  23064. and radio groups, etc.
  23065. @see TextButton, DrawableButton, ToggleButton
  23066. */
  23067. class JUCE_API Button : public Component,
  23068. public SettableTooltipClient,
  23069. public ApplicationCommandManagerListener,
  23070. private KeyListener
  23071. {
  23072. protected:
  23073. /** Creates a button.
  23074. @param buttonName the text to put in the button (the component's name is also
  23075. initially set to this string, but these can be changed later
  23076. using the setName() and setButtonText() methods)
  23077. */
  23078. Button (const String& buttonName);
  23079. public:
  23080. /** Destructor. */
  23081. virtual ~Button();
  23082. /** Changes the button's text.
  23083. @see getButtonText
  23084. */
  23085. void setButtonText (const String& newText) throw();
  23086. /** Returns the text displayed in the button.
  23087. @see setButtonText
  23088. */
  23089. const String getButtonText() const throw() { return text; }
  23090. /** Returns true if the button is currently being held down by the mouse.
  23091. @see isOver
  23092. */
  23093. bool isDown() const throw();
  23094. /** Returns true if the mouse is currently over the button.
  23095. This will be also be true if the mouse is being held down.
  23096. @see isDown
  23097. */
  23098. bool isOver() const throw();
  23099. /** A button has an on/off state associated with it, and this changes that.
  23100. By default buttons are 'off' and for simple buttons that you click to perform
  23101. an action you won't change this. Toggle buttons, however will want to
  23102. change their state when turned on or off.
  23103. @param shouldBeOn whether to set the button's toggle state to be on or
  23104. off. If it's a member of a button group, this will
  23105. always try to turn it on, and to turn off any other
  23106. buttons in the group
  23107. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  23108. the button will be repainted but no notification will
  23109. be sent
  23110. @see getToggleState, setRadioGroupId
  23111. */
  23112. void setToggleState (const bool shouldBeOn,
  23113. const bool sendChangeNotification);
  23114. /** Returns true if the button in 'on'.
  23115. By default buttons are 'off' and for simple buttons that you click to perform
  23116. an action you won't change this. Toggle buttons, however will want to
  23117. change their state when turned on or off.
  23118. @see setToggleState
  23119. */
  23120. bool getToggleState() const throw() { return isOn; }
  23121. /** This tells the button to automatically flip the toggle state when
  23122. the button is clicked.
  23123. If set to true, then before the clicked() callback occurs, the toggle-state
  23124. of the button is flipped.
  23125. */
  23126. void setClickingTogglesState (const bool shouldToggle) throw();
  23127. /** Returns true if this button is set to be an automatic toggle-button.
  23128. This returns the last value that was passed to setClickingTogglesState().
  23129. */
  23130. bool getClickingTogglesState() const throw();
  23131. /** Enables the button to act as a member of a mutually-exclusive group
  23132. of 'radio buttons'.
  23133. If the group ID is set to a non-zero number, then this button will
  23134. act as part of a group of buttons with the same ID, only one of
  23135. which can be 'on' at the same time. Note that when it's part of
  23136. a group, clicking a toggle-button that's 'on' won't turn it off.
  23137. To find other buttons with the same ID, this button will search through
  23138. its sibling components for ToggleButtons, so all the buttons for a
  23139. particular group must be placed inside the same parent component.
  23140. Set the group ID back to zero if you want it to act as a normal toggle
  23141. button again.
  23142. @see getRadioGroupId
  23143. */
  23144. void setRadioGroupId (const int newGroupId);
  23145. /** Returns the ID of the group to which this button belongs.
  23146. (See setRadioGroupId() for an explanation of this).
  23147. */
  23148. int getRadioGroupId() const throw() { return radioGroupId; }
  23149. /** Registers a listener to receive events when this button's state changes.
  23150. If the listener is already registered, this will not register it again.
  23151. @see removeButtonListener
  23152. */
  23153. void addButtonListener (ButtonListener* const newListener) throw();
  23154. /** Removes a previously-registered button listener
  23155. @see addButtonListener
  23156. */
  23157. void removeButtonListener (ButtonListener* const listener) throw();
  23158. /** Causes the button to act as if it's been clicked.
  23159. This will asynchronously make the button draw itself going down and up, and
  23160. will then call back the clicked() method as if mouse was clicked on it.
  23161. @see clicked
  23162. */
  23163. virtual void triggerClick();
  23164. /** Sets a command ID for this button to automatically invoke when it's clicked.
  23165. When the button is pressed, it will use the given manager to trigger the
  23166. command ID.
  23167. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  23168. before this button is. To disable the command triggering, call this method and
  23169. pass 0 for the parameters.
  23170. If generateTooltip is true, then the button's tooltip will be automatically
  23171. generated based on the name of this command and its current shortcut key.
  23172. @see addShortcut, getCommandID
  23173. */
  23174. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  23175. const int commandID,
  23176. const bool generateTooltip);
  23177. /** Returns the command ID that was set by setCommandToTrigger().
  23178. */
  23179. int getCommandID() const throw() { return commandID; }
  23180. /** Assigns a shortcut key to trigger the button.
  23181. The button registers itself with its top-level parent component for keypresses.
  23182. Note that a different way of linking buttons to keypresses is by using the
  23183. setCommandToTrigger() method to invoke a command.
  23184. @see clearShortcuts
  23185. */
  23186. void addShortcut (const KeyPress& key);
  23187. /** Removes all key shortcuts that had been set for this button.
  23188. @see addShortcut
  23189. */
  23190. void clearShortcuts();
  23191. /** Returns true if the given keypress is a shortcut for this button.
  23192. @see addShortcut
  23193. */
  23194. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  23195. /** Sets an auto-repeat speed for the button when it is held down.
  23196. (Auto-repeat is disabled by default).
  23197. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  23198. triggering the next click. If this is zero, auto-repeat
  23199. is disabled
  23200. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  23201. triggered
  23202. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  23203. get faster, the longer the button is held down, up to the
  23204. minimum interval specified here
  23205. */
  23206. void setRepeatSpeed (const int initialDelayInMillisecs,
  23207. const int repeatDelayInMillisecs,
  23208. const int minimumDelayInMillisecs = -1) throw();
  23209. /** Sets whether the button click should happen when the mouse is pressed or released.
  23210. By default the button is only considered to have been clicked when the mouse is
  23211. released, but setting this to true will make it call the clicked() method as soon
  23212. as the button is pressed.
  23213. This is useful if the button is being used to show a pop-up menu, as it allows
  23214. the click to be used as a drag onto the menu.
  23215. */
  23216. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  23217. /** Returns the number of milliseconds since the last time the button
  23218. went into the 'down' state.
  23219. */
  23220. uint32 getMillisecondsSinceButtonDown() const throw();
  23221. /** (overridden from Component to do special stuff). */
  23222. void setVisible (bool shouldBeVisible);
  23223. /** Sets the tooltip for this button.
  23224. @see TooltipClient, TooltipWindow
  23225. */
  23226. void setTooltip (const String& newTooltip);
  23227. // (implementation of the TooltipClient method)
  23228. const String getTooltip();
  23229. /** A combination of these flags are used by setConnectedEdges().
  23230. */
  23231. enum ConnectedEdgeFlags
  23232. {
  23233. ConnectedOnLeft = 1,
  23234. ConnectedOnRight = 2,
  23235. ConnectedOnTop = 4,
  23236. ConnectedOnBottom = 8
  23237. };
  23238. /** Hints about which edges of the button might be connected to adjoining buttons.
  23239. The value passed in is a bitwise combination of any of the values in the
  23240. ConnectedEdgeFlags enum.
  23241. E.g. if you are placing two buttons adjacent to each other, you could use this to
  23242. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  23243. without rounded corners on the edges that connect. It's only a hint, so the
  23244. LookAndFeel can choose to ignore it if it's not relevent for this type of
  23245. button.
  23246. */
  23247. void setConnectedEdges (const int connectedEdgeFlags) throw();
  23248. /** Returns the set of flags passed into setConnectedEdges(). */
  23249. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  23250. /** Indicates whether the button adjoins another one on its left edge.
  23251. @see setConnectedEdges
  23252. */
  23253. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  23254. /** Indicates whether the button adjoins another one on its right edge.
  23255. @see setConnectedEdges
  23256. */
  23257. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  23258. /** Indicates whether the button adjoins another one on its top edge.
  23259. @see setConnectedEdges
  23260. */
  23261. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  23262. /** Indicates whether the button adjoins another one on its bottom edge.
  23263. @see setConnectedEdges
  23264. */
  23265. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  23266. /** Used by setState(). */
  23267. enum ButtonState
  23268. {
  23269. buttonNormal,
  23270. buttonOver,
  23271. buttonDown
  23272. };
  23273. /** Can be used to force the button into a particular state.
  23274. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  23275. from happening.
  23276. The state that you set here will only last until it is automatically changed when the mouse
  23277. enters or exits the button, or the mouse-button is pressed or released.
  23278. */
  23279. void setState (const ButtonState newState);
  23280. juce_UseDebuggingNewOperator
  23281. protected:
  23282. /** This method is called when the button has been clicked.
  23283. Subclasses can override this to perform whatever they actions they need
  23284. to do.
  23285. Alternatively, a ButtonListener can be added to the button, and these listeners
  23286. will be called when the click occurs.
  23287. @see triggerClick
  23288. */
  23289. virtual void clicked();
  23290. /** This method is called when the button has been clicked.
  23291. By default it just calls clicked(), but you might want to override it to handle
  23292. things like clicking when a modifier key is pressed, etc.
  23293. @see ModifierKeys
  23294. */
  23295. virtual void clicked (const ModifierKeys& modifiers);
  23296. /** Subclasses should override this to actually paint the button's contents.
  23297. It's better to use this than the paint method, because it gives you information
  23298. about the over/down state of the button.
  23299. @param g the graphics context to use
  23300. @param isMouseOverButton true if the button is either in the 'over' or
  23301. 'down' state
  23302. @param isButtonDown true if the button should be drawn in the 'down' position
  23303. */
  23304. virtual void paintButton (Graphics& g,
  23305. bool isMouseOverButton,
  23306. bool isButtonDown) = 0;
  23307. /** Called when the button's up/down/over state changes.
  23308. Subclasses can override this if they need to do something special when the button
  23309. goes up or down.
  23310. @see isDown, isOver
  23311. */
  23312. virtual void buttonStateChanged();
  23313. /** @internal */
  23314. virtual void internalClickCallback (const ModifierKeys& modifiers);
  23315. /** @internal */
  23316. void handleCommandMessage (int commandId);
  23317. /** @internal */
  23318. void mouseEnter (const MouseEvent& e);
  23319. /** @internal */
  23320. void mouseExit (const MouseEvent& e);
  23321. /** @internal */
  23322. void mouseDown (const MouseEvent& e);
  23323. /** @internal */
  23324. void mouseDrag (const MouseEvent& e);
  23325. /** @internal */
  23326. void mouseUp (const MouseEvent& e);
  23327. /** @internal */
  23328. bool keyPressed (const KeyPress& key);
  23329. /** @internal */
  23330. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  23331. /** @internal */
  23332. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  23333. /** @internal */
  23334. void paint (Graphics& g);
  23335. /** @internal */
  23336. void parentHierarchyChanged();
  23337. /** @internal */
  23338. void focusGained (FocusChangeType cause);
  23339. /** @internal */
  23340. void focusLost (FocusChangeType cause);
  23341. /** @internal */
  23342. void enablementChanged();
  23343. /** @internal */
  23344. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  23345. /** @internal */
  23346. void applicationCommandListChanged();
  23347. private:
  23348. Array <KeyPress> shortcuts;
  23349. Component* keySource;
  23350. String text;
  23351. SortedSet <void*> buttonListeners;
  23352. friend class InternalButtonRepeatTimer;
  23353. Timer* repeatTimer;
  23354. uint32 buttonPressTime, lastTimeCallbackTime;
  23355. ApplicationCommandManager* commandManagerToUse;
  23356. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  23357. int radioGroupId, commandID, connectedEdgeFlags;
  23358. ButtonState buttonState;
  23359. bool isOn : 1;
  23360. bool clickTogglesState : 1;
  23361. bool needsToRelease : 1;
  23362. bool needsRepainting : 1;
  23363. bool isKeyDown : 1;
  23364. bool triggerOnMouseDown : 1;
  23365. bool generateTooltip : 1;
  23366. void repeatTimerCallback() throw();
  23367. Timer& getRepeatTimer() throw();
  23368. ButtonState updateState (const MouseEvent* const e) throw();
  23369. bool isShortcutPressed() const throw();
  23370. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  23371. void flashButtonState() throw();
  23372. void sendClickMessage (const ModifierKeys& modifiers);
  23373. void sendStateMessage();
  23374. Button (const Button&);
  23375. const Button& operator= (const Button&);
  23376. };
  23377. #endif // __JUCE_BUTTON_JUCEHEADER__
  23378. /********* End of inlined file: juce_Button.h *********/
  23379. class ScrollBar;
  23380. /**
  23381. A class for receiving events from a ScrollBar.
  23382. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  23383. method, and it will be called when the bar's position changes.
  23384. @see ScrollBar::addListener, ScrollBar::removeListener
  23385. */
  23386. class JUCE_API ScrollBarListener
  23387. {
  23388. public:
  23389. /** Destructor. */
  23390. virtual ~ScrollBarListener() {}
  23391. /** Called when a ScrollBar is moved.
  23392. @param scrollBarThatHasMoved the bar that has moved
  23393. @param newRangeStart the new range start of this bar
  23394. */
  23395. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  23396. const double newRangeStart) = 0;
  23397. };
  23398. /**
  23399. A scrollbar component.
  23400. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  23401. sets the range of values it can represent. Then you can use setCurrentRange() to
  23402. change the position and size of the scrollbar's 'thumb'.
  23403. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  23404. the user moves it, and you can use the getCurrentRangeStart() to find out where
  23405. they moved it to.
  23406. The scrollbar will adjust its own visibility according to whether its thumb size
  23407. allows it to actually be scrolled.
  23408. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  23409. instead of handling a scrollbar directly.
  23410. @see ScrollBarListener
  23411. */
  23412. class JUCE_API ScrollBar : public Component,
  23413. public AsyncUpdater,
  23414. private Timer
  23415. {
  23416. public:
  23417. /** Creates a Scrollbar.
  23418. @param isVertical whether it should be a vertical or horizontal bar
  23419. @param buttonsAreVisible whether to show the up/down or left/right buttons
  23420. */
  23421. ScrollBar (const bool isVertical,
  23422. const bool buttonsAreVisible = true);
  23423. /** Destructor. */
  23424. ~ScrollBar();
  23425. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  23426. bool isVertical() const throw() { return vertical; }
  23427. /** Changes the scrollbar's direction.
  23428. You'll also need to resize the bar appropriately - this just changes its internal
  23429. layout.
  23430. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  23431. */
  23432. void setOrientation (const bool shouldBeVertical) throw();
  23433. /** Shows or hides the scrollbar's buttons. */
  23434. void setButtonVisibility (const bool buttonsAreVisible);
  23435. /** Tells the scrollbar whether to make itself invisible when not needed.
  23436. The default behaviour is for a scrollbar to become invisible when the thumb
  23437. fills the whole of its range (i.e. when it can't be moved). Setting this
  23438. value to false forces the bar to always be visible.
  23439. */
  23440. void setAutoHide (const bool shouldHideWhenFullRange);
  23441. /** Sets the minimum and maximum values that the bar will move between.
  23442. The bar's thumb will always be constrained so that the top of the thumb
  23443. will be >= minimum, and the bottom of the thumb <= maximum.
  23444. @see setCurrentRange
  23445. */
  23446. void setRangeLimits (const double minimum,
  23447. const double maximum) throw();
  23448. /** Returns the lower value that the thumb can be set to.
  23449. This is the value set by setRangeLimits().
  23450. */
  23451. double getMinimumRangeLimit() const throw() { return minimum; }
  23452. /** Returns the upper value that the thumb can be set to.
  23453. This is the value set by setRangeLimits().
  23454. */
  23455. double getMaximumRangeLimit() const throw() { return maximum; }
  23456. /** Changes the position of the scrollbar's 'thumb'.
  23457. This sets both the position and size of the thumb - to just set the position without
  23458. changing the size, you can use setCurrentRangeStart().
  23459. If this method call actually changes the scrollbar's position, it will trigger an
  23460. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23461. are registered.
  23462. @param newStart the top (or left) of the thumb, in the range
  23463. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  23464. value is beyond these limits, it will be clipped.
  23465. @param newSize the size of the thumb, such that
  23466. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  23467. size is beyond these limits, it will be clipped.
  23468. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  23469. */
  23470. void setCurrentRange (double newStart,
  23471. double newSize) throw();
  23472. /** Moves the bar's thumb position.
  23473. This will move the thumb position without changing the thumb size. Note
  23474. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  23475. If this method call actually changes the scrollbar's position, it will trigger an
  23476. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23477. are registered.
  23478. @see setCurrentRange
  23479. */
  23480. void setCurrentRangeStart (double newStart) throw();
  23481. /** Returns the position of the top of the thumb.
  23482. @see setCurrentRangeStart
  23483. */
  23484. double getCurrentRangeStart() const throw() { return rangeStart; }
  23485. /** Returns the current size of the thumb.
  23486. @see setCurrentRange
  23487. */
  23488. double getCurrentRangeSize() const throw() { return rangeSize; }
  23489. /** Sets the amount by which the up and down buttons will move the bar.
  23490. The value here is in terms of the total range, and is added or subtracted
  23491. from the thumb position when the user clicks an up/down (or left/right) button.
  23492. */
  23493. void setSingleStepSize (const double newSingleStepSize) throw();
  23494. /** Moves the scrollbar by a number of single-steps.
  23495. This will move the bar by a multiple of its single-step interval (as
  23496. specified using the setSingleStepSize() method).
  23497. A positive value here will move the bar down or to the right, a negative
  23498. value moves it up or to the left.
  23499. */
  23500. void moveScrollbarInSteps (const int howManySteps) throw();
  23501. /** Moves the scroll bar up or down in pages.
  23502. This will move the bar by a multiple of its current thumb size, effectively
  23503. doing a page-up or down.
  23504. A positive value here will move the bar down or to the right, a negative
  23505. value moves it up or to the left.
  23506. */
  23507. void moveScrollbarInPages (const int howManyPages) throw();
  23508. /** Scrolls to the top (or left).
  23509. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  23510. */
  23511. void scrollToTop() throw();
  23512. /** Scrolls to the bottom (or right).
  23513. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  23514. */
  23515. void scrollToBottom() throw();
  23516. /** Changes the delay before the up and down buttons autorepeat when they are held
  23517. down.
  23518. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  23519. @see Button::setRepeatSpeed
  23520. */
  23521. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  23522. const int repeatDelayInMillisecs,
  23523. const int minimumDelayInMillisecs = -1) throw();
  23524. /** A set of colour IDs to use to change the colour of various aspects of the component.
  23525. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23526. methods.
  23527. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23528. */
  23529. enum ColourIds
  23530. {
  23531. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  23532. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  23533. 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. */
  23534. };
  23535. /** Registers a listener that will be called when the scrollbar is moved. */
  23536. void addListener (ScrollBarListener* const listener) throw();
  23537. /** Deregisters a previously-registered listener. */
  23538. void removeListener (ScrollBarListener* const listener) throw();
  23539. /** @internal */
  23540. bool keyPressed (const KeyPress& key);
  23541. /** @internal */
  23542. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23543. /** @internal */
  23544. void lookAndFeelChanged();
  23545. /** @internal */
  23546. void handleAsyncUpdate();
  23547. /** @internal */
  23548. void mouseDown (const MouseEvent& e);
  23549. /** @internal */
  23550. void mouseDrag (const MouseEvent& e);
  23551. /** @internal */
  23552. void mouseUp (const MouseEvent& e);
  23553. /** @internal */
  23554. void paint (Graphics& g);
  23555. /** @internal */
  23556. void resized();
  23557. juce_UseDebuggingNewOperator
  23558. private:
  23559. double minimum, maximum;
  23560. double rangeStart, rangeSize;
  23561. double singleStepSize, dragStartRange;
  23562. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  23563. int dragStartMousePos, lastMousePos;
  23564. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  23565. bool vertical, isDraggingThumb, alwaysVisible;
  23566. Button* upButton;
  23567. Button* downButton;
  23568. SortedSet <void*> listeners;
  23569. void updateThumbPosition() throw();
  23570. void timerCallback();
  23571. ScrollBar (const ScrollBar&);
  23572. const ScrollBar& operator= (const ScrollBar&);
  23573. };
  23574. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  23575. /********* End of inlined file: juce_ScrollBar.h *********/
  23576. /**
  23577. A Viewport is used to contain a larger child component, and allows the child
  23578. to be automatically scrolled around.
  23579. To use a Viewport, just create one and set the component that goes inside it
  23580. using the setViewedComponent() method. When the child component changes size,
  23581. the Viewport will adjust its scrollbars accordingly.
  23582. A subclass of the viewport can be created which will receive calls to its
  23583. visibleAreaChanged() method when the subcomponent changes position or size.
  23584. */
  23585. class JUCE_API Viewport : public Component,
  23586. private ComponentListener,
  23587. private ScrollBarListener
  23588. {
  23589. public:
  23590. /** Creates a Viewport.
  23591. The viewport is initially empty - use the setViewedComponent() method to
  23592. add a child component for it to manage.
  23593. */
  23594. Viewport (const String& componentName = String::empty);
  23595. /** Destructor. */
  23596. ~Viewport();
  23597. /** Sets the component that this viewport will contain and scroll around.
  23598. This will add the given component to this Viewport and position it at
  23599. (0, 0).
  23600. (Don't add or remove any child components directly using the normal
  23601. Component::addChildComponent() methods).
  23602. @param newViewedComponent the component to add to this viewport (this pointer
  23603. may be null). The component passed in will be deleted
  23604. by the Viewport when it's no longer needed
  23605. @see getViewedComponent
  23606. */
  23607. void setViewedComponent (Component* const newViewedComponent);
  23608. /** Returns the component that's currently being used inside the Viewport.
  23609. @see setViewedComponent
  23610. */
  23611. Component* getViewedComponent() const throw() { return contentComp; }
  23612. /** Changes the position of the viewed component.
  23613. The inner component will be moved so that the pixel at the top left of
  23614. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  23615. within the inner component.
  23616. This will update the scrollbars and might cause a call to visibleAreaChanged().
  23617. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  23618. */
  23619. void setViewPosition (const int xPixelsOffset,
  23620. const int yPixelsOffset);
  23621. /** Changes the view position as a proportion of the distance it can move.
  23622. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  23623. visible area in the top-left, and (1, 1) would put it as far down and
  23624. to the right as it's possible to go whilst keeping the child component
  23625. on-screen.
  23626. */
  23627. void setViewPositionProportionately (const double proportionX,
  23628. const double proportionY);
  23629. /** Returns the position within the child component of the top-left of its visible area.
  23630. @see getViewWidth, setViewPosition
  23631. */
  23632. int getViewPositionX() const throw() { return lastVX; }
  23633. /** Returns the position within the child component of the top-left of its visible area.
  23634. @see getViewHeight, setViewPosition
  23635. */
  23636. int getViewPositionY() const throw() { return lastVY; }
  23637. /** Returns the width of the visible area of the child component.
  23638. This may be less than the width of this Viewport if there's a vertical scrollbar
  23639. or if the child component is itself smaller.
  23640. */
  23641. int getViewWidth() const throw() { return lastVW; }
  23642. /** Returns the height of the visible area of the child component.
  23643. This may be less than the height of this Viewport if there's a horizontal scrollbar
  23644. or if the child component is itself smaller.
  23645. */
  23646. int getViewHeight() const throw() { return lastVH; }
  23647. /** Returns the width available within this component for the contents.
  23648. This will be the width of the viewport component minus the width of a
  23649. vertical scrollbar (if visible).
  23650. */
  23651. int getMaximumVisibleWidth() const throw();
  23652. /** Returns the height available within this component for the contents.
  23653. This will be the height of the viewport component minus the space taken up
  23654. by a horizontal scrollbar (if visible).
  23655. */
  23656. int getMaximumVisibleHeight() const throw();
  23657. /** Callback method that is called when the visible area changes.
  23658. This will be called when the visible area is moved either be scrolling or
  23659. by calls to setViewPosition(), etc.
  23660. */
  23661. virtual void visibleAreaChanged (int visibleX, int visibleY,
  23662. int visibleW, int visibleH);
  23663. /** Turns scrollbars on or off.
  23664. If set to false, the scrollbars won't ever appear. When true (the default)
  23665. they will appear only when needed.
  23666. */
  23667. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  23668. const bool showHorizontalScrollbarIfNeeded);
  23669. /** True if the vertical scrollbar is enabled.
  23670. @see setScrollBarsShown
  23671. */
  23672. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  23673. /** True if the horizontal scrollbar is enabled.
  23674. @see setScrollBarsShown
  23675. */
  23676. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  23677. /** Changes the width of the scrollbars.
  23678. If this isn't specified, the default width from the LookAndFeel class will be used.
  23679. @see LookAndFeel::getDefaultScrollbarWidth
  23680. */
  23681. void setScrollBarThickness (const int thickness);
  23682. /** Returns the thickness of the scrollbars.
  23683. @see setScrollBarThickness
  23684. */
  23685. int getScrollBarThickness() const throw();
  23686. /** Changes the distance that a single-step click on a scrollbar button
  23687. will move the viewport.
  23688. */
  23689. void setSingleStepSizes (const int stepX, const int stepY);
  23690. /** Shows or hides the buttons on any scrollbars that are used.
  23691. @see ScrollBar::setButtonVisibility
  23692. */
  23693. void setScrollBarButtonVisibility (const bool buttonsVisible);
  23694. /** Returns a pointer to the scrollbar component being used.
  23695. Handy if you need to customise the bar somehow.
  23696. */
  23697. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  23698. /** Returns a pointer to the scrollbar component being used.
  23699. Handy if you need to customise the bar somehow.
  23700. */
  23701. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  23702. juce_UseDebuggingNewOperator
  23703. /** @internal */
  23704. void resized();
  23705. /** @internal */
  23706. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  23707. /** @internal */
  23708. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23709. /** @internal */
  23710. bool keyPressed (const KeyPress& key);
  23711. /** @internal */
  23712. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  23713. /** @internal */
  23714. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23715. private:
  23716. Component* contentComp;
  23717. int lastVX, lastVY, lastVW, lastVH;
  23718. int scrollBarThickness;
  23719. int singleStepX, singleStepY;
  23720. bool showHScrollbar, showVScrollbar;
  23721. Component* contentHolder;
  23722. ScrollBar* verticalScrollBar;
  23723. ScrollBar* horizontalScrollBar;
  23724. void updateVisibleRegion();
  23725. Viewport (const Viewport&);
  23726. const Viewport& operator= (const Viewport&);
  23727. };
  23728. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  23729. /********* End of inlined file: juce_Viewport.h *********/
  23730. /**
  23731. A panel that holds a list of PropertyComponent objects.
  23732. This panel displays a list of PropertyComponents, and allows them to be organised
  23733. into collapsible sections.
  23734. To use, simply create one of these and add your properties to it with addProperties()
  23735. or addSection().
  23736. @see PropertyComponent
  23737. */
  23738. class JUCE_API PropertyPanel : public Component
  23739. {
  23740. public:
  23741. /** Creates an empty property panel. */
  23742. PropertyPanel();
  23743. /** Destructor. */
  23744. ~PropertyPanel();
  23745. /** Deletes all property components from the panel.
  23746. */
  23747. void clear();
  23748. /** Adds a set of properties to the panel.
  23749. The components in the list will be owned by this object and will be automatically
  23750. deleted later on when no longer needed.
  23751. These properties are added without them being inside a named section. If you
  23752. want them to be kept together in a collapsible section, use addSection() instead.
  23753. */
  23754. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  23755. /** Adds a set of properties to the panel.
  23756. These properties are added at the bottom of the list, under a section heading with
  23757. a plus/minus button that allows it to be opened and closed.
  23758. The components in the list will be owned by this object and will be automatically
  23759. deleted later on when no longer needed.
  23760. To add properies without them being in a section, use addProperties().
  23761. */
  23762. void addSection (const String& sectionTitle,
  23763. const Array <PropertyComponent*>& newPropertyComponents,
  23764. const bool shouldSectionInitiallyBeOpen = true);
  23765. /** Calls the refresh() method of all PropertyComponents in the panel */
  23766. void refreshAll() const;
  23767. /** Returns a list of all the names of sections in the panel.
  23768. These are the sections that have been added with addSection().
  23769. */
  23770. const StringArray getSectionNames() const;
  23771. /** Returns true if the section at this index is currently open.
  23772. The index is from 0 up to the number of items returned by getSectionNames().
  23773. */
  23774. bool isSectionOpen (const int sectionIndex) const;
  23775. /** Opens or closes one of the sections.
  23776. The index is from 0 up to the number of items returned by getSectionNames().
  23777. */
  23778. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  23779. /** Enables or disables one of the sections.
  23780. The index is from 0 up to the number of items returned by getSectionNames().
  23781. */
  23782. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  23783. /** Saves the current state of open/closed sections so it can be restored later.
  23784. The caller is responsible for deleting the object that is returned.
  23785. To restore this state, use restoreOpennessState().
  23786. @see restoreOpennessState
  23787. */
  23788. XmlElement* getOpennessState() const;
  23789. /** Restores a previously saved arrangement of open/closed sections.
  23790. This will try to restore a snapshot of the panel's state that was created by
  23791. the getOpennessState() method. If any of the sections named in the original
  23792. XML aren't present, they will be ignored.
  23793. @see getOpennessState
  23794. */
  23795. void restoreOpennessState (const XmlElement& newState);
  23796. /** Sets a message to be displayed when there are no properties in the panel.
  23797. The default message is "nothing selected".
  23798. */
  23799. void setMessageWhenEmpty (const String& newMessage);
  23800. /** Returns the message that is displayed when there are no properties.
  23801. @see setMessageWhenEmpty
  23802. */
  23803. const String& getMessageWhenEmpty() const throw();
  23804. /** @internal */
  23805. void paint (Graphics& g);
  23806. /** @internal */
  23807. void resized();
  23808. juce_UseDebuggingNewOperator
  23809. private:
  23810. Viewport* viewport;
  23811. Component* propertyHolderComponent;
  23812. String messageWhenEmpty;
  23813. void updatePropHolderLayout() const;
  23814. void updatePropHolderLayout (const int width) const;
  23815. };
  23816. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  23817. /********* End of inlined file: juce_PropertyPanel.h *********/
  23818. /**
  23819. A type of UI component that displays the parameters of an AudioProcessor as
  23820. a simple list of sliders.
  23821. This can be used for showing an editor for a processor that doesn't supply
  23822. its own custom editor.
  23823. @see AudioProcessor
  23824. */
  23825. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  23826. {
  23827. public:
  23828. GenericAudioProcessorEditor (AudioProcessor* const owner);
  23829. ~GenericAudioProcessorEditor();
  23830. void paint (Graphics& g);
  23831. void resized();
  23832. juce_UseDebuggingNewOperator
  23833. private:
  23834. PropertyPanel* panel;
  23835. };
  23836. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23837. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23838. #endif
  23839. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23840. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23841. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23842. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23843. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23844. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23845. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23846. /********* Start of inlined file: juce_AudioSource.h *********/
  23847. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23848. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23849. /**
  23850. Used by AudioSource::getNextAudioBlock().
  23851. */
  23852. struct JUCE_API AudioSourceChannelInfo
  23853. {
  23854. /** The destination buffer to fill with audio data.
  23855. When the AudioSource::getNextAudioBlock() method is called, the active section
  23856. of this buffer should be filled with whatever output the source produces.
  23857. Only the samples specified by the startSample and numSamples members of this structure
  23858. should be affected by the call.
  23859. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23860. method can be treated as the input if the source is performing some kind of filter operation,
  23861. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23862. a handy way of doing this.
  23863. The number of channels in the buffer could be anything, so the AudioSource
  23864. must cope with this in whatever way is appropriate for its function.
  23865. */
  23866. AudioSampleBuffer* buffer;
  23867. /** The first sample in the buffer from which the callback is expected
  23868. to write data. */
  23869. int startSample;
  23870. /** The number of samples in the buffer which the callback is expected to
  23871. fill with data. */
  23872. int numSamples;
  23873. /** Convenient method to clear the buffer if the source is not producing any data. */
  23874. void clearActiveBufferRegion() const
  23875. {
  23876. if (buffer != 0)
  23877. buffer->clear (startSample, numSamples);
  23878. }
  23879. };
  23880. /**
  23881. Base class for objects that can produce a continuous stream of audio.
  23882. @see AudioFormatReaderSource, ResamplingAudioSource
  23883. */
  23884. class JUCE_API AudioSource
  23885. {
  23886. protected:
  23887. /** Creates an AudioSource. */
  23888. AudioSource() throw() {}
  23889. public:
  23890. /** Destructor. */
  23891. virtual ~AudioSource() {}
  23892. /** Tells the source to prepare for playing.
  23893. The source can use this opportunity to initialise anything it needs to.
  23894. Note that this method could be called more than once in succession without
  23895. a matching call to releaseResources(), so make sure your code is robust and
  23896. can handle that kind of situation.
  23897. @param samplesPerBlockExpected the number of samples that the source
  23898. will be expected to supply each time its
  23899. getNextAudioBlock() method is called. This
  23900. number may vary slightly, because it will be dependent
  23901. on audio hardware callbacks, and these aren't
  23902. guaranteed to always use a constant block size, so
  23903. the source should be able to cope with small variations.
  23904. @param sampleRate the sample rate that the output will be used at - this
  23905. is needed by sources such as tone generators.
  23906. @see releaseResources, getNextAudioBlock
  23907. */
  23908. virtual void prepareToPlay (int samplesPerBlockExpected,
  23909. double sampleRate) = 0;
  23910. /** Allows the source to release anything it no longer needs after playback has stopped.
  23911. This will be called when the source is no longer going to have its getNextAudioBlock()
  23912. method called, so it should release any spare memory, etc. that it might have
  23913. allocated during the prepareToPlay() call.
  23914. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23915. releaseResources(), and it may be called more than once in succession, so make sure your
  23916. code is robust and doesn't make any assumptions about when it will be called.
  23917. @see prepareToPlay, getNextAudioBlock
  23918. */
  23919. virtual void releaseResources() = 0;
  23920. /** Called repeatedly to fetch subsequent blocks of audio data.
  23921. After calling the prepareToPlay() method, this callback will be made each
  23922. time the audio playback hardware (or whatever other destination the audio
  23923. data is going to) needs another block of data.
  23924. It will generally be called on a high-priority system thread, or possibly even
  23925. an interrupt, so be careful not to do too much work here, as that will cause
  23926. audio glitches!
  23927. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23928. */
  23929. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23930. };
  23931. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23932. /********* End of inlined file: juce_AudioSource.h *********/
  23933. /**
  23934. A type of AudioSource which can be repositioned.
  23935. The basic AudioSource just streams continuously with no idea of a current
  23936. time or length, so the PositionableAudioSource is used for a finite stream
  23937. that has a current read position.
  23938. @see AudioSource, AudioTransportSource
  23939. */
  23940. class JUCE_API PositionableAudioSource : public AudioSource
  23941. {
  23942. protected:
  23943. /** Creates the PositionableAudioSource. */
  23944. PositionableAudioSource() throw() {}
  23945. public:
  23946. /** Destructor */
  23947. ~PositionableAudioSource() {}
  23948. /** Tells the stream to move to a new position.
  23949. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23950. should return samples from this position.
  23951. Note that this may be called on a different thread to getNextAudioBlock(),
  23952. so the subclass should make sure it's synchronised.
  23953. */
  23954. virtual void setNextReadPosition (int newPosition) = 0;
  23955. /** Returns the position from which the next block will be returned.
  23956. @see setNextReadPosition
  23957. */
  23958. virtual int getNextReadPosition() const = 0;
  23959. /** Returns the total length of the stream (in samples). */
  23960. virtual int getTotalLength() const = 0;
  23961. /** Returns true if this source is actually playing in a loop. */
  23962. virtual bool isLooping() const = 0;
  23963. };
  23964. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23965. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23966. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23967. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23968. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23969. class AudioFormat;
  23970. /**
  23971. Reads samples from an audio file stream.
  23972. A subclass that reads a specific type of audio format will be created by
  23973. an AudioFormat object.
  23974. @see AudioFormat, AudioFormatWriter
  23975. */
  23976. class JUCE_API AudioFormatReader
  23977. {
  23978. protected:
  23979. /** Creates an AudioFormatReader object.
  23980. @param sourceStream the stream to read from - this will be deleted
  23981. by this object when it is no longer needed. (Some
  23982. specialised readers might not use this parameter and
  23983. can leave it as 0).
  23984. @param formatName the description that will be returned by the getFormatName()
  23985. method
  23986. */
  23987. AudioFormatReader (InputStream* const sourceStream,
  23988. const String& formatName);
  23989. public:
  23990. /** Destructor. */
  23991. virtual ~AudioFormatReader();
  23992. /** Returns a description of what type of format this is.
  23993. E.g. "AIFF"
  23994. */
  23995. const String getFormatName() const throw() { return formatName; }
  23996. /** Reads samples from the stream.
  23997. @param destSamples an array of buffers into which the sample data for each
  23998. channel will be written.
  23999. If the format is fixed-point, each channel will be written
  24000. as an array of 32-bit signed integers using the full
  24001. range -0x80000000 to 0x7fffffff, regardless of the source's
  24002. bit-depth. If it is a floating-point format, you should cast
  24003. the resulting array to a (float**) to get the values (in the
  24004. range -1.0 to 1.0 or beyond)
  24005. If the format is stereo, then destSamples[0] is the left channel
  24006. data, and destSamples[1] is the right channel.
  24007. The numDestChannels parameter indicates how many pointers this array
  24008. contains, but some of these pointers can be null if you don't want to
  24009. read data for some of the channels
  24010. @param numDestChannels the number of array elements in the destChannels array
  24011. @param startSampleInSource the position in the audio file or stream at which the samples
  24012. should be read, as a number of samples from the start of the
  24013. stream. It's ok for this to be beyond the start or end of the
  24014. available data - any samples that are out-of-range will be returned
  24015. as zeros.
  24016. @param numSamplesToRead the number of samples to read. If this is greater than the number
  24017. of samples that the file or stream contains. the result will be padded
  24018. with zeros
  24019. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  24020. for some of the channels that you pass in, then they should be filled with
  24021. copies of valid source channels.
  24022. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  24023. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  24024. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  24025. was false, then only the first channel would be filled with the file's contents, and
  24026. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  24027. from a stereo file, then the last 3 would all end up with copies of the same data.
  24028. @returns true if the operation succeeded, false if there was an error. Note
  24029. that reading sections of data beyond the extent of the stream isn't an
  24030. error - the reader should just return zeros for these regions
  24031. @see readMaxLevels
  24032. */
  24033. bool read (int** destSamples,
  24034. int numDestChannels,
  24035. int64 startSampleInSource,
  24036. int numSamplesToRead,
  24037. const bool fillLeftoverChannelsWithCopies);
  24038. /** Finds the highest and lowest sample levels from a section of the audio stream.
  24039. This will read a block of samples from the stream, and measure the
  24040. highest and lowest sample levels from the channels in that section, returning
  24041. these as normalised floating-point levels.
  24042. @param startSample the offset into the audio stream to start reading from. It's
  24043. ok for this to be beyond the start or end of the stream.
  24044. @param numSamples how many samples to read
  24045. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  24046. @param highestLeft on return, this is the highest absolute sample from the left channel
  24047. @param lowestRight on return, this is the lowest absolute sample from the right
  24048. channel (if there is one)
  24049. @param highestRight on return, this is the highest absolute sample from the right
  24050. channel (if there is one)
  24051. @see read
  24052. */
  24053. virtual void readMaxLevels (int64 startSample,
  24054. int64 numSamples,
  24055. float& lowestLeft,
  24056. float& highestLeft,
  24057. float& lowestRight,
  24058. float& highestRight);
  24059. /** Scans the source looking for a sample whose magnitude is in a specified range.
  24060. This will read from the source, either forwards or backwards between two sample
  24061. positions, until it finds a sample whose magnitude lies between two specified levels.
  24062. If it finds a suitable sample, it returns its position; if not, it will return -1.
  24063. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  24064. points when you're searching for a continuous range of samples
  24065. @param startSample the first sample to look at
  24066. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  24067. the search will go backwards
  24068. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  24069. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  24070. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  24071. of this many consecutive samples, all of which lie
  24072. within the target range. When it finds such a sequence,
  24073. it returns the position of the first in-range sample
  24074. it found (i.e. the earliest one if scanning forwards, the
  24075. latest one if scanning backwards)
  24076. */
  24077. int64 searchForLevel (int64 startSample,
  24078. int64 numSamplesToSearch,
  24079. const double magnitudeRangeMinimum,
  24080. const double magnitudeRangeMaximum,
  24081. const int minimumConsecutiveSamples);
  24082. /** The sample-rate of the stream. */
  24083. double sampleRate;
  24084. /** The number of bits per sample, e.g. 16, 24, 32. */
  24085. unsigned int bitsPerSample;
  24086. /** The total number of samples in the audio stream. */
  24087. int64 lengthInSamples;
  24088. /** The total number of channels in the audio stream. */
  24089. unsigned int numChannels;
  24090. /** Indicates whether the data is floating-point or fixed. */
  24091. bool usesFloatingPointData;
  24092. /** A set of metadata values that the reader has pulled out of the stream.
  24093. Exactly what these values are depends on the format, so you can
  24094. check out the format implementation code to see what kind of stuff
  24095. they understand.
  24096. */
  24097. StringPairArray metadataValues;
  24098. /** The input stream, for use by subclasses. */
  24099. InputStream* input;
  24100. /** Subclasses must implement this method to perform the low-level read operation.
  24101. Callers should use read() instead of calling this directly.
  24102. @param destSamples the array of destination buffers to fill. Some of these
  24103. pointers may be null
  24104. @param numDestChannels the number of items in the destSamples array. This
  24105. value is guaranteed not to be greater than the number of
  24106. channels that this reader object contains
  24107. @param startOffsetInDestBuffer the number of samples from the start of the
  24108. dest data at which to begin writing
  24109. @param startSampleInFile the number of samples into the source data at which
  24110. to begin reading. This value is guaranteed to be >= 0.
  24111. @param numSamples the number of samples to read
  24112. */
  24113. virtual bool readSamples (int** destSamples,
  24114. int numDestChannels,
  24115. int startOffsetInDestBuffer,
  24116. int64 startSampleInFile,
  24117. int numSamples) = 0;
  24118. juce_UseDebuggingNewOperator
  24119. private:
  24120. String formatName;
  24121. AudioFormatReader (const AudioFormatReader&);
  24122. const AudioFormatReader& operator= (const AudioFormatReader&);
  24123. };
  24124. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  24125. /********* End of inlined file: juce_AudioFormatReader.h *********/
  24126. /**
  24127. A type of AudioSource that will read from an AudioFormatReader.
  24128. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  24129. */
  24130. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  24131. {
  24132. public:
  24133. /** Creates an AudioFormatReaderSource for a given reader.
  24134. @param sourceReader the reader to use as the data source
  24135. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  24136. when this object is deleted; if false it will be
  24137. left up to the caller to manage its lifetime
  24138. */
  24139. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  24140. const bool deleteReaderWhenThisIsDeleted);
  24141. /** Destructor. */
  24142. ~AudioFormatReaderSource();
  24143. /** Toggles loop-mode.
  24144. If set to true, it will continuously loop the input source. If false,
  24145. it will just emit silence after the source has finished.
  24146. @see isLooping
  24147. */
  24148. void setLooping (const bool shouldLoop) throw();
  24149. /** Returns whether loop-mode is turned on or not. */
  24150. bool isLooping() const { return looping; }
  24151. /** Returns the reader that's being used. */
  24152. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  24153. /** Implementation of the AudioSource method. */
  24154. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24155. /** Implementation of the AudioSource method. */
  24156. void releaseResources();
  24157. /** Implementation of the AudioSource method. */
  24158. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24159. /** Implements the PositionableAudioSource method. */
  24160. void setNextReadPosition (int newPosition);
  24161. /** Implements the PositionableAudioSource method. */
  24162. int getNextReadPosition() const;
  24163. /** Implements the PositionableAudioSource method. */
  24164. int getTotalLength() const;
  24165. juce_UseDebuggingNewOperator
  24166. private:
  24167. AudioFormatReader* reader;
  24168. bool deleteReader;
  24169. int volatile nextPlayPos;
  24170. bool volatile looping;
  24171. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  24172. AudioFormatReaderSource (const AudioFormatReaderSource&);
  24173. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  24174. };
  24175. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  24176. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  24177. #endif
  24178. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  24179. #endif
  24180. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24181. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  24182. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24183. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24184. /**
  24185. Wrapper class to continuously stream audio from an audio source to an
  24186. AudioIODevice.
  24187. This object acts as an AudioIODeviceCallback, so can be attached to an
  24188. output device, and will stream audio from an AudioSource.
  24189. */
  24190. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  24191. {
  24192. public:
  24193. /** Creates an empty AudioSourcePlayer. */
  24194. AudioSourcePlayer();
  24195. /** Destructor.
  24196. Make sure this object isn't still being used by an AudioIODevice before
  24197. deleting it!
  24198. */
  24199. virtual ~AudioSourcePlayer();
  24200. /** Changes the current audio source to play from.
  24201. If the source passed in is already being used, this method will do nothing.
  24202. If the source is not null, its prepareToPlay() method will be called
  24203. before it starts being used for playback.
  24204. If there's another source currently playing, its releaseResources() method
  24205. will be called after it has been swapped for the new one.
  24206. @param newSource the new source to use - this will NOT be deleted
  24207. by this object when no longer needed, so it's the
  24208. caller's responsibility to manage it.
  24209. */
  24210. void setSource (AudioSource* newSource);
  24211. /** Returns the source that's playing.
  24212. May return 0 if there's no source.
  24213. */
  24214. AudioSource* getCurrentSource() const throw() { return source; }
  24215. /** Sets a gain to apply to the audio data. */
  24216. void setGain (const float newGain) throw();
  24217. /** Implementation of the AudioIODeviceCallback method. */
  24218. void audioDeviceIOCallback (const float** inputChannelData,
  24219. int totalNumInputChannels,
  24220. float** outputChannelData,
  24221. int totalNumOutputChannels,
  24222. int numSamples);
  24223. /** Implementation of the AudioIODeviceCallback method. */
  24224. void audioDeviceAboutToStart (AudioIODevice* device);
  24225. /** Implementation of the AudioIODeviceCallback method. */
  24226. void audioDeviceStopped();
  24227. juce_UseDebuggingNewOperator
  24228. private:
  24229. CriticalSection readLock;
  24230. AudioSource* source;
  24231. double sampleRate;
  24232. int bufferSize;
  24233. float* channels [128];
  24234. float* outputChans [128];
  24235. const float* inputChans [128];
  24236. AudioSampleBuffer tempBuffer;
  24237. float lastGain, gain;
  24238. AudioSourcePlayer (const AudioSourcePlayer&);
  24239. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  24240. };
  24241. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24242. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  24243. #endif
  24244. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24245. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  24246. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24247. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24248. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  24249. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24250. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24251. /**
  24252. An AudioSource which takes another source as input, and buffers it using a thread.
  24253. Create this as a wrapper around another thread, and it will read-ahead with
  24254. a background thread to smooth out playback. You can either create one of these
  24255. directly, or use it indirectly using an AudioTransportSource.
  24256. @see PositionableAudioSource, AudioTransportSource
  24257. */
  24258. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  24259. {
  24260. public:
  24261. /** Creates a BufferingAudioSource.
  24262. @param source the input source to read from
  24263. @param deleteSourceWhenDeleted if true, then the input source object will
  24264. be deleted when this object is deleted
  24265. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  24266. */
  24267. BufferingAudioSource (PositionableAudioSource* source,
  24268. const bool deleteSourceWhenDeleted,
  24269. int numberOfSamplesToBuffer);
  24270. /** Destructor.
  24271. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  24272. flag was set in the constructor.
  24273. */
  24274. ~BufferingAudioSource();
  24275. /** Implementation of the AudioSource method. */
  24276. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24277. /** Implementation of the AudioSource method. */
  24278. void releaseResources();
  24279. /** Implementation of the AudioSource method. */
  24280. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24281. /** Implements the PositionableAudioSource method. */
  24282. void setNextReadPosition (int newPosition);
  24283. /** Implements the PositionableAudioSource method. */
  24284. int getNextReadPosition() const;
  24285. /** Implements the PositionableAudioSource method. */
  24286. int getTotalLength() const { return source->getTotalLength(); }
  24287. /** Implements the PositionableAudioSource method. */
  24288. bool isLooping() const { return source->isLooping(); }
  24289. juce_UseDebuggingNewOperator
  24290. private:
  24291. PositionableAudioSource* source;
  24292. bool deleteSourceWhenDeleted;
  24293. int numberOfSamplesToBuffer;
  24294. AudioSampleBuffer buffer;
  24295. CriticalSection bufferStartPosLock;
  24296. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  24297. bool wasSourceLooping;
  24298. double volatile sampleRate;
  24299. friend class SharedBufferingAudioSourceThread;
  24300. bool readNextBufferChunk();
  24301. void readBufferSection (int start, int length, int bufferOffset);
  24302. BufferingAudioSource (const BufferingAudioSource&);
  24303. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  24304. };
  24305. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24306. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  24307. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  24308. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24309. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24310. /**
  24311. A type of AudioSource that takes an input source and changes its sample rate.
  24312. @see AudioSource
  24313. */
  24314. class JUCE_API ResamplingAudioSource : public AudioSource
  24315. {
  24316. public:
  24317. /** Creates a ResamplingAudioSource for a given input source.
  24318. @param inputSource the input source to read from
  24319. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24320. this object is deleted
  24321. */
  24322. ResamplingAudioSource (AudioSource* const inputSource,
  24323. const bool deleteInputWhenDeleted);
  24324. /** Destructor. */
  24325. ~ResamplingAudioSource();
  24326. /** Changes the resampling ratio.
  24327. (This value can be changed at any time, even while the source is running).
  24328. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  24329. values will speed it up; lower values will slow it
  24330. down. The ratio must be greater than 0
  24331. */
  24332. void setResamplingRatio (const double samplesInPerOutputSample);
  24333. /** Returns the current resampling ratio.
  24334. This is the value that was set by setResamplingRatio().
  24335. */
  24336. double getResamplingRatio() const throw() { return ratio; }
  24337. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24338. void releaseResources();
  24339. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24340. juce_UseDebuggingNewOperator
  24341. private:
  24342. AudioSource* const input;
  24343. const bool deleteInputWhenDeleted;
  24344. double ratio, lastRatio;
  24345. AudioSampleBuffer buffer;
  24346. int bufferPos, sampsInBuffer;
  24347. double subSampleOffset;
  24348. double coefficients[6];
  24349. CriticalSection ratioLock;
  24350. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  24351. void createLowPass (const double proportionalRate);
  24352. struct FilterState
  24353. {
  24354. double x1, x2, y1, y2;
  24355. };
  24356. FilterState filterStates[2];
  24357. void resetFilters();
  24358. void applyFilter (float* samples, int num, FilterState& fs);
  24359. ResamplingAudioSource (const ResamplingAudioSource&);
  24360. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  24361. };
  24362. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24363. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  24364. /**
  24365. An AudioSource that takes a PositionableAudioSource and allows it to be
  24366. played, stopped, started, etc.
  24367. This can also be told use a buffer and background thread to read ahead, and
  24368. if can correct for different sample-rates.
  24369. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  24370. to control playback of an audio file.
  24371. @see AudioSource, AudioSourcePlayer
  24372. */
  24373. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  24374. public ChangeBroadcaster
  24375. {
  24376. public:
  24377. /** Creates an AudioTransportSource.
  24378. After creating one of these, use the setSource() method to select an input source.
  24379. */
  24380. AudioTransportSource();
  24381. /** Destructor. */
  24382. ~AudioTransportSource();
  24383. /** Sets the reader that is being used as the input source.
  24384. This will stop playback, reset the position to 0 and change to the new reader.
  24385. The source passed in will not be deleted by this object, so must be managed by
  24386. the caller.
  24387. @param newSource the new input source to use. This may be zero
  24388. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  24389. is zero, no reading ahead will be done; if it's
  24390. greater than zero, a BufferingAudioSource will be used
  24391. to do the reading-ahead
  24392. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  24393. rate of the source, and playback will be sample-rate
  24394. adjusted to maintain playback at the correct pitch. If
  24395. this is 0, no sample-rate adjustment will be performed
  24396. */
  24397. void setSource (PositionableAudioSource* const newSource,
  24398. int readAheadBufferSize = 0,
  24399. double sourceSampleRateToCorrectFor = 0.0);
  24400. /** Changes the current playback position in the source stream.
  24401. The next time the getNextAudioBlock() method is called, this
  24402. is the time from which it'll read data.
  24403. @see getPosition
  24404. */
  24405. void setPosition (double newPosition);
  24406. /** Returns the position that the next data block will be read from
  24407. This is a time in seconds.
  24408. */
  24409. double getCurrentPosition() const;
  24410. /** Returns true if the player has stopped because its input stream ran out of data.
  24411. */
  24412. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24413. /** Starts playing (if a source has been selected).
  24414. If it starts playing, this will send a message to any ChangeListeners
  24415. that are registered with this object.
  24416. */
  24417. void start();
  24418. /** Stops playing.
  24419. If it's actually playing, this will send a message to any ChangeListeners
  24420. that are registered with this object.
  24421. */
  24422. void stop();
  24423. /** Returns true if it's currently playing. */
  24424. bool isPlaying() const throw() { return playing; }
  24425. /** Changes the gain to apply to the output.
  24426. @param newGain a factor by which to multiply the outgoing samples,
  24427. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24428. */
  24429. void setGain (const float newGain) throw();
  24430. /** Returns the current gain setting.
  24431. @see setGain
  24432. */
  24433. float getGain() const throw() { return gain; }
  24434. /** Implementation of the AudioSource method. */
  24435. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24436. /** Implementation of the AudioSource method. */
  24437. void releaseResources();
  24438. /** Implementation of the AudioSource method. */
  24439. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24440. /** Implements the PositionableAudioSource method. */
  24441. void setNextReadPosition (int newPosition);
  24442. /** Implements the PositionableAudioSource method. */
  24443. int getNextReadPosition() const;
  24444. /** Implements the PositionableAudioSource method. */
  24445. int getTotalLength() const;
  24446. /** Implements the PositionableAudioSource method. */
  24447. bool isLooping() const;
  24448. juce_UseDebuggingNewOperator
  24449. private:
  24450. PositionableAudioSource* source;
  24451. ResamplingAudioSource* resamplerSource;
  24452. BufferingAudioSource* bufferingSource;
  24453. PositionableAudioSource* positionableSource;
  24454. AudioSource* masterSource;
  24455. CriticalSection callbackLock;
  24456. float volatile gain, lastGain;
  24457. bool volatile playing, stopped;
  24458. double sampleRate, sourceSampleRate;
  24459. int blockSize, readAheadBufferSize;
  24460. bool isPrepared, inputStreamEOF;
  24461. AudioTransportSource (const AudioTransportSource&);
  24462. const AudioTransportSource& operator= (const AudioTransportSource&);
  24463. };
  24464. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24465. /********* End of inlined file: juce_AudioTransportSource.h *********/
  24466. #endif
  24467. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24468. #endif
  24469. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24470. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  24471. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24472. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24473. /**
  24474. An AudioSource that takes the audio from another source, and re-maps its
  24475. input and output channels to a different arrangement.
  24476. You can use this to increase or decrease the number of channels that an
  24477. audio source uses, or to re-order those channels.
  24478. Call the reset() method before using it to set up a default mapping, and then
  24479. the setInputChannelMapping() and setOutputChannelMapping() methods to
  24480. create an appropriate mapping, otherwise no channels will be connected and
  24481. it'll produce silence.
  24482. @see AudioSource
  24483. */
  24484. class ChannelRemappingAudioSource : public AudioSource
  24485. {
  24486. public:
  24487. /** Creates a remapping source that will pass on audio from the given input.
  24488. @param source the input source to use. Make sure that this doesn't
  24489. get deleted before the ChannelRemappingAudioSource object
  24490. @param deleteSourceWhenDeleted if true, the input source will be deleted
  24491. when this object is deleted, if false, the caller is
  24492. responsible for its deletion
  24493. */
  24494. ChannelRemappingAudioSource (AudioSource* const source,
  24495. const bool deleteSourceWhenDeleted);
  24496. /** Destructor. */
  24497. ~ChannelRemappingAudioSource();
  24498. /** Specifies a number of channels that this audio source must produce from its
  24499. getNextAudioBlock() callback.
  24500. */
  24501. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  24502. /** Clears any mapped channels.
  24503. After this, no channels are mapped, so this object will produce silence. Create
  24504. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  24505. */
  24506. void clearAllMappings() throw();
  24507. /** Creates an input channel mapping.
  24508. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  24509. data will be sent to destChannelIndex of our input source.
  24510. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  24511. source specified when this object was created).
  24512. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  24513. during our getNextAudioBlock() callback
  24514. */
  24515. void setInputChannelMapping (const int destChannelIndex,
  24516. const int sourceChannelIndex) throw();
  24517. /** Creates an output channel mapping.
  24518. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  24519. our input audio source will be copied to channel destChannelIndex of the final buffer.
  24520. @param sourceChannelIndex the index of an output channel coming from our input audio source
  24521. (i.e. the source specified when this object was created).
  24522. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  24523. during our getNextAudioBlock() callback
  24524. */
  24525. void setOutputChannelMapping (const int sourceChannelIndex,
  24526. const int destChannelIndex) throw();
  24527. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  24528. our input audio source.
  24529. */
  24530. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  24531. /** Returns the output channel to which channel outputChannelIndex of our input audio
  24532. source will be sent to.
  24533. */
  24534. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  24535. /** Returns an XML object to encapsulate the state of the mappings.
  24536. @see restoreFromXml
  24537. */
  24538. XmlElement* createXml() const throw();
  24539. /** Restores the mappings from an XML object created by createXML().
  24540. @see createXml
  24541. */
  24542. void restoreFromXml (const XmlElement& e) throw();
  24543. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24544. void releaseResources();
  24545. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24546. juce_UseDebuggingNewOperator
  24547. private:
  24548. int requiredNumberOfChannels;
  24549. Array <int> remappedInputs, remappedOutputs;
  24550. AudioSource* const source;
  24551. const bool deleteSourceWhenDeleted;
  24552. AudioSampleBuffer buffer;
  24553. AudioSourceChannelInfo remappedInfo;
  24554. CriticalSection lock;
  24555. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  24556. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  24557. };
  24558. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24559. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  24560. #endif
  24561. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24562. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  24563. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24564. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24565. /**
  24566. An AudioSource that performs an IIR filter on another source.
  24567. */
  24568. class JUCE_API IIRFilterAudioSource : public AudioSource
  24569. {
  24570. public:
  24571. /** Creates a IIRFilterAudioSource for a given input source.
  24572. @param inputSource the input source to read from
  24573. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24574. this object is deleted
  24575. */
  24576. IIRFilterAudioSource (AudioSource* const inputSource,
  24577. const bool deleteInputWhenDeleted);
  24578. /** Destructor. */
  24579. ~IIRFilterAudioSource();
  24580. /** Changes the filter to use the same parameters as the one being passed in.
  24581. */
  24582. void setFilterParameters (const IIRFilter& newSettings);
  24583. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24584. void releaseResources();
  24585. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24586. juce_UseDebuggingNewOperator
  24587. private:
  24588. AudioSource* const input;
  24589. const bool deleteInputWhenDeleted;
  24590. OwnedArray <IIRFilter> iirFilters;
  24591. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24592. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24593. };
  24594. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24595. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  24596. #endif
  24597. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24598. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  24599. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24600. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24601. /**
  24602. An AudioSource that mixes together the output of a set of other AudioSources.
  24603. Input sources can be added and removed while the mixer is running as long as their
  24604. prepareToPlay() and releaseResources() methods are called before and after adding
  24605. them to the mixer.
  24606. */
  24607. class JUCE_API MixerAudioSource : public AudioSource
  24608. {
  24609. public:
  24610. /** Creates a MixerAudioSource.
  24611. */
  24612. MixerAudioSource();
  24613. /** Destructor. */
  24614. ~MixerAudioSource();
  24615. /** Adds an input source to the mixer.
  24616. If the mixer is running you'll need to make sure that the input source
  24617. is ready to play by calling its prepareToPlay() method before adding it.
  24618. If the mixer is stopped, then its input sources will be automatically
  24619. prepared when the mixer's prepareToPlay() method is called.
  24620. @param newInput the source to add to the mixer
  24621. @param deleteWhenRemoved if true, then this source will be deleted when
  24622. the mixer is deleted or when removeAllInputs() is
  24623. called (unless the source is previously removed
  24624. with the removeInputSource method)
  24625. */
  24626. void addInputSource (AudioSource* newInput,
  24627. const bool deleteWhenRemoved);
  24628. /** Removes an input source.
  24629. If the mixer is running, this will remove the source but not call its
  24630. releaseResources() method, so the caller might want to do this manually.
  24631. @param input the source to remove
  24632. @param deleteSource whether to delete this source after it's been removed
  24633. */
  24634. void removeInputSource (AudioSource* input,
  24635. const bool deleteSource);
  24636. /** Removes all the input sources.
  24637. If the mixer is running, this will remove the sources but not call their
  24638. releaseResources() method, so the caller might want to do this manually.
  24639. Any sources which were added with the deleteWhenRemoved flag set will be
  24640. deleted by this method.
  24641. */
  24642. void removeAllInputs();
  24643. /** Implementation of the AudioSource method.
  24644. This will call prepareToPlay() on all its input sources.
  24645. */
  24646. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24647. /** Implementation of the AudioSource method.
  24648. This will call releaseResources() on all its input sources.
  24649. */
  24650. void releaseResources();
  24651. /** Implementation of the AudioSource method. */
  24652. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24653. juce_UseDebuggingNewOperator
  24654. private:
  24655. VoidArray inputs;
  24656. BitArray inputsToDelete;
  24657. CriticalSection lock;
  24658. AudioSampleBuffer tempBuffer;
  24659. double currentSampleRate;
  24660. int bufferSizeExpected;
  24661. MixerAudioSource (const MixerAudioSource&);
  24662. const MixerAudioSource& operator= (const MixerAudioSource&);
  24663. };
  24664. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24665. /********* End of inlined file: juce_MixerAudioSource.h *********/
  24666. #endif
  24667. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24668. #endif
  24669. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24670. #endif
  24671. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24672. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24673. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24674. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24675. /**
  24676. A simple AudioSource that generates a sine wave.
  24677. */
  24678. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24679. {
  24680. public:
  24681. /** Creates a ToneGeneratorAudioSource. */
  24682. ToneGeneratorAudioSource();
  24683. /** Destructor. */
  24684. ~ToneGeneratorAudioSource();
  24685. /** Sets the signal's amplitude. */
  24686. void setAmplitude (const float newAmplitude);
  24687. /** Sets the signal's frequency. */
  24688. void setFrequency (const double newFrequencyHz);
  24689. /** Implementation of the AudioSource method. */
  24690. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24691. /** Implementation of the AudioSource method. */
  24692. void releaseResources();
  24693. /** Implementation of the AudioSource method. */
  24694. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24695. juce_UseDebuggingNewOperator
  24696. private:
  24697. double frequency, sampleRate;
  24698. double currentPhase, phasePerSample;
  24699. float amplitude;
  24700. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24701. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24702. };
  24703. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24704. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24705. #endif
  24706. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24707. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  24708. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24709. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24710. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  24711. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24712. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24713. class AudioDeviceManager;
  24714. class Component;
  24715. /**
  24716. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24717. To get a list of available audio driver types, use the createDeviceTypes()
  24718. method. Each of the objects returned can then be used to list the available
  24719. devices of that type. E.g.
  24720. @code
  24721. OwnedArray <AudioIODeviceType> types;
  24722. AudioIODeviceType::createDeviceTypes (types);
  24723. for (int i = 0; i < types.size(); ++i)
  24724. {
  24725. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24726. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24727. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24728. for (int j = 0; j < deviceNames.size(); ++j)
  24729. {
  24730. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24731. ...
  24732. }
  24733. }
  24734. @endcode
  24735. For an easier way of managing audio devices and their settings, have a look at the
  24736. AudioDeviceManager class.
  24737. @see AudioIODevice, AudioDeviceManager
  24738. */
  24739. class JUCE_API AudioIODeviceType
  24740. {
  24741. public:
  24742. /** Returns the name of this type of driver that this object manages.
  24743. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24744. */
  24745. const String& getTypeName() const throw() { return typeName; }
  24746. /** Refreshes the object's cached list of known devices.
  24747. This must be called at least once before calling getDeviceNames() or any of
  24748. the other device creation methods.
  24749. */
  24750. virtual void scanForDevices() = 0;
  24751. /** Returns the list of available devices of this type.
  24752. The scanForDevices() method must have been called to create this list.
  24753. @param wantInputNames only really used by DirectSound where devices are split up
  24754. into inputs and outputs, this indicates whether to use
  24755. the input or output name to refer to a pair of devices.
  24756. */
  24757. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  24758. /** Returns the name of the default device.
  24759. This will be one of the names from the getDeviceNames() list.
  24760. @param forInput if true, this means that a default input device should be
  24761. returned; if false, it should return the default output
  24762. */
  24763. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  24764. /** Returns the index of a given device in the list of device names.
  24765. If asInput is true, it shows the index in the inputs list, otherwise it
  24766. looks for it in the outputs list.
  24767. */
  24768. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  24769. /** Returns true if two different devices can be used for the input and output.
  24770. */
  24771. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24772. /** Creates one of the devices of this type.
  24773. The deviceName must be one of the strings returned by getDeviceNames(), and
  24774. scanForDevices() must have been called before this method is used.
  24775. */
  24776. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24777. const String& inputDeviceName) = 0;
  24778. struct DeviceSetupDetails
  24779. {
  24780. AudioDeviceManager* manager;
  24781. int minNumInputChannels, maxNumInputChannels;
  24782. int minNumOutputChannels, maxNumOutputChannels;
  24783. bool useStereoPairs;
  24784. };
  24785. /** Destructor. */
  24786. virtual ~AudioIODeviceType();
  24787. protected:
  24788. AudioIODeviceType (const tchar* const typeName);
  24789. private:
  24790. String typeName;
  24791. AudioIODeviceType (const AudioIODeviceType&);
  24792. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  24793. };
  24794. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24795. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  24796. /********* Start of inlined file: juce_MidiOutput.h *********/
  24797. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24798. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24799. /**
  24800. Represents a midi output device.
  24801. To create one of these, use the static getDevices() method to find out what
  24802. outputs are available, then use the openDevice() method to try to open one.
  24803. @see MidiInput
  24804. */
  24805. class JUCE_API MidiOutput : private Thread
  24806. {
  24807. public:
  24808. /** Returns a list of the available midi output devices.
  24809. You can open one of the devices by passing its index into the
  24810. openDevice() method.
  24811. @see getDefaultDeviceIndex, openDevice
  24812. */
  24813. static const StringArray getDevices();
  24814. /** Returns the index of the default midi output device to use.
  24815. This refers to the index in the list returned by getDevices().
  24816. */
  24817. static int getDefaultDeviceIndex();
  24818. /** Tries to open one of the midi output devices.
  24819. This will return a MidiOutput object if it manages to open it. You can then
  24820. send messages to this device, and delete it when no longer needed.
  24821. If the device can't be opened, this will return a null pointer.
  24822. @param deviceIndex the index of a device from the list returned by getDevices()
  24823. @see getDevices
  24824. */
  24825. static MidiOutput* openDevice (int deviceIndex);
  24826. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  24827. /** This will try to create a new midi output device (Not available on Windows).
  24828. This will attempt to create a new midi output device that other apps can connect
  24829. to and use as their midi input.
  24830. Returns 0 if a device can't be created.
  24831. @param deviceName the name to use for the new device
  24832. */
  24833. static MidiOutput* createNewDevice (const String& deviceName);
  24834. #endif
  24835. /** Destructor. */
  24836. virtual ~MidiOutput();
  24837. /** Makes this device output a midi message.
  24838. @see MidiMessage
  24839. */
  24840. virtual void sendMessageNow (const MidiMessage& message);
  24841. /** Sends a midi reset to the device. */
  24842. virtual void reset();
  24843. /** Returns the current volume setting for this device. */
  24844. virtual bool getVolume (float& leftVol,
  24845. float& rightVol);
  24846. /** Changes the overall volume for this device. */
  24847. virtual void setVolume (float leftVol,
  24848. float rightVol);
  24849. /** This lets you supply a block of messages that will be sent out at some point
  24850. in the future.
  24851. The MidiOutput class has an internal thread that can send out timestamped
  24852. messages - this appends a set of messages to its internal buffer, ready for
  24853. sending.
  24854. This will only work if you've already started the thread with startBackgroundThread().
  24855. A time is supplied, at which the block of messages should be sent. This time uses
  24856. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24857. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24858. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24859. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24860. real time.
  24861. */
  24862. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24863. const double millisecondCounterToStartAt,
  24864. double samplesPerSecondForBuffer) throw();
  24865. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24866. */
  24867. virtual void clearAllPendingMessages() throw();
  24868. /** Starts up a background thread so that the device can send blocks of data.
  24869. Call this to get the device ready, before using sendBlockOfMessages().
  24870. */
  24871. virtual void startBackgroundThread() throw();
  24872. /** Stops the background thread, and clears any pending midi events.
  24873. @see startBackgroundThread
  24874. */
  24875. virtual void stopBackgroundThread() throw();
  24876. juce_UseDebuggingNewOperator
  24877. protected:
  24878. void* internal;
  24879. struct PendingMessage
  24880. {
  24881. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24882. MidiMessage message;
  24883. PendingMessage* next;
  24884. juce_UseDebuggingNewOperator
  24885. };
  24886. CriticalSection lock;
  24887. PendingMessage* firstMessage;
  24888. MidiOutput() throw();
  24889. MidiOutput (const MidiOutput&);
  24890. void run();
  24891. };
  24892. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24893. /********* End of inlined file: juce_MidiOutput.h *********/
  24894. /********* Start of inlined file: juce_ComboBox.h *********/
  24895. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24896. #define __JUCE_COMBOBOX_JUCEHEADER__
  24897. /********* Start of inlined file: juce_Label.h *********/
  24898. #ifndef __JUCE_LABEL_JUCEHEADER__
  24899. #define __JUCE_LABEL_JUCEHEADER__
  24900. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24901. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24902. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24903. /**
  24904. Object for monitoring a component, and later testing whether it's still valid.
  24905. Slightly obscure, this one, but it's used internally for making sure that
  24906. after some callbacks, a component hasn't been deleted. It's more reliable than
  24907. just using isValidComponent(), which can provide false-positives if a new
  24908. component is created at the same memory location as an old one.
  24909. */
  24910. class JUCE_API ComponentDeletionWatcher
  24911. {
  24912. public:
  24913. /** Creates a watcher for a given component.
  24914. The component must be valid at the time it's passed in.
  24915. */
  24916. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24917. /** Destructor. */
  24918. ~ComponentDeletionWatcher() throw();
  24919. /** Returns true if the component has been deleted since the time that this
  24920. object was created.
  24921. */
  24922. bool hasBeenDeleted() const throw();
  24923. /** Returns the component that's being watched, or null if it has been deleted. */
  24924. const Component* getComponent() const throw();
  24925. juce_UseDebuggingNewOperator
  24926. private:
  24927. const Component* const componentToWatch;
  24928. const uint32 componentUID;
  24929. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24930. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24931. };
  24932. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24933. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24934. /********* Start of inlined file: juce_TextEditor.h *********/
  24935. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24936. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24937. /********* Start of inlined file: juce_UndoManager.h *********/
  24938. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24939. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24940. /********* Start of inlined file: juce_UndoableAction.h *********/
  24941. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24942. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24943. /**
  24944. Used by the UndoManager class to store an action which can be done
  24945. and undone.
  24946. @see UndoManager
  24947. */
  24948. class JUCE_API UndoableAction
  24949. {
  24950. protected:
  24951. /** Creates an action. */
  24952. UndoableAction() throw() {}
  24953. public:
  24954. /** Destructor. */
  24955. virtual ~UndoableAction() {}
  24956. /** Overridden by a subclass to perform the action.
  24957. This method is called by the UndoManager, and shouldn't be used directly by
  24958. applications.
  24959. Be careful not to make any calls in a perform() method that could call
  24960. recursively back into the UndoManager::perform() method
  24961. @returns true if the action could be performed.
  24962. @see UndoManager::perform
  24963. */
  24964. virtual bool perform() = 0;
  24965. /** Overridden by a subclass to undo the action.
  24966. This method is called by the UndoManager, and shouldn't be used directly by
  24967. applications.
  24968. Be careful not to make any calls in an undo() method that could call
  24969. recursively back into the UndoManager::perform() method
  24970. @returns true if the action could be undone without any errors.
  24971. @see UndoManager::perform
  24972. */
  24973. virtual bool undo() = 0;
  24974. /** Returns a value to indicate how much memory this object takes up.
  24975. Because the UndoManager keeps a list of UndoableActions, this is used
  24976. to work out how much space each one will take up, so that the UndoManager
  24977. can work out how many to keep.
  24978. The default value returned here is 10 - units are arbitrary and
  24979. don't have to be accurate.
  24980. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24981. UndoManager::setMaxNumberOfStoredUnits
  24982. */
  24983. virtual int getSizeInUnits() { return 10; }
  24984. };
  24985. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24986. /********* End of inlined file: juce_UndoableAction.h *********/
  24987. /**
  24988. Manages a list of undo/redo commands.
  24989. An UndoManager object keeps a list of past actions and can use these actions
  24990. to move backwards and forwards through an undo history.
  24991. To use it, create subclasses of UndoableAction which perform all the
  24992. actions you need, then when you need to actually perform an action, create one
  24993. and pass it to the UndoManager's perform() method.
  24994. The manager also uses the concept of 'transactions' to group the actions
  24995. together - all actions performed between calls to beginNewTransaction() are
  24996. grouped together and are all undone/redone as a group.
  24997. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24998. when actions are performed or undone.
  24999. @see UndoableAction
  25000. */
  25001. class JUCE_API UndoManager : public ChangeBroadcaster
  25002. {
  25003. public:
  25004. /** Creates an UndoManager.
  25005. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  25006. to indicate how much storage it takes up
  25007. (UndoableAction::getSizeInUnits()), so this
  25008. lets you specify the maximum total number of
  25009. units that the undomanager is allowed to
  25010. keep in memory before letting the older actions
  25011. drop off the end of the list.
  25012. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  25013. that will be kept, even if this involves exceeding
  25014. the amount of space specified in maxNumberOfUnitsToKeep
  25015. */
  25016. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  25017. const int minimumTransactionsToKeep = 30);
  25018. /** Destructor. */
  25019. ~UndoManager();
  25020. /** Deletes all stored actions in the list. */
  25021. void clearUndoHistory();
  25022. /** Returns the current amount of space to use for storing UndoableAction objects.
  25023. @see setMaxNumberOfStoredUnits
  25024. */
  25025. int getNumberOfUnitsTakenUpByStoredCommands() const;
  25026. /** Sets the amount of space that can be used for storing UndoableAction objects.
  25027. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  25028. to indicate how much storage it takes up
  25029. (UndoableAction::getSizeInUnits()), so this
  25030. lets you specify the maximum total number of
  25031. units that the undomanager is allowed to
  25032. keep in memory before letting the older actions
  25033. drop off the end of the list.
  25034. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  25035. that will be kept, even if this involves exceeding
  25036. the amount of space specified in maxNumberOfUnitsToKeep
  25037. @see getNumberOfUnitsTakenUpByStoredCommands
  25038. */
  25039. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  25040. const int minimumTransactionsToKeep);
  25041. /** Performs an action and adds it to the undo history list.
  25042. @param action the action to perform - this will be deleted by the UndoManager
  25043. when no longer needed
  25044. @param actionName if this string is non-empty, the current transaction will be
  25045. given this name; if it's empty, the current transaction name will
  25046. be left unchanged. See setCurrentTransactionName()
  25047. @returns true if the command succeeds - see UndoableAction::perform
  25048. @see beginNewTransaction
  25049. */
  25050. bool perform (UndoableAction* const action,
  25051. const String& actionName = String::empty);
  25052. /** Starts a new group of actions that together will be treated as a single transaction.
  25053. All actions that are passed to the perform() method between calls to this
  25054. method are grouped together and undone/redone together by a single call to
  25055. undo() or redo().
  25056. @param actionName a description of the transaction that is about to be
  25057. performed
  25058. */
  25059. void beginNewTransaction (const String& actionName = String::empty);
  25060. /** Changes the name stored for the current transaction.
  25061. Each transaction is given a name when the beginNewTransaction() method is
  25062. called, but this can be used to change that name without starting a new
  25063. transaction.
  25064. */
  25065. void setCurrentTransactionName (const String& newName);
  25066. /** Returns true if there's at least one action in the list to undo.
  25067. @see getUndoDescription, undo, canRedo
  25068. */
  25069. bool canUndo() const;
  25070. /** Returns the description of the transaction that would be next to get undone.
  25071. The description returned is the one that was passed into beginNewTransaction
  25072. before the set of actions was performed.
  25073. @see undo
  25074. */
  25075. const String getUndoDescription() const;
  25076. /** Tries to roll-back the last transaction.
  25077. @returns true if the transaction can be undone, and false if it fails, or
  25078. if there aren't any transactions to undo
  25079. */
  25080. bool undo();
  25081. /** Tries to roll-back any actions that were added to the current transaction.
  25082. This will perform an undo() only if there are some actions in the undo list
  25083. that were added after the last call to beginNewTransaction().
  25084. This is useful because it lets you call beginNewTransaction(), then
  25085. perform an operation which may or may not actually perform some actions, and
  25086. then call this method to get rid of any actions that might have been done
  25087. without it rolling back the previous transaction if nothing was actually
  25088. done.
  25089. @returns true if any actions were undone.
  25090. */
  25091. bool undoCurrentTransactionOnly();
  25092. /** Returns a list of the UndoableAction objects that have been performed during the
  25093. transaction that is currently open.
  25094. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  25095. were to be called now.
  25096. The first item in the list is the earliest action performed.
  25097. */
  25098. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  25099. /** Returns true if there's at least one action in the list to redo.
  25100. @see getRedoDescription, redo, canUndo
  25101. */
  25102. bool canRedo() const;
  25103. /** Returns the description of the transaction that would be next to get redone.
  25104. The description returned is the one that was passed into beginNewTransaction
  25105. before the set of actions was performed.
  25106. @see redo
  25107. */
  25108. const String getRedoDescription() const;
  25109. /** Tries to redo the last transaction that was undone.
  25110. @returns true if the transaction can be redone, and false if it fails, or
  25111. if there aren't any transactions to redo
  25112. */
  25113. bool redo();
  25114. juce_UseDebuggingNewOperator
  25115. private:
  25116. OwnedArray <OwnedArray <UndoableAction> > transactions;
  25117. StringArray transactionNames;
  25118. String currentTransactionName;
  25119. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  25120. bool newTransaction, reentrancyCheck;
  25121. // disallow copy constructor
  25122. UndoManager (const UndoManager&);
  25123. const UndoManager& operator= (const UndoManager&);
  25124. };
  25125. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  25126. /********* End of inlined file: juce_UndoManager.h *********/
  25127. class TextEditor;
  25128. class TextHolderComponent;
  25129. /**
  25130. Receives callbacks from a TextEditor component when it changes.
  25131. @see TextEditor::addListener
  25132. */
  25133. class JUCE_API TextEditorListener
  25134. {
  25135. public:
  25136. /** Destructor. */
  25137. virtual ~TextEditorListener() {}
  25138. /** Called when the user changes the text in some way. */
  25139. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  25140. /** Called when the user presses the return key. */
  25141. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  25142. /** Called when the user presses the escape key. */
  25143. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  25144. /** Called when the text editor loses focus. */
  25145. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  25146. };
  25147. /**
  25148. A component containing text that can be edited.
  25149. A TextEditor can either be in single- or multi-line mode, and supports mixed
  25150. fonts and colours.
  25151. @see TextEditorListener, Label
  25152. */
  25153. class JUCE_API TextEditor : public Component,
  25154. public SettableTooltipClient
  25155. {
  25156. public:
  25157. /** Creates a new, empty text editor.
  25158. @param componentName the name to pass to the component for it to use as its name
  25159. @param passwordCharacter if this is not zero, this character will be used as a replacement
  25160. for all characters that are drawn on screen - e.g. to create
  25161. a password-style textbox containing circular blobs instead of text,
  25162. you could set this value to 0x25cf, which is the unicode character
  25163. for a black splodge (not all fonts include this, though), or 0x2022,
  25164. which is a bullet (probably the best choice for linux).
  25165. */
  25166. TextEditor (const String& componentName = String::empty,
  25167. const tchar passwordCharacter = 0);
  25168. /** Destructor. */
  25169. virtual ~TextEditor();
  25170. /** Puts the editor into either multi- or single-line mode.
  25171. By default, the editor will be in single-line mode, so use this if you need a multi-line
  25172. editor.
  25173. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  25174. on if you want a multi-line editor with line-breaks.
  25175. @see isMultiLine, setReturnKeyStartsNewLine
  25176. */
  25177. void setMultiLine (const bool shouldBeMultiLine,
  25178. const bool shouldWordWrap = true);
  25179. /** Returns true if the editor is in multi-line mode.
  25180. */
  25181. bool isMultiLine() const throw();
  25182. /** Changes the behaviour of the return key.
  25183. If set to true, the return key will insert a new-line into the text; if false
  25184. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  25185. method. By default this is set to false, and when true it will only insert
  25186. new-lines when in multi-line mode (see setMultiLine()).
  25187. */
  25188. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  25189. /** Returns the value set by setReturnKeyStartsNewLine().
  25190. See setReturnKeyStartsNewLine() for more info.
  25191. */
  25192. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  25193. /** Indicates whether the tab key should be accepted and used to input a tab character,
  25194. or whether it gets ignored.
  25195. By default the tab key is ignored, so that it can be used to switch keyboard focus
  25196. between components.
  25197. */
  25198. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  25199. /** Returns true if the tab key is being used for input.
  25200. @see setTabKeyUsedAsCharacter
  25201. */
  25202. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  25203. /** Changes the editor to read-only mode.
  25204. By default, the text editor is not read-only. If you're making it read-only, you
  25205. might also want to call setCaretVisible (false) to get rid of the caret.
  25206. The text can still be highlighted and copied when in read-only mode.
  25207. @see isReadOnly, setCaretVisible
  25208. */
  25209. void setReadOnly (const bool shouldBeReadOnly);
  25210. /** Returns true if the editor is in read-only mode.
  25211. */
  25212. bool isReadOnly() const throw();
  25213. /** Makes the caret visible or invisible.
  25214. By default the caret is visible.
  25215. @see setCaretColour, setCaretPosition
  25216. */
  25217. void setCaretVisible (const bool shouldBeVisible) throw();
  25218. /** Returns true if the caret is enabled.
  25219. @see setCaretVisible
  25220. */
  25221. bool isCaretVisible() const throw() { return caretVisible; }
  25222. /** Enables/disables a vertical scrollbar.
  25223. (This only applies when in multi-line mode). When the text gets too long to fit
  25224. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  25225. this is enabled, the scrollbar will be hidden unless it's needed.
  25226. By default the scrollbar is enabled.
  25227. */
  25228. void setScrollbarsShown (bool shouldBeEnabled) throw();
  25229. /** Returns true if scrollbars are enabled.
  25230. @see setScrollbarsShown
  25231. */
  25232. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  25233. /** Changes the password character used to disguise the text.
  25234. @param passwordCharacter if this is not zero, this character will be used as a replacement
  25235. for all characters that are drawn on screen - e.g. to create
  25236. a password-style textbox containing circular blobs instead of text,
  25237. you could set this value to 0x25cf, which is the unicode character
  25238. for a black splodge (not all fonts include this, though), or 0x2022,
  25239. which is a bullet (probably the best choice for linux).
  25240. */
  25241. void setPasswordCharacter (const tchar passwordCharacter) throw();
  25242. /** Returns the current password character.
  25243. @see setPasswordCharacter
  25244. l */
  25245. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  25246. /** Allows a right-click menu to appear for the editor.
  25247. (This defaults to being enabled).
  25248. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  25249. of options such as cut/copy/paste, undo/redo, etc.
  25250. */
  25251. void setPopupMenuEnabled (const bool menuEnabled) throw();
  25252. /** Returns true if the right-click menu is enabled.
  25253. @see setPopupMenuEnabled
  25254. */
  25255. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  25256. /** Returns true if a popup-menu is currently being displayed.
  25257. */
  25258. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  25259. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  25260. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25261. methods.
  25262. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25263. */
  25264. enum ColourIds
  25265. {
  25266. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  25267. transparent if necessary. */
  25268. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  25269. that because the editor can contain multiple colours, calling this
  25270. method won't change the colour of existing text - to do that, call
  25271. applyFontToAllText() after calling this method.*/
  25272. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  25273. the text - this can be transparent if you don't want to show any
  25274. highlighting.*/
  25275. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  25276. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  25277. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  25278. the edge of the component. */
  25279. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  25280. the edge of the component when it has focus. */
  25281. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  25282. around the edge of the editor. */
  25283. };
  25284. /** Sets the font to use for newly added text.
  25285. This will change the font that will be used next time any text is added or entered
  25286. into the editor. It won't change the font of any existing text - to do that, use
  25287. applyFontToAllText() instead.
  25288. @see applyFontToAllText
  25289. */
  25290. void setFont (const Font& newFont) throw();
  25291. /** Applies a font to all the text in the editor.
  25292. This will also set the current font to use for any new text that's added.
  25293. @see setFont
  25294. */
  25295. void applyFontToAllText (const Font& newFont);
  25296. /** Returns the font that's currently being used for new text.
  25297. @see setFont
  25298. */
  25299. const Font getFont() const throw();
  25300. /** If set to true, focusing on the editor will highlight all its text.
  25301. (Set to false by default).
  25302. This is useful for boxes where you expect the user to re-enter all the
  25303. text when they focus on the component, rather than editing what's already there.
  25304. */
  25305. void setSelectAllWhenFocused (const bool b) throw();
  25306. /** Sets limits on the characters that can be entered.
  25307. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  25308. limit is set
  25309. @param allowedCharacters if this is non-empty, then only characters that occur in
  25310. this string are allowed to be entered into the editor.
  25311. */
  25312. void setInputRestrictions (const int maxTextLength,
  25313. const String& allowedCharacters = String::empty) throw();
  25314. /** When the text editor is empty, it can be set to display a message.
  25315. This is handy for things like telling the user what to type in the box - the
  25316. string is only displayed, it's not taken to actually be the contents of
  25317. the editor.
  25318. */
  25319. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  25320. /** Changes the size of the scrollbars that are used.
  25321. Handy if you need smaller scrollbars for a small text box.
  25322. */
  25323. void setScrollBarThickness (const int newThicknessPixels);
  25324. /** Shows or hides the buttons on any scrollbars that are used.
  25325. @see ScrollBar::setButtonVisibility
  25326. */
  25327. void setScrollBarButtonVisibility (const bool buttonsVisible);
  25328. /** Registers a listener to be told when things happen to the text.
  25329. @see removeListener
  25330. */
  25331. void addListener (TextEditorListener* const newListener) throw();
  25332. /** Deregisters a listener.
  25333. @see addListener
  25334. */
  25335. void removeListener (TextEditorListener* const listenerToRemove) throw();
  25336. /** Returns the entire contents of the editor. */
  25337. const String getText() const throw();
  25338. /** Returns a section of the contents of the editor. */
  25339. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  25340. /** Returns true if there are no characters in the editor.
  25341. This is more efficient than calling getText().isEmpty().
  25342. */
  25343. bool isEmpty() const throw();
  25344. /** Sets the entire content of the editor.
  25345. This will clear the editor and insert the given text (using the current text colour
  25346. and font). You can set the current text colour using
  25347. @code setColour (TextEditor::textColourId, ...);
  25348. @endcode
  25349. @param newText the text to add
  25350. @param sendTextChangeMessage if true, this will cause a change message to
  25351. be sent to all the listeners.
  25352. @see insertText
  25353. */
  25354. void setText (const String& newText,
  25355. const bool sendTextChangeMessage = true);
  25356. /** Inserts some text at the current cursor position.
  25357. If a section of the text is highlighted, it will be replaced by
  25358. this string, otherwise it will be inserted.
  25359. To delete a section of text, you can use setHighlightedRegion() to
  25360. highlight it, and call insertTextAtCursor (String::empty).
  25361. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  25362. */
  25363. void insertTextAtCursor (String textToInsert);
  25364. /** Deletes all the text from the editor. */
  25365. void clear();
  25366. /** Deletes the currently selected region, and puts it on the clipboard.
  25367. @see copy, paste, SystemClipboard
  25368. */
  25369. void cut();
  25370. /** Copies any currently selected region to the clipboard.
  25371. @see cut, paste, SystemClipboard
  25372. */
  25373. void copy();
  25374. /** Pastes the contents of the clipboard into the editor at the cursor position.
  25375. @see cut, copy, SystemClipboard
  25376. */
  25377. void paste();
  25378. /** Moves the caret to be in front of a given character.
  25379. @see getCaretPosition
  25380. */
  25381. void setCaretPosition (const int newIndex) throw();
  25382. /** Returns the current index of the caret.
  25383. @see setCaretPosition
  25384. */
  25385. int getCaretPosition() const throw();
  25386. /** Attempts to scroll the text editor so that the caret ends up at
  25387. a specified position.
  25388. This won't affect the caret's position within the text, it tries to scroll
  25389. the entire editor vertically and horizontally so that the caret is sitting
  25390. at the given position (relative to the top-left of this component).
  25391. Depending on the amount of text available, it might not be possible to
  25392. scroll far enough for the caret to reach this exact position, but it
  25393. will go as far as it can in that direction.
  25394. */
  25395. void scrollEditorToPositionCaret (const int desiredCaretX,
  25396. const int desiredCaretY) throw();
  25397. /** Get the graphical position of the caret.
  25398. The rectangle returned is relative to the component's top-left corner.
  25399. @see scrollEditorToPositionCaret
  25400. */
  25401. const Rectangle getCaretRectangle() throw();
  25402. /** Selects a section of the text.
  25403. */
  25404. void setHighlightedRegion (int startIndex,
  25405. int numberOfCharactersToHighlight) throw();
  25406. /** Returns the first character that is selected.
  25407. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  25408. will return 0.
  25409. @see setHighlightedRegion, getHighlightedRegionLength
  25410. */
  25411. int getHighlightedRegionStart() const throw() { return selectionStart; }
  25412. /** Returns the number of characters that are selected.
  25413. @see setHighlightedRegion, getHighlightedRegionStart
  25414. */
  25415. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  25416. /** Returns the section of text that is currently selected. */
  25417. const String getHighlightedText() const throw();
  25418. /** Finds the index of the character at a given position.
  25419. The co-ordinates are relative to the component's top-left.
  25420. */
  25421. int getTextIndexAt (const int x, const int y) throw();
  25422. /** Counts the number of characters in the text.
  25423. This is quicker than getting the text as a string if you just need to know
  25424. the length.
  25425. */
  25426. int getTotalNumChars() throw();
  25427. /** Returns the total width of the text, as it is currently laid-out.
  25428. This may be larger than the size of the TextEditor, and can change when
  25429. the TextEditor is resized or the text changes.
  25430. */
  25431. int getTextWidth() const throw();
  25432. /** Returns the maximum height of the text, as it is currently laid-out.
  25433. This may be larger than the size of the TextEditor, and can change when
  25434. the TextEditor is resized or the text changes.
  25435. */
  25436. int getTextHeight() const throw();
  25437. /** Changes the size of the gap at the top and left-edge of the editor.
  25438. By default there's a gap of 4 pixels.
  25439. */
  25440. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  25441. /** Changes the size of border left around the edge of the component.
  25442. @see getBorder
  25443. */
  25444. void setBorder (const BorderSize& border) throw();
  25445. /** Returns the size of border around the edge of the component.
  25446. @see setBorder
  25447. */
  25448. const BorderSize getBorder() const throw();
  25449. /** Used to disable the auto-scrolling which keeps the cursor visible.
  25450. If true (the default), the editor will scroll when the cursor moves offscreen. If
  25451. set to false, it won't.
  25452. */
  25453. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  25454. /** @internal */
  25455. void paint (Graphics& g);
  25456. /** @internal */
  25457. void paintOverChildren (Graphics& g);
  25458. /** @internal */
  25459. void mouseDown (const MouseEvent& e);
  25460. /** @internal */
  25461. void mouseUp (const MouseEvent& e);
  25462. /** @internal */
  25463. void mouseDrag (const MouseEvent& e);
  25464. /** @internal */
  25465. void mouseDoubleClick (const MouseEvent& e);
  25466. /** @internal */
  25467. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25468. /** @internal */
  25469. bool keyPressed (const KeyPress& key);
  25470. /** @internal */
  25471. bool keyStateChanged (const bool isKeyDown);
  25472. /** @internal */
  25473. void focusGained (FocusChangeType cause);
  25474. /** @internal */
  25475. void focusLost (FocusChangeType cause);
  25476. /** @internal */
  25477. void resized();
  25478. /** @internal */
  25479. void enablementChanged();
  25480. /** @internal */
  25481. void colourChanged();
  25482. juce_UseDebuggingNewOperator
  25483. protected:
  25484. /** This adds the items to the popup menu.
  25485. By default it adds the cut/copy/paste items, but you can override this if
  25486. you need to replace these with your own items.
  25487. If you want to add your own items to the existing ones, you can override this,
  25488. call the base class's addPopupMenuItems() method, then append your own items.
  25489. When the menu has been shown, performPopupMenuAction() will be called to
  25490. perform the item that the user has chosen.
  25491. The default menu items will be added using item IDs in the range
  25492. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  25493. menu IDs.
  25494. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  25495. a pointer to the info about it, or may be null if the menu is being triggered
  25496. by some other means.
  25497. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  25498. */
  25499. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  25500. const MouseEvent* mouseClickEvent);
  25501. /** This is called to perform one of the items that was shown on the popup menu.
  25502. If you've overridden addPopupMenuItems(), you should also override this
  25503. to perform the actions that you've added.
  25504. If you've overridden addPopupMenuItems() but have still left the default items
  25505. on the menu, remember to call the superclass's performPopupMenuAction()
  25506. so that it can perform the default actions if that's what the user clicked on.
  25507. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  25508. */
  25509. virtual void performPopupMenuAction (const int menuItemID);
  25510. /** Scrolls the minimum distance needed to get the caret into view. */
  25511. void scrollToMakeSureCursorIsVisible() throw();
  25512. /** @internal */
  25513. void moveCaret (int newCaretPos) throw();
  25514. /** @internal */
  25515. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  25516. /** Used internally to dispatch a text-change message. */
  25517. void textChanged() throw();
  25518. /** Begins a new transaction in the UndoManager.
  25519. */
  25520. void newTransaction() throw();
  25521. /** Used internally to trigger an undo or redo. */
  25522. void doUndoRedo (const bool isRedo);
  25523. /** Can be overridden to intercept return key presses directly */
  25524. virtual void returnPressed();
  25525. /** Can be overridden to intercept escape key presses directly */
  25526. virtual void escapePressed();
  25527. /** @internal */
  25528. void handleCommandMessage (int commandId);
  25529. private:
  25530. Viewport* viewport;
  25531. TextHolderComponent* textHolder;
  25532. BorderSize borderSize;
  25533. bool readOnly : 1;
  25534. bool multiline : 1;
  25535. bool wordWrap : 1;
  25536. bool returnKeyStartsNewLine : 1;
  25537. bool caretVisible : 1;
  25538. bool popupMenuEnabled : 1;
  25539. bool selectAllTextWhenFocused : 1;
  25540. bool scrollbarVisible : 1;
  25541. bool wasFocused : 1;
  25542. bool caretFlashState : 1;
  25543. bool keepCursorOnScreen : 1;
  25544. bool tabKeyUsed : 1;
  25545. bool menuActive : 1;
  25546. UndoManager undoManager;
  25547. float cursorX, cursorY, cursorHeight;
  25548. int maxTextLength;
  25549. int selectionStart, selectionEnd;
  25550. int leftIndent, topIndent;
  25551. unsigned int lastTransactionTime;
  25552. Font currentFont;
  25553. int totalNumChars, caretPosition;
  25554. VoidArray sections;
  25555. String textToShowWhenEmpty;
  25556. Colour colourForTextWhenEmpty;
  25557. tchar passwordCharacter;
  25558. enum
  25559. {
  25560. notDragging,
  25561. draggingSelectionStart,
  25562. draggingSelectionEnd
  25563. } dragType;
  25564. String allowedCharacters;
  25565. SortedSet <void*> listeners;
  25566. friend class TextEditorInsertAction;
  25567. friend class TextEditorRemoveAction;
  25568. void coalesceSimilarSections() throw();
  25569. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  25570. void clearInternal (UndoManager* const um) throw();
  25571. void insert (const String& text,
  25572. const int insertIndex,
  25573. const Font& font,
  25574. const Colour& colour,
  25575. UndoManager* const um,
  25576. const int caretPositionToMoveTo) throw();
  25577. void reinsert (const int insertIndex,
  25578. const VoidArray& sections) throw();
  25579. void remove (const int startIndex,
  25580. int endIndex,
  25581. UndoManager* const um,
  25582. const int caretPositionToMoveTo) throw();
  25583. void getCharPosition (const int index,
  25584. float& x, float& y,
  25585. float& lineHeight) const throw();
  25586. void updateCaretPosition() throw();
  25587. int indexAtPosition (const float x,
  25588. const float y) throw();
  25589. int findWordBreakAfter (const int position) const throw();
  25590. int findWordBreakBefore (const int position) const throw();
  25591. friend class TextHolderComponent;
  25592. friend class TextEditorViewport;
  25593. void drawContent (Graphics& g);
  25594. void updateTextHolderSize() throw();
  25595. float getWordWrapWidth() const throw();
  25596. void timerCallbackInt();
  25597. void repaintCaret();
  25598. void repaintText (int textStartIndex, int textEndIndex);
  25599. TextEditor (const TextEditor&);
  25600. const TextEditor& operator= (const TextEditor&);
  25601. };
  25602. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  25603. /********* End of inlined file: juce_TextEditor.h *********/
  25604. class Label;
  25605. /**
  25606. A class for receiving events from a Label.
  25607. You can register a LabelListener with a Label using the Label::addListener()
  25608. method, and it will be called when the text of the label changes, either because
  25609. of a call to Label::setText() or by the user editing the text (if the label is
  25610. editable).
  25611. @see Label::addListener, Label::removeListener
  25612. */
  25613. class JUCE_API LabelListener
  25614. {
  25615. public:
  25616. /** Destructor. */
  25617. virtual ~LabelListener() {}
  25618. /** Called when a Label's text has changed.
  25619. */
  25620. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  25621. };
  25622. /**
  25623. A component that displays a text string, and can optionally become a text
  25624. editor when clicked.
  25625. */
  25626. class JUCE_API Label : public Component,
  25627. public SettableTooltipClient,
  25628. protected TextEditorListener,
  25629. private ComponentListener
  25630. {
  25631. public:
  25632. /** Creates a Label.
  25633. @param componentName the name to give the component
  25634. @param labelText the text to show in the label
  25635. */
  25636. Label (const String& componentName,
  25637. const String& labelText);
  25638. /** Destructor. */
  25639. ~Label();
  25640. /** Changes the label text.
  25641. If broadcastChangeMessage is true and the new text is different to the current
  25642. text, then the class will broadcast a change message to any LabelListeners that
  25643. are registered.
  25644. */
  25645. void setText (const String& newText,
  25646. const bool broadcastChangeMessage);
  25647. /** Returns the label's current text.
  25648. @param returnActiveEditorContents if this is true and the label is currently
  25649. being edited, then this method will return the
  25650. text as it's being shown in the editor. If false,
  25651. then the value returned here won't be updated until
  25652. the user has finished typing and pressed the return
  25653. key.
  25654. */
  25655. const String getText (const bool returnActiveEditorContents = false) const throw();
  25656. /** Changes the font to use to draw the text.
  25657. @see getFont
  25658. */
  25659. void setFont (const Font& newFont) throw();
  25660. /** Returns the font currently being used.
  25661. @see setFont
  25662. */
  25663. const Font& getFont() const throw();
  25664. /** A set of colour IDs to use to change the colour of various aspects of the label.
  25665. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25666. methods.
  25667. Note that you can also use the constants from TextEditor::ColourIds to change the
  25668. colour of the text editor that is opened when a label is editable.
  25669. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25670. */
  25671. enum ColourIds
  25672. {
  25673. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  25674. textColourId = 0x1000281, /**< The colour for the text. */
  25675. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25676. Leave this transparent to not have an outline. */
  25677. };
  25678. /** Sets the style of justification to be used for positioning the text.
  25679. (The default is Justification::centredLeft)
  25680. */
  25681. void setJustificationType (const Justification& justification) throw();
  25682. /** Returns the type of justification, as set in setJustificationType(). */
  25683. const Justification getJustificationType() const throw() { return justification; }
  25684. /** Changes the gap that is left between the edge of the component and the text.
  25685. By default there's a small gap left at the sides of the component to allow for
  25686. the drawing of the border, but you can change this if necessary.
  25687. */
  25688. void setBorderSize (int horizontalBorder, int verticalBorder);
  25689. /** Returns the size of the horizontal gap being left around the text.
  25690. */
  25691. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25692. /** Returns the size of the vertical gap being left around the text.
  25693. */
  25694. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25695. /** Makes this label "stick to" another component.
  25696. This will cause the label to follow another component around, staying
  25697. either to its left or above it.
  25698. @param owner the component to follow
  25699. @param onLeft if true, the label will stay on the left of its component; if
  25700. false, it will stay above it.
  25701. */
  25702. void attachToComponent (Component* owner,
  25703. const bool onLeft);
  25704. /** If this label has been attached to another component using attachToComponent, this
  25705. returns the other component.
  25706. Returns 0 if the label is not attached.
  25707. */
  25708. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25709. /** If the label is attached to the left of another component, this returns true.
  25710. Returns false if the label is above the other component. This is only relevent if
  25711. attachToComponent() has been called.
  25712. */
  25713. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25714. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25715. using ellipsis.
  25716. @see Graphics::drawFittedText
  25717. */
  25718. void setMinimumHorizontalScale (const float newScale);
  25719. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25720. /** Registers a listener that will be called when the label's text changes. */
  25721. void addListener (LabelListener* const listener) throw();
  25722. /** Deregisters a previously-registered listener. */
  25723. void removeListener (LabelListener* const listener) throw();
  25724. /** Makes the label turn into a TextEditor when clicked.
  25725. By default this is turned off.
  25726. If turned on, then single- or double-clicking will turn the label into
  25727. an editor. If the user then changes the text, then the ChangeBroadcaster
  25728. base class will be used to send change messages to any listeners that
  25729. have registered.
  25730. If the user changes the text, the textWasEdited() method will be called
  25731. afterwards, and subclasses can override this if they need to do anything
  25732. special.
  25733. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25734. @param editOnDoubleClick if true, a double-click is needed to start editing
  25735. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25736. edited will discard any changes; if false, then this will
  25737. commit the changes.
  25738. @see showEditor, setEditorColours, TextEditor
  25739. */
  25740. void setEditable (const bool editOnSingleClick,
  25741. const bool editOnDoubleClick = false,
  25742. const bool lossOfFocusDiscardsChanges = false) throw();
  25743. /** Returns true if this option was set using setEditable(). */
  25744. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25745. /** Returns true if this option was set using setEditable(). */
  25746. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25747. /** Returns true if this option has been set in a call to setEditable(). */
  25748. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25749. /** Returns true if the user can edit this label's text. */
  25750. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25751. /** Makes the editor appear as if the label had been clicked by the user.
  25752. @see textWasEdited, setEditable
  25753. */
  25754. void showEditor();
  25755. /** Hides the editor if it was being shown.
  25756. @param discardCurrentEditorContents if true, the label's text will be
  25757. reset to whatever it was before the editor
  25758. was shown; if false, the current contents of the
  25759. editor will be used to set the label's text
  25760. before it is hidden.
  25761. */
  25762. void hideEditor (const bool discardCurrentEditorContents);
  25763. /** Returns true if the editor is currently focused and active. */
  25764. bool isBeingEdited() const throw();
  25765. juce_UseDebuggingNewOperator
  25766. protected:
  25767. /** @internal */
  25768. void paint (Graphics& g);
  25769. /** @internal */
  25770. void resized();
  25771. /** @internal */
  25772. void mouseUp (const MouseEvent& e);
  25773. /** @internal */
  25774. void mouseDoubleClick (const MouseEvent& e);
  25775. /** @internal */
  25776. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25777. /** @internal */
  25778. void componentParentHierarchyChanged (Component& component);
  25779. /** @internal */
  25780. void componentVisibilityChanged (Component& component);
  25781. /** @internal */
  25782. void inputAttemptWhenModal();
  25783. /** @internal */
  25784. void focusGained (FocusChangeType);
  25785. /** @internal */
  25786. void enablementChanged();
  25787. /** @internal */
  25788. KeyboardFocusTraverser* createFocusTraverser();
  25789. /** @internal */
  25790. void textEditorTextChanged (TextEditor& editor);
  25791. /** @internal */
  25792. void textEditorReturnKeyPressed (TextEditor& editor);
  25793. /** @internal */
  25794. void textEditorEscapeKeyPressed (TextEditor& editor);
  25795. /** @internal */
  25796. void textEditorFocusLost (TextEditor& editor);
  25797. /** @internal */
  25798. void colourChanged();
  25799. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25800. Subclasses can override this if they need to customise this component in some way.
  25801. */
  25802. virtual TextEditor* createEditorComponent();
  25803. /** Called after the user changes the text.
  25804. */
  25805. virtual void textWasEdited();
  25806. /** Called when the text has been altered.
  25807. */
  25808. virtual void textWasChanged();
  25809. /** Called when the text editor has just appeared, due to a user click or other
  25810. focus change.
  25811. */
  25812. virtual void editorShown (TextEditor* editorComponent);
  25813. /** Called when the text editor is going to be deleted, after editing has finished.
  25814. */
  25815. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  25816. private:
  25817. String text;
  25818. Font font;
  25819. Justification justification;
  25820. TextEditor* editor;
  25821. SortedSet <void*> listeners;
  25822. Component* ownerComponent;
  25823. ComponentDeletionWatcher* deletionWatcher;
  25824. int horizontalBorderSize, verticalBorderSize;
  25825. float minimumHorizontalScale;
  25826. bool editSingleClick : 1;
  25827. bool editDoubleClick : 1;
  25828. bool lossOfFocusDiscardsChanges : 1;
  25829. bool leftOfOwnerComp : 1;
  25830. bool updateFromTextEditorContents();
  25831. void callChangeListeners();
  25832. Label (const Label&);
  25833. const Label& operator= (const Label&);
  25834. };
  25835. #endif // __JUCE_LABEL_JUCEHEADER__
  25836. /********* End of inlined file: juce_Label.h *********/
  25837. class ComboBox;
  25838. /**
  25839. A class for receiving events from a ComboBox.
  25840. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25841. method, and it will be called when the selected item in the box changes.
  25842. @see ComboBox::addListener, ComboBox::removeListener
  25843. */
  25844. class JUCE_API ComboBoxListener
  25845. {
  25846. public:
  25847. /** Destructor. */
  25848. virtual ~ComboBoxListener() {}
  25849. /** Called when a ComboBox has its selected item changed.
  25850. */
  25851. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25852. };
  25853. /**
  25854. A component that lets the user choose from a drop-down list of choices.
  25855. The combo-box has a list of text strings, each with an associated id number,
  25856. that will be shown in the drop-down list when the user clicks on the component.
  25857. The currently selected choice is displayed in the combo-box, and this can
  25858. either be read-only text, or editable.
  25859. To find out when the user selects a different item or edits the text, you
  25860. can register a ComboBoxListener to receive callbacks.
  25861. @see ComboBoxListener
  25862. */
  25863. class JUCE_API ComboBox : public Component,
  25864. public SettableTooltipClient,
  25865. private LabelListener,
  25866. private AsyncUpdater
  25867. {
  25868. public:
  25869. /** Creates a combo-box.
  25870. On construction, the text field will be empty, so you should call the
  25871. setSelectedId() or setText() method to choose the initial value before
  25872. displaying it.
  25873. @param componentName the name to set for the component (see Component::setName())
  25874. */
  25875. ComboBox (const String& componentName);
  25876. /** Destructor. */
  25877. ~ComboBox();
  25878. /** Sets whether the test in the combo-box is editable.
  25879. The default state for a new ComboBox is non-editable, and can only be changed
  25880. by choosing from the drop-down list.
  25881. */
  25882. void setEditableText (const bool isEditable);
  25883. /** Returns true if the text is directly editable.
  25884. @see setEditableText
  25885. */
  25886. bool isTextEditable() const throw();
  25887. /** Sets the style of justification to be used for positioning the text.
  25888. The default is Justification::centredLeft. The text is displayed using a
  25889. Label component inside the ComboBox.
  25890. */
  25891. void setJustificationType (const Justification& justification) throw();
  25892. /** Returns the current justification for the text box.
  25893. @see setJustificationType
  25894. */
  25895. const Justification getJustificationType() const throw();
  25896. /** Adds an item to be shown in the drop-down list.
  25897. @param newItemText the text of the item to show in the list
  25898. @param newItemId an associated ID number that can be set or retrieved - see
  25899. getSelectedId() and setSelectedId()
  25900. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25901. */
  25902. void addItem (const String& newItemText,
  25903. const int newItemId) throw();
  25904. /** Adds a separator line to the drop-down list.
  25905. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25906. */
  25907. void addSeparator() throw();
  25908. /** Adds a heading to the drop-down list, so that you can group the items into
  25909. different sections.
  25910. The headings are indented slightly differently to set them apart from the
  25911. items on the list, and obviously can't be selected. You might want to add
  25912. separators between your sections too.
  25913. @see addItem, addSeparator
  25914. */
  25915. void addSectionHeading (const String& headingName) throw();
  25916. /** This allows items in the drop-down list to be selectively disabled.
  25917. When you add an item, it's enabled by default, but you can call this
  25918. method to change its status.
  25919. If you disable an item which is already selected, this won't change the
  25920. current selection - it just stops the user choosing that item from the list.
  25921. */
  25922. void setItemEnabled (const int itemId,
  25923. const bool isEnabled) throw();
  25924. /** Changes the text for an existing item.
  25925. */
  25926. void changeItemText (const int itemId,
  25927. const String& newText) throw();
  25928. /** Removes all the items from the drop-down list.
  25929. If this call causes the content to be cleared, then a change-message
  25930. will be broadcast unless dontSendChangeMessage is true.
  25931. @see addItem, removeItem, getNumItems
  25932. */
  25933. void clear (const bool dontSendChangeMessage = false);
  25934. /** Returns the number of items that have been added to the list.
  25935. Note that this doesn't include headers or separators.
  25936. */
  25937. int getNumItems() const throw();
  25938. /** Returns the text for one of the items in the list.
  25939. Note that this doesn't include headers or separators.
  25940. @param index the item's index from 0 to (getNumItems() - 1)
  25941. */
  25942. const String getItemText (const int index) const throw();
  25943. /** Returns the ID for one of the items in the list.
  25944. Note that this doesn't include headers or separators.
  25945. @param index the item's index from 0 to (getNumItems() - 1)
  25946. */
  25947. int getItemId (const int index) const throw();
  25948. /** Returns the ID of the item that's currently shown in the box.
  25949. If no item is selected, or if the text is editable and the user
  25950. has entered something which isn't one of the items in the list, then
  25951. this will return 0.
  25952. @see setSelectedId, getSelectedItemIndex, getText
  25953. */
  25954. int getSelectedId() const throw();
  25955. /** Sets one of the items to be the current selection.
  25956. This will set the ComboBox's text to that of the item that matches
  25957. this ID.
  25958. @param newItemId the new item to select
  25959. @param dontSendChangeMessage if set to true, this method won't trigger a
  25960. change notification
  25961. @see getSelectedId, setSelectedItemIndex, setText
  25962. */
  25963. void setSelectedId (const int newItemId,
  25964. const bool dontSendChangeMessage = false) throw();
  25965. /** Returns the index of the item that's currently shown in the box.
  25966. If no item is selected, or if the text is editable and the user
  25967. has entered something which isn't one of the items in the list, then
  25968. this will return -1.
  25969. @see setSelectedItemIndex, getSelectedId, getText
  25970. */
  25971. int getSelectedItemIndex() const throw();
  25972. /** Sets one of the items to be the current selection.
  25973. This will set the ComboBox's text to that of the item at the given
  25974. index in the list.
  25975. @param newItemIndex the new item to select
  25976. @param dontSendChangeMessage if set to true, this method won't trigger a
  25977. change notification
  25978. @see getSelectedItemIndex, setSelectedId, setText
  25979. */
  25980. void setSelectedItemIndex (const int newItemIndex,
  25981. const bool dontSendChangeMessage = false) throw();
  25982. /** Returns the text that is currently shown in the combo-box's text field.
  25983. If the ComboBox has editable text, then this text may have been edited
  25984. by the user; otherwise it will be one of the items from the list, or
  25985. possibly an empty string if nothing was selected.
  25986. @see setText, getSelectedId, getSelectedItemIndex
  25987. */
  25988. const String getText() const throw();
  25989. /** Sets the contents of the combo-box's text field.
  25990. The text passed-in will be set as the current text regardless of whether
  25991. it is one of the items in the list. If the current text isn't one of the
  25992. items, then getSelectedId() will return -1, otherwise it wil return
  25993. the approriate ID.
  25994. @param newText the text to select
  25995. @param dontSendChangeMessage if set to true, this method won't trigger a
  25996. change notification
  25997. @see getText
  25998. */
  25999. void setText (const String& newText,
  26000. const bool dontSendChangeMessage = false) throw();
  26001. /** Programmatically opens the text editor to allow the user to edit the current item.
  26002. This is the same effect as when the box is clicked-on.
  26003. @see Label::showEditor();
  26004. */
  26005. void showEditor();
  26006. /** Registers a listener that will be called when the box's content changes. */
  26007. void addListener (ComboBoxListener* const listener) throw();
  26008. /** Deregisters a previously-registered listener. */
  26009. void removeListener (ComboBoxListener* const listener) throw();
  26010. /** Sets a message to display when there is no item currently selected.
  26011. @see getTextWhenNothingSelected
  26012. */
  26013. void setTextWhenNothingSelected (const String& newMessage) throw();
  26014. /** Returns the text that is shown when no item is selected.
  26015. @see setTextWhenNothingSelected
  26016. */
  26017. const String getTextWhenNothingSelected() const throw();
  26018. /** Sets the message to show when there are no items in the list, and the user clicks
  26019. on the drop-down box.
  26020. By default it just says "no choices", but this lets you change it to something more
  26021. meaningful.
  26022. */
  26023. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  26024. /** Returns the text shown when no items have been added to the list.
  26025. @see setTextWhenNoChoicesAvailable
  26026. */
  26027. const String getTextWhenNoChoicesAvailable() const throw();
  26028. /** Gives the ComboBox a tooltip. */
  26029. void setTooltip (const String& newTooltip);
  26030. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  26031. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26032. methods.
  26033. To change the colours of the menu that pops up
  26034. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26035. */
  26036. enum ColourIds
  26037. {
  26038. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  26039. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  26040. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  26041. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  26042. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  26043. };
  26044. /** @internal */
  26045. void labelTextChanged (Label*);
  26046. /** @internal */
  26047. void enablementChanged();
  26048. /** @internal */
  26049. void colourChanged();
  26050. /** @internal */
  26051. void focusGained (Component::FocusChangeType cause);
  26052. /** @internal */
  26053. void focusLost (Component::FocusChangeType cause);
  26054. /** @internal */
  26055. void handleAsyncUpdate();
  26056. /** @internal */
  26057. const String getTooltip() { return label->getTooltip(); }
  26058. /** @internal */
  26059. void mouseDown (const MouseEvent&);
  26060. /** @internal */
  26061. void mouseDrag (const MouseEvent&);
  26062. /** @internal */
  26063. void mouseUp (const MouseEvent&);
  26064. /** @internal */
  26065. void lookAndFeelChanged();
  26066. /** @internal */
  26067. void paint (Graphics&);
  26068. /** @internal */
  26069. void resized();
  26070. /** @internal */
  26071. bool keyStateChanged (const bool isKeyDown);
  26072. /** @internal */
  26073. bool keyPressed (const KeyPress&);
  26074. juce_UseDebuggingNewOperator
  26075. private:
  26076. struct ItemInfo
  26077. {
  26078. String name;
  26079. int itemId;
  26080. bool isEnabled : 1, isHeading : 1;
  26081. bool isSeparator() const throw();
  26082. bool isRealItem() const throw();
  26083. };
  26084. OwnedArray <ItemInfo> items;
  26085. int currentIndex;
  26086. bool isButtonDown;
  26087. bool separatorPending;
  26088. bool menuActive;
  26089. SortedSet <void*> listeners;
  26090. Label* label;
  26091. String textWhenNothingSelected, noChoicesMessage;
  26092. void showPopup();
  26093. ItemInfo* getItemForId (const int itemId) const throw();
  26094. ItemInfo* getItemForIndex (const int index) const throw();
  26095. ComboBox (const ComboBox&);
  26096. const ComboBox& operator= (const ComboBox&);
  26097. };
  26098. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  26099. /********* End of inlined file: juce_ComboBox.h *********/
  26100. /**
  26101. Manages the state of some audio and midi i/o devices.
  26102. This class keeps tracks of a currently-selected audio device, through
  26103. with which it continuously streams data from an audio callback, as well as
  26104. one or more midi inputs.
  26105. The idea is that your application will create one global instance of this object,
  26106. and let it take care of creating and deleting specific types of audio devices
  26107. internally. So when the device is changed, your callbacks will just keep running
  26108. without having to worry about this.
  26109. The manager can save and reload all of its device settings as XML, which
  26110. makes it very easy for you to save and reload the audio setup of your
  26111. application.
  26112. And to make it easy to let the user change its settings, there's a component
  26113. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  26114. device selection/sample-rate/latency controls.
  26115. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  26116. call addAudioCallback() to register your audio callback with it, and use that to process
  26117. your audio data.
  26118. The manager also acts as a handy hub for incoming midi messages, allowing a
  26119. listener to register for messages from either a specific midi device, or from whatever
  26120. the current default midi input device is. The listener then doesn't have to worry about
  26121. re-registering with different midi devices if they are changed or deleted.
  26122. And yet another neat trick is that amount of CPU time being used is measured and
  26123. available with the getCpuUsage() method.
  26124. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  26125. listeners whenever one of its settings is changed.
  26126. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  26127. */
  26128. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  26129. {
  26130. public:
  26131. /** Creates a default AudioDeviceManager.
  26132. Initially no audio device will be selected. You should call the initialise() method
  26133. and register an audio callback with setAudioCallback() before it'll be able to
  26134. actually make any noise.
  26135. */
  26136. AudioDeviceManager();
  26137. /** Destructor. */
  26138. ~AudioDeviceManager();
  26139. /**
  26140. This structure holds a set of properties describing the current audio setup.
  26141. @see AudioDeviceManager::setAudioDeviceSetup()
  26142. */
  26143. struct JUCE_API AudioDeviceSetup
  26144. {
  26145. AudioDeviceSetup();
  26146. bool operator== (const AudioDeviceSetup& other) const;
  26147. /** The name of the audio device used for output.
  26148. The name has to be one of the ones listed by the AudioDeviceManager's currently
  26149. selected device type.
  26150. This may be the same as the input device.
  26151. */
  26152. String outputDeviceName;
  26153. /** The name of the audio device used for input.
  26154. This may be the same as the output device.
  26155. */
  26156. String inputDeviceName;
  26157. /** The current sample rate.
  26158. This rate is used for both the input and output devices.
  26159. */
  26160. double sampleRate;
  26161. /** The buffer size, in samples.
  26162. This buffer size is used for both the input and output devices.
  26163. */
  26164. int bufferSize;
  26165. /** The set of active input channels.
  26166. The bits that are set in this array indicate the channels of the
  26167. input device that are active.
  26168. */
  26169. BitArray inputChannels;
  26170. /** If this is true, it indicates that the inputChannels array
  26171. should be ignored, and instead, the device's default channels
  26172. should be used.
  26173. */
  26174. bool useDefaultInputChannels;
  26175. /** The set of active output channels.
  26176. The bits that are set in this array indicate the channels of the
  26177. input device that are active.
  26178. */
  26179. BitArray outputChannels;
  26180. /** If this is true, it indicates that the outputChannels array
  26181. should be ignored, and instead, the device's default channels
  26182. should be used.
  26183. */
  26184. bool useDefaultOutputChannels;
  26185. };
  26186. /** Opens a set of audio devices ready for use.
  26187. This will attempt to open either a default audio device, or one that was
  26188. previously saved as XML.
  26189. @param numInputChannelsNeeded a minimum number of input channels needed
  26190. by your app.
  26191. @param numOutputChannelsNeeded a minimum number of output channels to open
  26192. @param savedState either a previously-saved state that was produced
  26193. by createStateXml(), or 0 if you want the manager
  26194. to choose the best device to open.
  26195. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  26196. fails to open, then a default device will be used
  26197. instead. If false, then on failure, no device is
  26198. opened.
  26199. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  26200. name, then that will be used as the default device
  26201. (assuming that there wasn't one specified in the XML).
  26202. The string can actually be a simple wildcard, containing "*"
  26203. and "?" characters
  26204. @param preferredSetupOptions if this is non-null, the structure will be used as the
  26205. set of preferred settings when opening the device. If you
  26206. use this parameter, the preferredDefaultDeviceName
  26207. field will be ignored
  26208. @returns an error message if anything went wrong, or an empty string if it worked ok.
  26209. */
  26210. const String initialise (const int numInputChannelsNeeded,
  26211. const int numOutputChannelsNeeded,
  26212. const XmlElement* const savedState,
  26213. const bool selectDefaultDeviceOnFailure,
  26214. const String& preferredDefaultDeviceName = String::empty,
  26215. const AudioDeviceSetup* preferredSetupOptions = 0);
  26216. /** Returns some XML representing the current state of the manager.
  26217. This stores the current device, its samplerate, block size, etc, and
  26218. can be restored later with initialise().
  26219. */
  26220. XmlElement* createStateXml() const;
  26221. /** Returns the current device properties that are in use.
  26222. @see setAudioDeviceSetup
  26223. */
  26224. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  26225. /** Changes the current device or its settings.
  26226. If you want to change a device property, like the current sample rate or
  26227. block size, you can call getAudioDeviceSetup() to retrieve the current
  26228. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  26229. and pass it back into this method to apply the new settings.
  26230. @param newSetup the settings that you'd like to use
  26231. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  26232. settings will be taken as having been explicitly chosen by the
  26233. user, and the next time createStateXml() is called, these settings
  26234. will be returned. If it's false, then the device is treated as a
  26235. temporary or default device, and a call to createStateXml() will
  26236. return either the last settings that were made with treatAsChosenDevice
  26237. as true, or the last XML settings that were passed into initialise().
  26238. @returns an error message if anything went wrong, or an empty string if it worked ok.
  26239. @see getAudioDeviceSetup
  26240. */
  26241. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  26242. const bool treatAsChosenDevice);
  26243. /** Returns the currently-active audio device. */
  26244. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  26245. /** Returns the type of audio device currently in use.
  26246. @see setCurrentAudioDeviceType
  26247. */
  26248. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  26249. /** Returns the currently active audio device type object.
  26250. Don't keep a copy of this pointer - it's owned by the device manager and could
  26251. change at any time.
  26252. */
  26253. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  26254. /** Changes the class of audio device being used.
  26255. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  26256. this because there's only one type: CoreAudio.
  26257. For a list of types, see getAvailableDeviceTypes().
  26258. */
  26259. void setCurrentAudioDeviceType (const String& type,
  26260. const bool treatAsChosenDevice);
  26261. /** Closes the currently-open device.
  26262. You can call restartLastAudioDevice() later to reopen it in the same state
  26263. that it was just in.
  26264. */
  26265. void closeAudioDevice();
  26266. /** Tries to reload the last audio device that was running.
  26267. Note that this only reloads the last device that was running before
  26268. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  26269. and can only be called after a device has been opened with SetAudioDevice().
  26270. If a device is already open, this call will do nothing.
  26271. */
  26272. void restartLastAudioDevice();
  26273. /** Registers an audio callback to be used.
  26274. The manager will redirect callbacks from whatever audio device is currently
  26275. in use to all registered callback objects. If more than one callback is
  26276. active, they will all be given the same input data, and their outputs will
  26277. be summed.
  26278. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  26279. object before returning.
  26280. To remove a callback, use removeAudioCallback().
  26281. */
  26282. void addAudioCallback (AudioIODeviceCallback* newCallback);
  26283. /** Deregisters a previously added callback.
  26284. If necessary, this method will invoke audioDeviceStopped() on the callback
  26285. object before returning.
  26286. @see addAudioCallback
  26287. */
  26288. void removeAudioCallback (AudioIODeviceCallback* callback);
  26289. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  26290. Returns a value between 0 and 1.0
  26291. */
  26292. double getCpuUsage() const;
  26293. /** Enables or disables a midi input device.
  26294. The list of devices can be obtained with the MidiInput::getDevices() method.
  26295. Any incoming messages from enabled input devices will be forwarded on to all the
  26296. listeners that have been registered with the addMidiInputCallback() method. They
  26297. can either register for messages from a particular device, or from just the
  26298. "default" midi input.
  26299. Routing the midi input via an AudioDeviceManager means that when a listener
  26300. registers for the default midi input, this default device can be changed by the
  26301. manager without the listeners having to know about it or re-register.
  26302. It also means that a listener can stay registered for a midi input that is disabled
  26303. or not present, so that when the input is re-enabled, the listener will start
  26304. receiving messages again.
  26305. @see addMidiInputCallback, isMidiInputEnabled
  26306. */
  26307. void setMidiInputEnabled (const String& midiInputDeviceName,
  26308. const bool enabled);
  26309. /** Returns true if a given midi input device is being used.
  26310. @see setMidiInputEnabled
  26311. */
  26312. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  26313. /** Registers a listener for callbacks when midi events arrive from a midi input.
  26314. The device name can be empty to indicate that it wants events from whatever the
  26315. current "default" device is. Or it can be the name of one of the midi input devices
  26316. (see MidiInput::getDevices() for the names).
  26317. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  26318. events forwarded on to listeners.
  26319. */
  26320. void addMidiInputCallback (const String& midiInputDeviceName,
  26321. MidiInputCallback* callback);
  26322. /** Removes a listener that was previously registered with addMidiInputCallback().
  26323. */
  26324. void removeMidiInputCallback (const String& midiInputDeviceName,
  26325. MidiInputCallback* callback);
  26326. /** Sets a midi output device to use as the default.
  26327. The list of devices can be obtained with the MidiOutput::getDevices() method.
  26328. The specified device will be opened automatically and can be retrieved with the
  26329. getDefaultMidiOutput() method.
  26330. Pass in an empty string to deselect all devices. For the default device, you
  26331. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  26332. @see getDefaultMidiOutput, getDefaultMidiOutputName
  26333. */
  26334. void setDefaultMidiOutput (const String& deviceName);
  26335. /** Returns the name of the default midi output.
  26336. @see setDefaultMidiOutput, getDefaultMidiOutput
  26337. */
  26338. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  26339. /** Returns the current default midi output device.
  26340. If no device has been selected, or the device can't be opened, this will
  26341. return 0.
  26342. @see getDefaultMidiOutputName
  26343. */
  26344. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  26345. /** Returns a list of the types of device supported.
  26346. */
  26347. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  26348. /** Creates a list of available types.
  26349. This will add a set of new AudioIODeviceType objects to the specified list, to
  26350. represent each available types of device.
  26351. You can override this if your app needs to do something specific, like avoid
  26352. using DirectSound devices, etc.
  26353. */
  26354. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  26355. /** Plays a beep through the current audio device.
  26356. This is here to allow the audio setup UI panels to easily include a "test"
  26357. button so that the user can check where the audio is coming from.
  26358. */
  26359. void playTestSound();
  26360. /** Turns on level-measuring.
  26361. When enabled, the device manager will measure the peak input level
  26362. across all channels, and you can get this level by calling getCurrentInputLevel().
  26363. This is mainly intended for audio setup UI panels to use to create a mic
  26364. level display, so that the user can check that they've selected the right
  26365. device.
  26366. A simple filter is used to make the level decay smoothly, but this is
  26367. only intended for giving rough feedback, and not for any kind of accurate
  26368. measurement.
  26369. */
  26370. void enableInputLevelMeasurement (const bool enableMeasurement);
  26371. /** Returns the current input level.
  26372. To use this, you must first enable it by calling enableInputLevelMeasurement().
  26373. See enableInputLevelMeasurement() for more info.
  26374. */
  26375. double getCurrentInputLevel() const;
  26376. juce_UseDebuggingNewOperator
  26377. private:
  26378. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  26379. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  26380. AudioDeviceSetup currentSetup;
  26381. AudioIODevice* currentAudioDevice;
  26382. SortedSet <AudioIODeviceCallback*> callbacks;
  26383. int numInputChansNeeded, numOutputChansNeeded;
  26384. String currentDeviceType;
  26385. BitArray inputChannels, outputChannels;
  26386. XmlElement* lastExplicitSettings;
  26387. mutable bool listNeedsScanning;
  26388. bool useInputNames;
  26389. int inputLevelMeasurementEnabledCount;
  26390. double inputLevel;
  26391. AudioSampleBuffer* testSound;
  26392. int testSoundPosition;
  26393. AudioSampleBuffer tempBuffer;
  26394. StringArray midiInsFromXml;
  26395. OwnedArray <MidiInput> enabledMidiInputs;
  26396. Array <MidiInputCallback*> midiCallbacks;
  26397. Array <MidiInput*> midiCallbackDevices;
  26398. String defaultMidiOutputName;
  26399. MidiOutput* defaultMidiOutput;
  26400. CriticalSection audioCallbackLock, midiCallbackLock;
  26401. double cpuUsageMs, timeToCpuScale;
  26402. class CallbackHandler : public AudioIODeviceCallback,
  26403. public MidiInputCallback
  26404. {
  26405. public:
  26406. AudioDeviceManager* owner;
  26407. void audioDeviceIOCallback (const float** inputChannelData,
  26408. int totalNumInputChannels,
  26409. float** outputChannelData,
  26410. int totalNumOutputChannels,
  26411. int numSamples);
  26412. void audioDeviceAboutToStart (AudioIODevice*);
  26413. void audioDeviceStopped();
  26414. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26415. };
  26416. CallbackHandler callbackHandler;
  26417. friend class CallbackHandler;
  26418. void audioDeviceIOCallbackInt (const float** inputChannelData,
  26419. int totalNumInputChannels,
  26420. float** outputChannelData,
  26421. int totalNumOutputChannels,
  26422. int numSamples);
  26423. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  26424. void audioDeviceStoppedInt();
  26425. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  26426. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  26427. const BitArray& ins, const BitArray& outs);
  26428. void stopDevice();
  26429. void updateXml();
  26430. void createDeviceTypesIfNeeded();
  26431. void scanDevicesIfNeeded();
  26432. void deleteCurrentDevice();
  26433. double chooseBestSampleRate (double preferred) const;
  26434. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  26435. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  26436. AudioDeviceManager (const AudioDeviceManager&);
  26437. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  26438. };
  26439. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26440. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  26441. #endif
  26442. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26443. #endif
  26444. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26445. #endif
  26446. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26447. #endif
  26448. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  26449. #endif
  26450. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26451. /********* Start of inlined file: juce_Sampler.h *********/
  26452. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26453. #define __JUCE_SAMPLER_JUCEHEADER__
  26454. /********* Start of inlined file: juce_Synthesiser.h *********/
  26455. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26456. #define __JUCE_SYNTHESISER_JUCEHEADER__
  26457. /**
  26458. Describes one of the sounds that a Synthesiser can play.
  26459. A synthesiser can contain one or more sounds, and a sound can choose which
  26460. midi notes and channels can trigger it.
  26461. The SynthesiserSound is a passive class that just describes what the sound is -
  26462. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  26463. more than one SynthesiserVoice to play the same sound at the same time.
  26464. @see Synthesiser, SynthesiserVoice
  26465. */
  26466. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  26467. {
  26468. protected:
  26469. SynthesiserSound();
  26470. public:
  26471. /** Destructor. */
  26472. virtual ~SynthesiserSound();
  26473. /** Returns true if this sound should be played when a given midi note is pressed.
  26474. The Synthesiser will use this information when deciding which sounds to trigger
  26475. for a given note.
  26476. */
  26477. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  26478. /** Returns true if the sound should be triggered by midi events on a given channel.
  26479. The Synthesiser will use this information when deciding which sounds to trigger
  26480. for a given note.
  26481. */
  26482. virtual bool appliesToChannel (const int midiChannel) = 0;
  26483. /**
  26484. */
  26485. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  26486. juce_UseDebuggingNewOperator
  26487. };
  26488. /**
  26489. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  26490. A voice plays a single sound at a time, and a synthesiser holds an array of
  26491. voices so that it can play polyphonically.
  26492. @see Synthesiser, SynthesiserSound
  26493. */
  26494. class JUCE_API SynthesiserVoice
  26495. {
  26496. public:
  26497. /** Creates a voice. */
  26498. SynthesiserVoice();
  26499. /** Destructor. */
  26500. virtual ~SynthesiserVoice();
  26501. /** Returns the midi note that this voice is currently playing.
  26502. Returns a value less than 0 if no note is playing.
  26503. */
  26504. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  26505. /** Returns the sound that this voice is currently playing.
  26506. Returns 0 if it's not playing.
  26507. */
  26508. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  26509. /** Must return true if this voice object is capable of playing the given sound.
  26510. If there are different classes of sound, and different classes of voice, a voice can
  26511. choose which ones it wants to take on.
  26512. A typical implementation of this method may just return true if there's only one type
  26513. of voice and sound, or it might check the type of the sound object passed-in and
  26514. see if it's one that it understands.
  26515. */
  26516. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  26517. /** Called to start a new note.
  26518. This will be called during the rendering callback, so must be fast and thread-safe.
  26519. */
  26520. virtual void startNote (const int midiNoteNumber,
  26521. const float velocity,
  26522. SynthesiserSound* sound,
  26523. const int currentPitchWheelPosition) = 0;
  26524. /** Called to stop a note.
  26525. This will be called during the rendering callback, so must be fast and thread-safe.
  26526. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  26527. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  26528. and allow the synth to reassign it another sound.
  26529. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  26530. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  26531. finishes playing (during the rendering callback), it must make sure that it calls
  26532. clearCurrentNote().
  26533. */
  26534. virtual void stopNote (const bool allowTailOff) = 0;
  26535. /** Called to let the voice know that the pitch wheel has been moved.
  26536. This will be called during the rendering callback, so must be fast and thread-safe.
  26537. */
  26538. virtual void pitchWheelMoved (const int newValue) = 0;
  26539. /** Called to let the voice know that a midi controller has been moved.
  26540. This will be called during the rendering callback, so must be fast and thread-safe.
  26541. */
  26542. virtual void controllerMoved (const int controllerNumber,
  26543. const int newValue) = 0;
  26544. /** Renders the next block of data for this voice.
  26545. The output audio data must be added to the current contents of the buffer provided.
  26546. Only the region of the buffer between startSample and (startSample + numSamples)
  26547. should be altered by this method.
  26548. If the voice is currently silent, it should just return without doing anything.
  26549. If the sound that the voice is playing finishes during the course of this rendered
  26550. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  26551. The size of the blocks that are rendered can change each time it is called, and may
  26552. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  26553. the voice's methods will be called to tell it about note and controller events.
  26554. */
  26555. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  26556. int startSample,
  26557. int numSamples) = 0;
  26558. /** Returns true if the voice is currently playing a sound which is mapped to the given
  26559. midi channel.
  26560. If it's not currently playing, this will return false.
  26561. */
  26562. bool isPlayingChannel (const int midiChannel) const;
  26563. /** Changes the voice's reference sample rate.
  26564. The rate is set so that subclasses know the output rate and can set their pitch
  26565. accordingly.
  26566. This method is called by the synth, and subclasses can access the current rate with
  26567. the currentSampleRate member.
  26568. */
  26569. void setCurrentPlaybackSampleRate (const double newRate);
  26570. juce_UseDebuggingNewOperator
  26571. protected:
  26572. /** Returns the current target sample rate at which rendering is being done.
  26573. This is available for subclasses so they can pitch things correctly.
  26574. */
  26575. double getSampleRate() const throw() { return currentSampleRate; }
  26576. /** Resets the state of this voice after a sound has finished playing.
  26577. The subclass must call this when it finishes playing a note and becomes available
  26578. to play new ones.
  26579. It must either call it in the stopNote() method, or if the voice is tailing off,
  26580. then it should call it later during the renderNextBlock method, as soon as it
  26581. finishes its tail-off.
  26582. It can also be called at any time during the render callback if the sound happens
  26583. to have finished, e.g. if it's playing a sample and the sample finishes.
  26584. */
  26585. void clearCurrentNote();
  26586. private:
  26587. friend class Synthesiser;
  26588. double currentSampleRate;
  26589. int currentlyPlayingNote;
  26590. uint32 noteOnTime;
  26591. SynthesiserSound::Ptr currentlyPlayingSound;
  26592. };
  26593. /**
  26594. Base class for a musical device that can play sounds.
  26595. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  26596. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  26597. which can play back one of these sounds.
  26598. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  26599. set of sounds, and a set of voices it can use to play them. If you only give it
  26600. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  26601. have available.
  26602. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  26603. events that go in will be scanned for note on/off messages, and these are used to
  26604. start and stop the voices playing the appropriate sounds.
  26605. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  26606. noteOff() and other controller methods.
  26607. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  26608. what the target playback rate is. This value is passed on to the voices so that
  26609. they can pitch their output correctly.
  26610. */
  26611. class JUCE_API Synthesiser
  26612. {
  26613. public:
  26614. /** Creates a new synthesiser.
  26615. You'll need to add some sounds and voices before it'll make any sound..
  26616. */
  26617. Synthesiser();
  26618. /** Destructor. */
  26619. virtual ~Synthesiser();
  26620. /** Deletes all voices. */
  26621. void clearVoices();
  26622. /** Returns the number of voices that have been added. */
  26623. int getNumVoices() const throw() { return voices.size(); }
  26624. /** Returns one of the voices that have been added. */
  26625. SynthesiserVoice* getVoice (const int index) const throw();
  26626. /** Adds a new voice to the synth.
  26627. All the voices should be the same class of object and are treated equally.
  26628. The object passed in will be managed by the synthesiser, which will delete
  26629. it later on when no longer needed. The caller should not retain a pointer to the
  26630. voice.
  26631. */
  26632. void addVoice (SynthesiserVoice* const newVoice);
  26633. /** Deletes one of the voices. */
  26634. void removeVoice (const int index);
  26635. /** Deletes all sounds. */
  26636. void clearSounds();
  26637. /** Returns the number of sounds that have been added to the synth. */
  26638. int getNumSounds() const throw() { return sounds.size(); }
  26639. /** Returns one of the sounds. */
  26640. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  26641. /** Adds a new sound to the synthesiser.
  26642. The object passed in is reference counted, so will be deleted when it is removed
  26643. from the synthesiser, and when no voices are still using it.
  26644. */
  26645. void addSound (const SynthesiserSound::Ptr& newSound);
  26646. /** Removes and deletes one of the sounds. */
  26647. void removeSound (const int index);
  26648. /** If set to true, then the synth will try to take over an existing voice if
  26649. it runs out and needs to play another note.
  26650. The value of this boolean is passed into findFreeVoice(), so the result will
  26651. depend on the implementation of this method.
  26652. */
  26653. void setNoteStealingEnabled (const bool shouldStealNotes);
  26654. /** Returns true if note-stealing is enabled.
  26655. @see setNoteStealingEnabled
  26656. */
  26657. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  26658. /** Triggers a note-on event.
  26659. The default method here will find all the sounds that want to be triggered by
  26660. this note/channel. For each sound, it'll try to find a free voice, and use the
  26661. voice to start playing the sound.
  26662. Subclasses might want to override this if they need a more complex algorithm.
  26663. This method will be called automatically according to the midi data passed into
  26664. renderNextBlock(), but may be called explicitly too.
  26665. */
  26666. virtual void noteOn (const int midiChannel,
  26667. const int midiNoteNumber,
  26668. const float velocity);
  26669. /** Triggers a note-off event.
  26670. This will turn off any voices that are playing a sound for the given note/channel.
  26671. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  26672. (if they can do). If this is false, the notes will all be cut off immediately.
  26673. This method will be called automatically according to the midi data passed into
  26674. renderNextBlock(), but may be called explicitly too.
  26675. */
  26676. virtual void noteOff (const int midiChannel,
  26677. const int midiNoteNumber,
  26678. const bool allowTailOff);
  26679. /** Turns off all notes.
  26680. This will turn off any voices that are playing a sound on the given midi channel.
  26681. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  26682. which channel they're playing.
  26683. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  26684. (if they can do). If this is false, the notes will all be cut off immediately.
  26685. This method will be called automatically according to the midi data passed into
  26686. renderNextBlock(), but may be called explicitly too.
  26687. */
  26688. virtual void allNotesOff (const int midiChannel,
  26689. const bool allowTailOff);
  26690. /** Sends a pitch-wheel message.
  26691. This will send a pitch-wheel message to any voices that are playing sounds on
  26692. the given midi channel.
  26693. This method will be called automatically according to the midi data passed into
  26694. renderNextBlock(), but may be called explicitly too.
  26695. @param midiChannel the midi channel for the event
  26696. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  26697. */
  26698. virtual void handlePitchWheel (const int midiChannel,
  26699. const int wheelValue);
  26700. /** Sends a midi controller message.
  26701. This will send a midi controller message to any voices that are playing sounds on
  26702. the given midi channel.
  26703. This method will be called automatically according to the midi data passed into
  26704. renderNextBlock(), but may be called explicitly too.
  26705. @param midiChannel the midi channel for the event
  26706. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  26707. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  26708. */
  26709. virtual void handleController (const int midiChannel,
  26710. const int controllerNumber,
  26711. const int controllerValue);
  26712. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  26713. render.
  26714. This value is propagated to the voices so that they can use it to render the correct
  26715. pitches.
  26716. */
  26717. void setCurrentPlaybackSampleRate (const double sampleRate);
  26718. /** Creates the next block of audio output.
  26719. This will process the next numSamples of data from all the voices, and add that output
  26720. to the audio block supplied, starting from the offset specified. Note that the
  26721. data will be added to the current contents of the buffer, so you should clear it
  26722. before calling this method if necessary.
  26723. The midi events in the inputMidi buffer are parsed for note and controller events,
  26724. and these are used to trigger the voices. Note that the startSample offset applies
  26725. both to the audio output buffer and the midi input buffer, so any midi events
  26726. with timestamps outside the specified region will be ignored.
  26727. */
  26728. void renderNextBlock (AudioSampleBuffer& outputAudio,
  26729. const MidiBuffer& inputMidi,
  26730. int startSample,
  26731. int numSamples);
  26732. juce_UseDebuggingNewOperator
  26733. protected:
  26734. /** This is used to control access to the rendering callback and the note trigger methods. */
  26735. CriticalSection lock;
  26736. OwnedArray <SynthesiserVoice> voices;
  26737. ReferenceCountedArray <SynthesiserSound> sounds;
  26738. /** The last pitch-wheel values for each midi channel. */
  26739. int lastPitchWheelValues [16];
  26740. /** Searches through the voices to find one that's not currently playing, and which
  26741. can play the given sound.
  26742. Returns 0 if all voices are busy and stealing isn't enabled.
  26743. This can be overridden to implement custom voice-stealing algorithms.
  26744. */
  26745. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  26746. const bool stealIfNoneAvailable) const;
  26747. /** Starts a specified voice playing a particular sound.
  26748. You'll probably never need to call this, it's used internally by noteOn(), but
  26749. may be needed by subclasses for custom behaviours.
  26750. */
  26751. void startVoice (SynthesiserVoice* const voice,
  26752. SynthesiserSound* const sound,
  26753. const int midiChannel,
  26754. const int midiNoteNumber,
  26755. const float velocity);
  26756. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  26757. int findFreeVoice (const bool) const { return 0; }
  26758. private:
  26759. double sampleRate;
  26760. uint32 lastNoteOnCounter;
  26761. bool shouldStealNotes;
  26762. Synthesiser (const Synthesiser&);
  26763. const Synthesiser& operator= (const Synthesiser&);
  26764. };
  26765. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  26766. /********* End of inlined file: juce_Synthesiser.h *********/
  26767. /**
  26768. A subclass of SynthesiserSound that represents a sampled audio clip.
  26769. This is a pretty basic sampler, and just attempts to load the whole audio stream
  26770. into memory.
  26771. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26772. give it some SampledSound objects to play.
  26773. @see SamplerVoice, Synthesiser, SynthesiserSound
  26774. */
  26775. class JUCE_API SamplerSound : public SynthesiserSound
  26776. {
  26777. public:
  26778. /** Creates a sampled sound from an audio reader.
  26779. This will attempt to load the audio from the source into memory and store
  26780. it in this object.
  26781. @param name a name for the sample
  26782. @param source the audio to load. This object can be safely deleted by the
  26783. caller after this constructor returns
  26784. @param midiNotes the set of midi keys that this sound should be played on. This
  26785. is used by the SynthesiserSound::appliesToNote() method
  26786. @param midiNoteForNormalPitch the midi note at which the sample should be played
  26787. with its natural rate. All other notes will be pitched
  26788. up or down relative to this one
  26789. @param attackTimeSecs the attack (fade-in) time, in seconds
  26790. @param releaseTimeSecs the decay (fade-out) time, in seconds
  26791. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  26792. source, in seconds
  26793. */
  26794. SamplerSound (const String& name,
  26795. AudioFormatReader& source,
  26796. const BitArray& midiNotes,
  26797. const int midiNoteForNormalPitch,
  26798. const double attackTimeSecs,
  26799. const double releaseTimeSecs,
  26800. const double maxSampleLengthSeconds);
  26801. /** Destructor. */
  26802. ~SamplerSound();
  26803. /** Returns the sample's name */
  26804. const String& getName() const throw() { return name; }
  26805. /** Returns the audio sample data.
  26806. This could be 0 if there was a problem loading it.
  26807. */
  26808. AudioSampleBuffer* getAudioData() const throw() { return data; }
  26809. bool appliesToNote (const int midiNoteNumber);
  26810. bool appliesToChannel (const int midiChannel);
  26811. juce_UseDebuggingNewOperator
  26812. private:
  26813. friend class SamplerVoice;
  26814. String name;
  26815. AudioSampleBuffer* data;
  26816. double sourceSampleRate;
  26817. BitArray midiNotes;
  26818. int length, attackSamples, releaseSamples;
  26819. int midiRootNote;
  26820. };
  26821. /**
  26822. A subclass of SynthesiserVoice that can play a SamplerSound.
  26823. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26824. give it some SampledSound objects to play.
  26825. @see SamplerSound, Synthesiser, SynthesiserVoice
  26826. */
  26827. class JUCE_API SamplerVoice : public SynthesiserVoice
  26828. {
  26829. public:
  26830. /** Creates a SamplerVoice.
  26831. */
  26832. SamplerVoice();
  26833. /** Destructor. */
  26834. ~SamplerVoice();
  26835. bool canPlaySound (SynthesiserSound* sound);
  26836. void startNote (const int midiNoteNumber,
  26837. const float velocity,
  26838. SynthesiserSound* sound,
  26839. const int currentPitchWheelPosition);
  26840. void stopNote (const bool allowTailOff);
  26841. void pitchWheelMoved (const int newValue);
  26842. void controllerMoved (const int controllerNumber,
  26843. const int newValue);
  26844. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  26845. juce_UseDebuggingNewOperator
  26846. private:
  26847. double pitchRatio;
  26848. double sourceSamplePosition;
  26849. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  26850. bool isInAttack, isInRelease;
  26851. };
  26852. #endif // __JUCE_SAMPLER_JUCEHEADER__
  26853. /********* End of inlined file: juce_Sampler.h *********/
  26854. #endif
  26855. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26856. #endif
  26857. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26858. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26859. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26860. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26861. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  26862. /**
  26863. Implements a plugin format manager for AudioUnits.
  26864. */
  26865. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  26866. {
  26867. public:
  26868. AudioUnitPluginFormat();
  26869. ~AudioUnitPluginFormat();
  26870. const String getName() const { return "AudioUnit"; }
  26871. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26872. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26873. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26874. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26875. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26876. bool doesPluginStillExist (const PluginDescription& desc);
  26877. const FileSearchPath getDefaultLocationsToSearch();
  26878. juce_UseDebuggingNewOperator
  26879. private:
  26880. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  26881. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  26882. };
  26883. #endif
  26884. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26885. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  26886. #endif
  26887. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26888. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  26889. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26890. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26891. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  26892. // Sorry, this file is just a placeholder at the moment!...
  26893. /**
  26894. Implements a plugin format manager for DirectX plugins.
  26895. */
  26896. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  26897. {
  26898. public:
  26899. DirectXPluginFormat();
  26900. ~DirectXPluginFormat();
  26901. const String getName() const { return "DirectX"; }
  26902. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26903. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26904. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26905. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26906. const FileSearchPath getDefaultLocationsToSearch();
  26907. juce_UseDebuggingNewOperator
  26908. private:
  26909. DirectXPluginFormat (const DirectXPluginFormat&);
  26910. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  26911. };
  26912. #endif
  26913. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26914. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  26915. #endif
  26916. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26917. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  26918. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26919. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26920. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  26921. // Sorry, this file is just a placeholder at the moment!...
  26922. /**
  26923. Implements a plugin format manager for DirectX plugins.
  26924. */
  26925. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26926. {
  26927. public:
  26928. LADSPAPluginFormat();
  26929. ~LADSPAPluginFormat();
  26930. const String getName() const { return "LADSPA"; }
  26931. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26932. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26933. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26934. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26935. const FileSearchPath getDefaultLocationsToSearch();
  26936. juce_UseDebuggingNewOperator
  26937. private:
  26938. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26939. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26940. };
  26941. #endif
  26942. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26943. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26944. #endif
  26945. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26946. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  26947. #ifdef __aeffect__
  26948. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26949. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26950. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26951. events to the list.
  26952. This is used by both the VST hosting code and the plugin wrapper.
  26953. */
  26954. class VSTMidiEventList
  26955. {
  26956. public:
  26957. VSTMidiEventList()
  26958. : events (0), numEventsUsed (0), numEventsAllocated (0)
  26959. {
  26960. }
  26961. ~VSTMidiEventList()
  26962. {
  26963. freeEvents();
  26964. }
  26965. void clear()
  26966. {
  26967. numEventsUsed = 0;
  26968. if (events != 0)
  26969. events->numEvents = 0;
  26970. }
  26971. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26972. {
  26973. ensureSize (numEventsUsed + 1);
  26974. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26975. events->numEvents = ++numEventsUsed;
  26976. if (numBytes <= 4)
  26977. {
  26978. if (e->type == kVstSysExType)
  26979. {
  26980. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26981. e->type = kVstMidiType;
  26982. e->byteSize = sizeof (VstMidiEvent);
  26983. e->noteLength = 0;
  26984. e->noteOffset = 0;
  26985. e->detune = 0;
  26986. e->noteOffVelocity = 0;
  26987. }
  26988. e->deltaFrames = frameOffset;
  26989. memcpy (e->midiData, midiData, numBytes);
  26990. }
  26991. else
  26992. {
  26993. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26994. if (se->type == kVstSysExType)
  26995. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26996. else
  26997. se->sysexDump = (char*) juce_malloc (numBytes);
  26998. memcpy (se->sysexDump, midiData, numBytes);
  26999. se->type = kVstSysExType;
  27000. se->byteSize = sizeof (VstMidiSysexEvent);
  27001. se->deltaFrames = frameOffset;
  27002. se->flags = 0;
  27003. se->dumpBytes = numBytes;
  27004. se->resvd1 = 0;
  27005. se->resvd2 = 0;
  27006. }
  27007. }
  27008. // Handy method to pull the events out of an event buffer supplied by the host
  27009. // or plugin.
  27010. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  27011. {
  27012. for (int i = 0; i < events->numEvents; ++i)
  27013. {
  27014. const VstEvent* const e = events->events[i];
  27015. if (e != 0)
  27016. {
  27017. if (e->type == kVstMidiType)
  27018. {
  27019. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  27020. 4, e->deltaFrames);
  27021. }
  27022. else if (e->type == kVstSysExType)
  27023. {
  27024. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  27025. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  27026. e->deltaFrames);
  27027. }
  27028. }
  27029. }
  27030. }
  27031. void ensureSize (int numEventsNeeded)
  27032. {
  27033. if (numEventsNeeded > numEventsAllocated)
  27034. {
  27035. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  27036. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  27037. if (events == 0)
  27038. events = (VstEvents*) juce_calloc (size);
  27039. else
  27040. events = (VstEvents*) juce_realloc (events, size);
  27041. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  27042. {
  27043. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  27044. (int) sizeof (VstMidiSysexEvent)));
  27045. e->type = kVstMidiType;
  27046. e->byteSize = sizeof (VstMidiEvent);
  27047. events->events[i] = (VstEvent*) e;
  27048. }
  27049. numEventsAllocated = numEventsNeeded;
  27050. }
  27051. }
  27052. void freeEvents()
  27053. {
  27054. if (events != 0)
  27055. {
  27056. for (int i = numEventsAllocated; --i >= 0;)
  27057. {
  27058. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  27059. if (e->type == kVstSysExType)
  27060. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27061. juce_free (e);
  27062. }
  27063. juce_free (events);
  27064. events = 0;
  27065. numEventsUsed = 0;
  27066. numEventsAllocated = 0;
  27067. }
  27068. }
  27069. VstEvents* events;
  27070. private:
  27071. int numEventsUsed, numEventsAllocated;
  27072. };
  27073. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27074. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27075. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  27076. #endif
  27077. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27078. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  27079. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27080. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27081. #if JUCE_PLUGINHOST_VST
  27082. /**
  27083. Implements a plugin format manager for VSTs.
  27084. */
  27085. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  27086. {
  27087. public:
  27088. VSTPluginFormat();
  27089. ~VSTPluginFormat();
  27090. const String getName() const { return "VST"; }
  27091. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27092. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27093. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27094. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27095. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27096. bool doesPluginStillExist (const PluginDescription& desc);
  27097. const FileSearchPath getDefaultLocationsToSearch();
  27098. juce_UseDebuggingNewOperator
  27099. private:
  27100. VSTPluginFormat (const VSTPluginFormat&);
  27101. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  27102. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  27103. };
  27104. #endif
  27105. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27106. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  27107. #endif
  27108. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27109. #endif
  27110. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27111. #endif
  27112. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27113. #endif
  27114. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27115. #endif
  27116. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27117. #endif
  27118. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27119. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  27120. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27121. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27122. /**
  27123. Scans a directory for plugins, and adds them to a KnownPluginList.
  27124. To use one of these, create it and call scanNextFile() repeatedly, until
  27125. it returns false.
  27126. */
  27127. class JUCE_API PluginDirectoryScanner
  27128. {
  27129. public:
  27130. /**
  27131. Creates a scanner.
  27132. @param listToAddResultsTo this will get the new types added to it.
  27133. @param formatToLookFor this is the type of format that you want to look for
  27134. @param directoriesToSearch the path to search
  27135. @param searchRecursively true to search recursively
  27136. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  27137. be used as a file to store the names of any plugins
  27138. that crash during initialisation. If there are
  27139. any plugins listed in it, then these will always
  27140. be scanned after all other possible files have
  27141. been tried - in this way, even if there's a few
  27142. dodgy plugins in your path, then a couple of rescans
  27143. will still manage to find all the proper plugins.
  27144. It's probably best to choose a file in the user's
  27145. application data directory (alongside your app's
  27146. settings file) for this. The file format it uses
  27147. is just a list of filenames of the modules that
  27148. failed.
  27149. */
  27150. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  27151. AudioPluginFormat& formatToLookFor,
  27152. FileSearchPath directoriesToSearch,
  27153. const bool searchRecursively,
  27154. const File& deadMansPedalFile);
  27155. /** Destructor. */
  27156. ~PluginDirectoryScanner();
  27157. /** Tries the next likely-looking file.
  27158. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  27159. re-tested if it's not already in the list, or if the file's modification
  27160. time has changed since the list was created. If dontRescanIfAlreadyInList is
  27161. false, the file will always be reloaded and tested.
  27162. Returns false when there are no more files to try.
  27163. */
  27164. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  27165. /** Returns the description of the plugin that will be scanned during the next
  27166. call to scanNextFile().
  27167. This is handy if you want to show the user which file is currently getting
  27168. scanned.
  27169. */
  27170. const String getNextPluginFileThatWillBeScanned() const throw();
  27171. /** Returns the estimated progress, between 0 and 1.
  27172. */
  27173. float getProgress() const { return progress; }
  27174. /** This returns a list of all the filenames of things that looked like being
  27175. a plugin file, but which failed to open for some reason.
  27176. */
  27177. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  27178. juce_UseDebuggingNewOperator
  27179. private:
  27180. KnownPluginList& list;
  27181. AudioPluginFormat& format;
  27182. StringArray filesOrIdentifiersToScan;
  27183. File deadMansPedalFile;
  27184. StringArray failedFiles;
  27185. int nextIndex;
  27186. float progress;
  27187. const StringArray getDeadMansPedalFile() throw();
  27188. void setDeadMansPedalFile (const StringArray& newContents) throw();
  27189. PluginDirectoryScanner (const PluginDirectoryScanner&);
  27190. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  27191. };
  27192. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27193. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  27194. #endif
  27195. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27196. /********* Start of inlined file: juce_PluginListComponent.h *********/
  27197. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27198. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27199. /********* Start of inlined file: juce_ListBox.h *********/
  27200. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  27201. #define __JUCE_LISTBOX_JUCEHEADER__
  27202. class ListViewport;
  27203. /**
  27204. A subclass of this is used to drive a ListBox.
  27205. @see ListBox
  27206. */
  27207. class JUCE_API ListBoxModel
  27208. {
  27209. public:
  27210. /** Destructor. */
  27211. virtual ~ListBoxModel() {}
  27212. /** This has to return the number of items in the list.
  27213. @see ListBox::getNumRows()
  27214. */
  27215. virtual int getNumRows() = 0;
  27216. /** This method must be implemented to draw a row of the list.
  27217. */
  27218. virtual void paintListBoxItem (int rowNumber,
  27219. Graphics& g,
  27220. int width, int height,
  27221. bool rowIsSelected) = 0;
  27222. /** This is used to create or update a custom component to go in a row of the list.
  27223. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  27224. and handle mouse clicks with listBoxItemClicked().
  27225. This method will be called whenever a custom component might need to be updated - e.g.
  27226. when the table is changed, or TableListBox::updateContent() is called.
  27227. If you don't need a custom component for the specified row, then return 0.
  27228. If you do want a custom component, and the existingComponentToUpdate is null, then
  27229. this method must create a suitable new component and return it.
  27230. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  27231. by this method. In this case, the method must either update it to make sure it's correctly representing
  27232. the given row (which may be different from the one that the component was created for), or it can
  27233. delete this component and return a new one.
  27234. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  27235. */
  27236. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  27237. Component* existingComponentToUpdate);
  27238. /** This can be overridden to react to the user clicking on a row.
  27239. @see listBoxItemDoubleClicked
  27240. */
  27241. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  27242. /** This can be overridden to react to the user double-clicking on a row.
  27243. @see listBoxItemClicked
  27244. */
  27245. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  27246. /** This can be overridden to react to the user double-clicking on a part of the list where
  27247. there are no rows.
  27248. @see listBoxItemClicked
  27249. */
  27250. virtual void backgroundClicked();
  27251. /** Override this to be informed when rows are selected or deselected.
  27252. This will be called whenever a row is selected or deselected. If a range of
  27253. rows is selected all at once, this will just be called once for that event.
  27254. @param lastRowSelected the last row that the user selected. If no
  27255. rows are currently selected, this may be -1.
  27256. */
  27257. virtual void selectedRowsChanged (int lastRowSelected);
  27258. /** Override this to be informed when the delete key is pressed.
  27259. If no rows are selected when they press the key, this won't be called.
  27260. @param lastRowSelected the last row that had been selected when they pressed the
  27261. key - if there are multiple selections, this might not be
  27262. very useful
  27263. */
  27264. virtual void deleteKeyPressed (int lastRowSelected);
  27265. /** Override this to be informed when the return key is pressed.
  27266. If no rows are selected when they press the key, this won't be called.
  27267. @param lastRowSelected the last row that had been selected when they pressed the
  27268. key - if there are multiple selections, this might not be
  27269. very useful
  27270. */
  27271. virtual void returnKeyPressed (int lastRowSelected);
  27272. /** Override this to be informed when the list is scrolled.
  27273. This might be caused by the user moving the scrollbar, or by programmatic changes
  27274. to the list position.
  27275. */
  27276. virtual void listWasScrolled();
  27277. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  27278. If this returns a non-empty name then when the user drags a row, the listbox will
  27279. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  27280. a drag-and-drop operation, using this string as the source description, with the listbox
  27281. itself as the source component.
  27282. @see DragAndDropContainer::startDragging
  27283. */
  27284. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  27285. };
  27286. /**
  27287. A list of items that can be scrolled vertically.
  27288. To create a list, you'll need to create a subclass of ListBoxModel. This can
  27289. either paint each row of the list and respond to events via callbacks, or for
  27290. more specialised tasks, it can supply a custom component to fill each row.
  27291. @see ComboBox, TableListBox
  27292. */
  27293. class JUCE_API ListBox : public Component,
  27294. public SettableTooltipClient
  27295. {
  27296. public:
  27297. /** Creates a ListBox.
  27298. The model pointer passed-in can be null, in which case you can set it later
  27299. with setModel().
  27300. */
  27301. ListBox (const String& componentName,
  27302. ListBoxModel* const model);
  27303. /** Destructor. */
  27304. ~ListBox();
  27305. /** Changes the current data model to display. */
  27306. void setModel (ListBoxModel* const newModel);
  27307. /** Returns the current list model. */
  27308. ListBoxModel* getModel() const throw() { return model; }
  27309. /** Causes the list to refresh its content.
  27310. Call this when the number of rows in the list changes, or if you want it
  27311. to call refreshComponentForRow() on all the row components.
  27312. Be careful not to call it from a different thread, though, as it's not
  27313. thread-safe.
  27314. */
  27315. void updateContent();
  27316. /** Turns on multiple-selection of rows.
  27317. By default this is disabled.
  27318. When your row component gets clicked you'll need to call the
  27319. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  27320. clicked and to get it to do the appropriate selection based on whether
  27321. the ctrl/shift keys are held down.
  27322. */
  27323. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  27324. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  27325. This function is here primarily for the ComboBox class to use, but might be
  27326. useful for some other purpose too.
  27327. */
  27328. void setMouseMoveSelectsRows (bool shouldSelect);
  27329. /** Selects a row.
  27330. If the row is already selected, this won't do anything.
  27331. @param rowNumber the row to select
  27332. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  27333. the selected row is off-screen, it'll scroll to make
  27334. sure that row is on-screen
  27335. @param deselectOthersFirst if true and there are multiple selections, these will
  27336. first be deselected before this item is selected
  27337. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  27338. deselectAllRows, selectRangeOfRows
  27339. */
  27340. void selectRow (const int rowNumber,
  27341. bool dontScrollToShowThisRow = false,
  27342. bool deselectOthersFirst = true);
  27343. /** Selects a set of rows.
  27344. This will add these rows to the current selection, so you might need to
  27345. clear the current selection first with deselectAllRows()
  27346. @param firstRow the first row to select (inclusive)
  27347. @param lastRow the last row to select (inclusive)
  27348. */
  27349. void selectRangeOfRows (int firstRow,
  27350. int lastRow);
  27351. /** Deselects a row.
  27352. If it's not currently selected, this will do nothing.
  27353. @see selectRow, deselectAllRows
  27354. */
  27355. void deselectRow (const int rowNumber);
  27356. /** Deselects any currently selected rows.
  27357. @see deselectRow
  27358. */
  27359. void deselectAllRows();
  27360. /** Selects or deselects a row.
  27361. If the row's currently selected, this deselects it, and vice-versa.
  27362. */
  27363. void flipRowSelection (const int rowNumber);
  27364. /** Returns a sparse set indicating the rows that are currently selected.
  27365. @see setSelectedRows
  27366. */
  27367. const SparseSet<int> getSelectedRows() const;
  27368. /** Sets the rows that should be selected, based on an explicit set of ranges.
  27369. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  27370. method will be called. If it's false, no notification will be sent to the model.
  27371. @see getSelectedRows
  27372. */
  27373. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  27374. const bool sendNotificationEventToModel = true);
  27375. /** Checks whether a row is selected.
  27376. */
  27377. bool isRowSelected (const int rowNumber) const;
  27378. /** Returns the number of rows that are currently selected.
  27379. @see getSelectedRow, isRowSelected, getLastRowSelected
  27380. */
  27381. int getNumSelectedRows() const;
  27382. /** Returns the row number of a selected row.
  27383. This will return the row number of the Nth selected row. The row numbers returned will
  27384. be sorted in order from low to high.
  27385. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  27386. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  27387. selected
  27388. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  27389. */
  27390. int getSelectedRow (const int index = 0) const;
  27391. /** Returns the last row that the user selected.
  27392. This isn't the same as the highest row number that is currently selected - if the user
  27393. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  27394. If nothing is selected, it will return -1.
  27395. */
  27396. int getLastRowSelected() const;
  27397. /** Multiply-selects rows based on the modifier keys.
  27398. If no modifier keys are down, this will select the given row and
  27399. deselect any others.
  27400. If the ctrl (or command on the Mac) key is down, it'll flip the
  27401. state of the selected row.
  27402. If the shift key is down, it'll select up to the given row from the
  27403. last row selected.
  27404. @see selectRow
  27405. */
  27406. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  27407. const ModifierKeys& modifiers);
  27408. /** Scrolls the list to a particular position.
  27409. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  27410. 1.0 scrolls to the bottom.
  27411. If the total number of rows all fit onto the screen at once, then this
  27412. method won't do anything.
  27413. @see getVerticalPosition
  27414. */
  27415. void setVerticalPosition (const double newProportion);
  27416. /** Returns the current vertical position as a proportion of the total.
  27417. This can be used in conjunction with setVerticalPosition() to save and restore
  27418. the list's position. It returns a value in the range 0 to 1.
  27419. @see setVerticalPosition
  27420. */
  27421. double getVerticalPosition() const;
  27422. /** Scrolls if necessary to make sure that a particular row is visible.
  27423. */
  27424. void scrollToEnsureRowIsOnscreen (const int row);
  27425. /** Returns a pointer to the scrollbar.
  27426. (Unlikely to be useful for most people).
  27427. */
  27428. ScrollBar* getVerticalScrollBar() const throw();
  27429. /** Returns a pointer to the scrollbar.
  27430. (Unlikely to be useful for most people).
  27431. */
  27432. ScrollBar* getHorizontalScrollBar() const throw();
  27433. /** Finds the row index that contains a given x,y position.
  27434. The position is relative to the ListBox's top-left.
  27435. If no row exists at this position, the method will return -1.
  27436. @see getComponentForRowNumber
  27437. */
  27438. int getRowContainingPosition (const int x, const int y) const throw();
  27439. /** Finds a row index that would be the most suitable place to insert a new
  27440. item for a given position.
  27441. This is useful when the user is e.g. dragging and dropping onto the listbox,
  27442. because it lets you easily choose the best position to insert the item that
  27443. they drop, based on where they drop it.
  27444. If the position is out of range, this will return -1. If the position is
  27445. beyond the end of the list, it will return getNumRows() to indicate the end
  27446. of the list.
  27447. @see getComponentForRowNumber
  27448. */
  27449. int getInsertionIndexForPosition (const int x, const int y) const throw();
  27450. /** Returns the position of one of the rows, relative to the top-left of
  27451. the listbox.
  27452. This may be off-screen, and the range of the row number that is passed-in is
  27453. not checked to see if it's a valid row.
  27454. */
  27455. const Rectangle getRowPosition (const int rowNumber,
  27456. const bool relativeToComponentTopLeft) const throw();
  27457. /** Finds the row component for a given row in the list.
  27458. The component returned will have been created using createRowComponent().
  27459. If the component for this row is off-screen or if the row is out-of-range,
  27460. this will return 0.
  27461. @see getRowContainingPosition
  27462. */
  27463. Component* getComponentForRowNumber (const int rowNumber) const throw();
  27464. /** Returns the row number that the given component represents.
  27465. If the component isn't one of the list's rows, this will return -1.
  27466. */
  27467. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  27468. /** Returns the width of a row (which may be less than the width of this component
  27469. if there's a scrollbar).
  27470. */
  27471. int getVisibleRowWidth() const throw();
  27472. /** Sets the height of each row in the list.
  27473. The default height is 22 pixels.
  27474. @see getRowHeight
  27475. */
  27476. void setRowHeight (const int newHeight);
  27477. /** Returns the height of a row in the list.
  27478. @see setRowHeight
  27479. */
  27480. int getRowHeight() const throw() { return rowHeight; }
  27481. /** Returns the number of rows actually visible.
  27482. This is the number of whole rows which will fit on-screen, so the value might
  27483. be more than the actual number of rows in the list.
  27484. */
  27485. int getNumRowsOnScreen() const throw();
  27486. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27487. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27488. methods.
  27489. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27490. */
  27491. enum ColourIds
  27492. {
  27493. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  27494. Make this transparent if you don't want the background to be filled. */
  27495. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  27496. Make this transparent to not have an outline. */
  27497. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  27498. };
  27499. /** Sets the thickness of a border that will be drawn around the box.
  27500. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  27501. @see outlineColourId
  27502. */
  27503. void setOutlineThickness (const int outlineThickness);
  27504. /** Returns the thickness of outline that will be drawn around the listbox.
  27505. @see setOutlineColour
  27506. */
  27507. int getOutlineThickness() const throw() { return outlineThickness; }
  27508. /** Sets a component that the list should use as a header.
  27509. This will position the given component at the top of the list, maintaining the
  27510. height of the component passed-in, but rescaling it horizontally to match the
  27511. width of the items in the listbox.
  27512. The component will be deleted when setHeaderComponent() is called with a
  27513. different component, or when the listbox is deleted.
  27514. */
  27515. void setHeaderComponent (Component* const newHeaderComponent);
  27516. /** Changes the width of the rows in the list.
  27517. This can be used to make the list's row components wider than the list itself - the
  27518. width of the rows will be either the width of the list or this value, whichever is
  27519. greater, and if the rows become wider than the list, a horizontal scrollbar will
  27520. appear.
  27521. The default value for this is 0, which means that the rows will always
  27522. be the same width as the list.
  27523. */
  27524. void setMinimumContentWidth (const int newMinimumWidth);
  27525. /** Returns the space currently available for the row items, taking into account
  27526. borders, scrollbars, etc.
  27527. */
  27528. int getVisibleContentWidth() const throw();
  27529. /** Repaints one of the rows.
  27530. This is a lightweight alternative to calling updateContent, and just causes a
  27531. repaint of the row's area.
  27532. */
  27533. void repaintRow (const int rowNumber) throw();
  27534. /** This fairly obscure method creates an image that just shows the currently
  27535. selected row components.
  27536. It's a handy method for doing drag-and-drop, as it can be passed to the
  27537. DragAndDropContainer for use as the drag image.
  27538. Note that it will make the row components temporarily invisible, so if you're
  27539. using custom components this could affect them if they're sensitive to that
  27540. sort of thing.
  27541. @see Component::createComponentSnapshot
  27542. */
  27543. Image* createSnapshotOfSelectedRows();
  27544. /** Returns the viewport that this ListBox uses.
  27545. You may need to use this to change parameters such as whether scrollbars
  27546. are shown, etc.
  27547. */
  27548. Viewport* getViewport() const throw();
  27549. /** @internal */
  27550. bool keyPressed (const KeyPress& key);
  27551. /** @internal */
  27552. bool keyStateChanged (const bool isKeyDown);
  27553. /** @internal */
  27554. void paint (Graphics& g);
  27555. /** @internal */
  27556. void paintOverChildren (Graphics& g);
  27557. /** @internal */
  27558. void resized();
  27559. /** @internal */
  27560. void visibilityChanged();
  27561. /** @internal */
  27562. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27563. /** @internal */
  27564. void mouseMove (const MouseEvent&);
  27565. /** @internal */
  27566. void mouseExit (const MouseEvent&);
  27567. /** @internal */
  27568. void mouseUp (const MouseEvent&);
  27569. /** @internal */
  27570. void colourChanged();
  27571. juce_UseDebuggingNewOperator
  27572. private:
  27573. friend class ListViewport;
  27574. friend class TableListBox;
  27575. ListBoxModel* model;
  27576. ListViewport* viewport;
  27577. Component* headerComponent;
  27578. int totalItems, rowHeight, minimumRowWidth;
  27579. int outlineThickness;
  27580. int lastMouseX, lastMouseY, lastRowSelected;
  27581. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  27582. SparseSet <int> selected;
  27583. void selectRowInternal (const int rowNumber,
  27584. bool dontScrollToShowThisRow,
  27585. bool deselectOthersFirst,
  27586. bool isMouseClick);
  27587. ListBox (const ListBox&);
  27588. const ListBox& operator= (const ListBox&);
  27589. };
  27590. #endif // __JUCE_LISTBOX_JUCEHEADER__
  27591. /********* End of inlined file: juce_ListBox.h *********/
  27592. /********* Start of inlined file: juce_TextButton.h *********/
  27593. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  27594. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  27595. /**
  27596. A button that uses the standard lozenge-shaped background with a line of
  27597. text on it.
  27598. @see Button, DrawableButton
  27599. */
  27600. class JUCE_API TextButton : public Button
  27601. {
  27602. public:
  27603. /** Creates a TextButton.
  27604. @param buttonName the text to put in the button (the component's name is also
  27605. initially set to this string, but these can be changed later
  27606. using the setName() and setButtonText() methods)
  27607. @param toolTip an optional string to use as a toolip
  27608. @see Button
  27609. */
  27610. TextButton (const String& buttonName,
  27611. const String& toolTip = String::empty);
  27612. /** Destructor. */
  27613. ~TextButton();
  27614. /** A set of colour IDs to use to change the colour of various aspects of the button.
  27615. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27616. methods.
  27617. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27618. */
  27619. enum ColourIds
  27620. {
  27621. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  27622. 'off'). The look-and-feel class might re-interpret this to add
  27623. effects, etc. */
  27624. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  27625. 'on'). The look-and-feel class might re-interpret this to add
  27626. effects, etc. */
  27627. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  27628. };
  27629. /** Resizes the button to fit neatly around its current text.
  27630. If newHeight is >= 0, the button's height will be changed to this
  27631. value. If it's less than zero, its height will be unaffected.
  27632. */
  27633. void changeWidthToFitText (const int newHeight = -1);
  27634. /** This can be overridden to use different fonts than the default one.
  27635. Note that you'll need to set the font's size appropriately, too.
  27636. */
  27637. virtual const Font getFont();
  27638. juce_UseDebuggingNewOperator
  27639. protected:
  27640. /** @internal */
  27641. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  27642. /** @internal */
  27643. void colourChanged();
  27644. private:
  27645. TextButton (const TextButton&);
  27646. const TextButton& operator= (const TextButton&);
  27647. };
  27648. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  27649. /********* End of inlined file: juce_TextButton.h *********/
  27650. /**
  27651. A component displaying a list of plugins, with options to scan for them,
  27652. add, remove and sort them.
  27653. */
  27654. class JUCE_API PluginListComponent : public Component,
  27655. public ListBoxModel,
  27656. public ChangeListener,
  27657. public ButtonListener,
  27658. public Timer
  27659. {
  27660. public:
  27661. /**
  27662. Creates the list component.
  27663. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  27664. The properties file, if supplied, is used to store the user's last search paths.
  27665. */
  27666. PluginListComponent (KnownPluginList& listToRepresent,
  27667. const File& deadMansPedalFile,
  27668. PropertiesFile* const propertiesToUse);
  27669. /** Destructor. */
  27670. ~PluginListComponent();
  27671. /** @internal */
  27672. void resized();
  27673. /** @internal */
  27674. bool isInterestedInFileDrag (const StringArray& files);
  27675. /** @internal */
  27676. void filesDropped (const StringArray& files, int, int);
  27677. /** @internal */
  27678. int getNumRows();
  27679. /** @internal */
  27680. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  27681. /** @internal */
  27682. void deleteKeyPressed (int lastRowSelected);
  27683. /** @internal */
  27684. void buttonClicked (Button* b);
  27685. /** @internal */
  27686. void changeListenerCallback (void*);
  27687. /** @internal */
  27688. void timerCallback();
  27689. juce_UseDebuggingNewOperator
  27690. private:
  27691. KnownPluginList& list;
  27692. File deadMansPedalFile;
  27693. ListBox* listBox;
  27694. TextButton* optionsButton;
  27695. PropertiesFile* propertiesToUse;
  27696. int typeToScan;
  27697. void scanFor (AudioPluginFormat* format);
  27698. PluginListComponent (const PluginListComponent&);
  27699. const PluginListComponent& operator= (const PluginListComponent&);
  27700. };
  27701. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27702. /********* End of inlined file: juce_PluginListComponent.h *********/
  27703. #endif
  27704. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27705. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  27706. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27707. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27708. /********* Start of inlined file: juce_AudioFormat.h *********/
  27709. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27710. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  27711. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  27712. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27713. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27714. /**
  27715. Writes samples to an audio file stream.
  27716. A subclass that writes a specific type of audio format will be created by
  27717. an AudioFormat object.
  27718. After creating one of these with the AudioFormat::createWriterFor() method
  27719. you can call its write() method to store the samples, and then delete it.
  27720. @see AudioFormat, AudioFormatReader
  27721. */
  27722. class JUCE_API AudioFormatWriter
  27723. {
  27724. protected:
  27725. /** Creates an AudioFormatWriter object.
  27726. @param destStream the stream to write to - this will be deleted
  27727. by this object when it is no longer needed
  27728. @param formatName the description that will be returned by the getFormatName()
  27729. method
  27730. @param sampleRate the sample rate to use - the base class just stores
  27731. this value, it doesn't do anything with it
  27732. @param numberOfChannels the number of channels to write - the base class just stores
  27733. this value, it doesn't do anything with it
  27734. @param bitsPerSample the bit depth of the stream - the base class just stores
  27735. this value, it doesn't do anything with it
  27736. */
  27737. AudioFormatWriter (OutputStream* const destStream,
  27738. const String& formatName,
  27739. const double sampleRate,
  27740. const unsigned int numberOfChannels,
  27741. const unsigned int bitsPerSample);
  27742. public:
  27743. /** Destructor. */
  27744. virtual ~AudioFormatWriter();
  27745. /** Returns a description of what type of format this is.
  27746. E.g. "AIFF file"
  27747. */
  27748. const String getFormatName() const throw() { return formatName; }
  27749. /** Writes a set of samples to the audio stream.
  27750. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27751. can use AudioSampleBuffer::writeToAudioWriter().
  27752. @param samplesToWrite an array of arrays containing the sample data for
  27753. each channel to write. This is a zero-terminated
  27754. array of arrays, and can contain a different number
  27755. of channels than the actual stream uses, and the
  27756. writer should do its best to cope with this.
  27757. If the format is fixed-point, each channel will be formatted
  27758. as an array of signed integers using the full 32-bit
  27759. range -0x80000000 to 0x7fffffff, regardless of the source's
  27760. bit-depth. If it is a floating-point format, you should treat
  27761. the arrays as arrays of floats, and just cast it to an (int**)
  27762. to pass it into the method.
  27763. @param numSamples the number of samples to write
  27764. */
  27765. virtual bool write (const int** samplesToWrite,
  27766. int numSamples) = 0;
  27767. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27768. the output.
  27769. This will take care of any floating-point conversion that's required to convert
  27770. between the two formats. It won't deal with sample-rate conversion, though.
  27771. If numSamplesToRead < 0, it will write the entire length of the reader.
  27772. @returns false if it can't read or write properly during the operation
  27773. */
  27774. bool writeFromAudioReader (AudioFormatReader& reader,
  27775. int64 startSample,
  27776. int64 numSamplesToRead);
  27777. /** Reads some samples from an AudioSource, and writes these to the output.
  27778. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27779. @param source the source to read from
  27780. @param numSamplesToRead total number of samples to read and write
  27781. @param samplesPerBlock the maximum number of samples to fetch from the source
  27782. @returns false if it can't read or write properly during the operation
  27783. */
  27784. bool writeFromAudioSource (AudioSource& source,
  27785. int numSamplesToRead,
  27786. const int samplesPerBlock = 2048);
  27787. /** Returns the sample rate being used. */
  27788. double getSampleRate() const throw() { return sampleRate; }
  27789. /** Returns the number of channels being written. */
  27790. int getNumChannels() const throw() { return numChannels; }
  27791. /** Returns the bit-depth of the data being written. */
  27792. int getBitsPerSample() const throw() { return bitsPerSample; }
  27793. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27794. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27795. juce_UseDebuggingNewOperator
  27796. protected:
  27797. /** The sample rate of the stream. */
  27798. double sampleRate;
  27799. /** The number of channels being written to the stream. */
  27800. unsigned int numChannels;
  27801. /** The bit depth of the file. */
  27802. unsigned int bitsPerSample;
  27803. /** True if it's a floating-point format, false if it's fixed-point. */
  27804. bool usesFloatingPointData;
  27805. /** The output stream for Use by subclasses. */
  27806. OutputStream* output;
  27807. private:
  27808. String formatName;
  27809. };
  27810. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27811. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  27812. /**
  27813. Subclasses of AudioFormat are used to read and write different audio
  27814. file formats.
  27815. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27816. */
  27817. class JUCE_API AudioFormat
  27818. {
  27819. public:
  27820. /** Destructor. */
  27821. virtual ~AudioFormat();
  27822. /** Returns the name of this format.
  27823. e.g. "WAV file" or "AIFF file"
  27824. */
  27825. const String& getFormatName() const;
  27826. /** Returns all the file extensions that might apply to a file of this format.
  27827. The first item will be the one that's preferred when creating a new file.
  27828. So for a wav file this might just return ".wav"; for an AIFF file it might
  27829. return two items, ".aif" and ".aiff"
  27830. */
  27831. const StringArray& getFileExtensions() const;
  27832. /** Returns true if this the given file can be read by this format.
  27833. Subclasses shouldn't do too much work here, just check the extension or
  27834. file type. The base class implementation just checks the file's extension
  27835. against one of the ones that was registered in the constructor.
  27836. */
  27837. virtual bool canHandleFile (const File& fileToTest);
  27838. /** Returns a set of sample rates that the format can read and write. */
  27839. virtual const Array <int> getPossibleSampleRates() = 0;
  27840. /** Returns a set of bit depths that the format can read and write. */
  27841. virtual const Array <int> getPossibleBitDepths() = 0;
  27842. /** Returns true if the format can do 2-channel audio. */
  27843. virtual bool canDoStereo() = 0;
  27844. /** Returns true if the format can do 1-channel audio. */
  27845. virtual bool canDoMono() = 0;
  27846. /** Returns true if the format uses compressed data. */
  27847. virtual bool isCompressed();
  27848. /** Returns a list of different qualities that can be used when writing.
  27849. Non-compressed formats will just return an empty array, but for something
  27850. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27851. When calling createWriterFor(), an index from this array is passed in to
  27852. tell the format which option is required.
  27853. */
  27854. virtual const StringArray getQualityOptions();
  27855. /** Tries to create an object that can read from a stream containing audio
  27856. data in this format.
  27857. The reader object that is returned can be used to read from the stream, and
  27858. should then be deleted by the caller.
  27859. @param sourceStream the stream to read from - the AudioFormatReader object
  27860. that is returned will delete this stream when it no longer
  27861. needs it.
  27862. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27863. should delete the stream object that was passed-in. (If a valid
  27864. reader is returned, it will always be in charge of deleting the
  27865. stream, so this parameter is ignored)
  27866. @see AudioFormatReader
  27867. */
  27868. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27869. const bool deleteStreamIfOpeningFails) = 0;
  27870. /** Tries to create an object that can write to a stream with this audio format.
  27871. The writer object that is returned can be used to write to the stream, and
  27872. should then be deleted by the caller.
  27873. If the stream can't be created for some reason (e.g. the parameters passed in
  27874. here aren't suitable), this will return 0.
  27875. @param streamToWriteTo the stream that the data will go to - this will be
  27876. deleted by the AudioFormatWriter object when it's no longer
  27877. needed. If no AudioFormatWriter can be created by this method,
  27878. the stream will NOT be deleted, so that the caller can re-use it
  27879. to try to open a different format, etc
  27880. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27881. returned by getPossibleSampleRates()
  27882. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27883. the choice will depend on the results of canDoMono() and
  27884. canDoStereo()
  27885. @param bitsPerSample the bits per sample to use - this must be one of the values
  27886. returned by getPossibleBitDepths()
  27887. @param metadataValues a set of metadata values that the writer should try to write
  27888. to the stream. Exactly what these are depends on the format,
  27889. and the subclass doesn't actually have to do anything with
  27890. them if it doesn't want to. Have a look at the specific format
  27891. implementation classes to see possible values that can be
  27892. used
  27893. @param qualityOptionIndex the index of one of compression qualities returned by the
  27894. getQualityOptions() method. If there aren't any quality options
  27895. for this format, just pass 0 in this parameter, as it'll be
  27896. ignored
  27897. @see AudioFormatWriter
  27898. */
  27899. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27900. double sampleRateToUse,
  27901. unsigned int numberOfChannels,
  27902. int bitsPerSample,
  27903. const StringPairArray& metadataValues,
  27904. int qualityOptionIndex) = 0;
  27905. protected:
  27906. /** Creates an AudioFormat object.
  27907. @param formatName this sets the value that will be returned by getFormatName()
  27908. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27909. be returned by getFileExtension()
  27910. */
  27911. AudioFormat (const String& formatName,
  27912. const tchar** const fileExtensions);
  27913. private:
  27914. String formatName;
  27915. StringArray fileExtensions;
  27916. };
  27917. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27918. /********* End of inlined file: juce_AudioFormat.h *********/
  27919. /**
  27920. Reads and Writes AIFF format audio files.
  27921. @see AudioFormat
  27922. */
  27923. class JUCE_API AiffAudioFormat : public AudioFormat
  27924. {
  27925. public:
  27926. /** Creates an format object. */
  27927. AiffAudioFormat();
  27928. /** Destructor. */
  27929. ~AiffAudioFormat();
  27930. const Array <int> getPossibleSampleRates();
  27931. const Array <int> getPossibleBitDepths();
  27932. bool canDoStereo();
  27933. bool canDoMono();
  27934. #if JUCE_MAC
  27935. bool canHandleFile (const File& fileToTest);
  27936. #endif
  27937. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27938. const bool deleteStreamIfOpeningFails);
  27939. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27940. double sampleRateToUse,
  27941. unsigned int numberOfChannels,
  27942. int bitsPerSample,
  27943. const StringPairArray& metadataValues,
  27944. int qualityOptionIndex);
  27945. juce_UseDebuggingNewOperator
  27946. };
  27947. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27948. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  27949. #endif
  27950. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27951. #endif
  27952. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27953. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27954. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27955. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27956. /**
  27957. A class for keeping a list of available audio formats, and for deciding which
  27958. one to use to open a given file.
  27959. You can either use this class as a singleton object, or create instances of it
  27960. yourself. Once created, use its registerFormat() method to tell it which
  27961. formats it should use.
  27962. @see AudioFormat
  27963. */
  27964. class JUCE_API AudioFormatManager
  27965. {
  27966. public:
  27967. /** Creates an empty format manager.
  27968. Before it'll be any use, you'll need to call registerFormat() with all the
  27969. formats you want it to be able to recognise.
  27970. */
  27971. AudioFormatManager();
  27972. /** Destructor. */
  27973. ~AudioFormatManager();
  27974. juce_DeclareSingleton (AudioFormatManager, false);
  27975. /** Adds a format to the manager's list of available file types.
  27976. The object passed-in will be deleted by this object, so don't keep a pointer
  27977. to it!
  27978. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27979. return this one when called.
  27980. */
  27981. void registerFormat (AudioFormat* newFormat,
  27982. const bool makeThisTheDefaultFormat);
  27983. /** Handy method to make it easy to register the formats that come with Juce.
  27984. Currently, this will add WAV and AIFF to the list.
  27985. */
  27986. void registerBasicFormats();
  27987. /** Clears the list of known formats. */
  27988. void clearFormats();
  27989. /** Returns the number of currently registered file formats. */
  27990. int getNumKnownFormats() const;
  27991. /** Returns one of the registered file formats. */
  27992. AudioFormat* getKnownFormat (const int index) const;
  27993. /** Looks for which of the known formats is listed as being for a given file
  27994. extension.
  27995. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27996. */
  27997. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27998. /** Returns the format which has been set as the default one.
  27999. You can set a format as being the default when it is registered. It's useful
  28000. when you want to write to a file, because the best format may change between
  28001. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28002. If none has been set as the default, this method will just return the first
  28003. one in the list.
  28004. */
  28005. AudioFormat* getDefaultFormat() const;
  28006. /** Returns a set of wildcards for file-matching that contains the extensions for
  28007. all known formats.
  28008. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28009. */
  28010. const String getWildcardForAllFormats() const;
  28011. /** Searches through the known formats to try to create a suitable reader for
  28012. this file.
  28013. If none of the registered formats can open the file, it'll return 0. If it
  28014. returns a reader, it's the caller's responsibility to delete the reader.
  28015. */
  28016. AudioFormatReader* createReaderFor (const File& audioFile);
  28017. /** Searches through the known formats to try to create a suitable reader for
  28018. this stream.
  28019. The stream object that is passed-in will be deleted by this method or by the
  28020. reader that is returned, so the caller should not keep any references to it.
  28021. The stream that is passed-in must be capable of being repositioned so
  28022. that all the formats can have a go at opening it.
  28023. If none of the registered formats can open the stream, it'll return 0. If it
  28024. returns a reader, it's the caller's responsibility to delete the reader.
  28025. */
  28026. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28027. juce_UseDebuggingNewOperator
  28028. private:
  28029. VoidArray knownFormats;
  28030. int defaultFormatIndex;
  28031. };
  28032. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28033. /********* End of inlined file: juce_AudioFormatManager.h *********/
  28034. #endif
  28035. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28036. #endif
  28037. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28038. #endif
  28039. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28040. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  28041. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28042. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28043. /**
  28044. This class is used to wrap an AudioFormatReader and only read from a
  28045. subsection of the file.
  28046. So if you have a reader which can read a 1000 sample file, you could wrap it
  28047. in one of these to only access, e.g. samples 100 to 200, and any samples
  28048. outside that will come back as 0. Accessing sample 0 from this reader will
  28049. actually read the first sample from the other's subsection, which might
  28050. be at a non-zero position.
  28051. @see AudioFormatReader
  28052. */
  28053. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28054. {
  28055. public:
  28056. /** Creates a AudioSubsectionReader for a given data source.
  28057. @param sourceReader the source reader from which we'll be taking data
  28058. @param subsectionStartSample the sample within the source reader which will be
  28059. mapped onto sample 0 for this reader.
  28060. @param subsectionLength the number of samples from the source that will
  28061. make up the subsection. If this reader is asked for
  28062. any samples beyond this region, it will return zero.
  28063. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28064. this object is deleted.
  28065. */
  28066. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  28067. const int64 subsectionStartSample,
  28068. const int64 subsectionLength,
  28069. const bool deleteSourceWhenDeleted);
  28070. /** Destructor. */
  28071. ~AudioSubsectionReader();
  28072. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28073. int64 startSampleInFile, int numSamples);
  28074. void readMaxLevels (int64 startSample,
  28075. int64 numSamples,
  28076. float& lowestLeft,
  28077. float& highestLeft,
  28078. float& lowestRight,
  28079. float& highestRight);
  28080. juce_UseDebuggingNewOperator
  28081. private:
  28082. AudioFormatReader* const source;
  28083. int64 startSample, length;
  28084. const bool deleteSourceWhenDeleted;
  28085. AudioSubsectionReader (const AudioSubsectionReader&);
  28086. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  28087. };
  28088. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28089. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  28090. #endif
  28091. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28092. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  28093. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28094. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28095. class AudioThumbnailCache;
  28096. /**
  28097. Makes it easy to quickly draw scaled views of the waveform shape of an
  28098. audio file.
  28099. To use this class, just create an AudioThumbNail class for the file you want
  28100. to draw, call setSource to tell it which file or resource to use, then call
  28101. drawChannel() to draw it.
  28102. The class will asynchronously scan the wavefile to create its scaled-down view,
  28103. so you should make your UI repaint itself as this data comes in. To do this, the
  28104. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28105. listeners should repaint themselves.
  28106. The thumbnail stores an internal low-res version of the wave data, and this can
  28107. be loaded and saved to avoid having to scan the file again.
  28108. @see AudioThumbnailCache
  28109. */
  28110. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  28111. public TimeSliceClient,
  28112. private Timer
  28113. {
  28114. public:
  28115. /** Creates an audio thumbnail.
  28116. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28117. of the audio data, this is the scale at which it should be done. (This
  28118. number is the number of original samples that will be averaged for each
  28119. low-res sample)
  28120. @param formatManagerToUse the audio format manager that is used to open the file
  28121. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28122. thread and storage that is used to by the thumbnail, and the cache
  28123. object can be shared between multiple thumbnails
  28124. */
  28125. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  28126. AudioFormatManager& formatManagerToUse,
  28127. AudioThumbnailCache& cacheToUse);
  28128. /** Destructor. */
  28129. ~AudioThumbnail();
  28130. /** Specifies the file or stream that contains the audio file.
  28131. For a file, just call
  28132. @code
  28133. setSource (new FileInputSource (file))
  28134. @endcode
  28135. You can pass a zero in here to clear the thumbnail.
  28136. The source that is passed in will be deleted by this object when it is no
  28137. longer needed
  28138. */
  28139. void setSource (InputSource* const newSource);
  28140. /** Reloads the low res thumbnail data from an input stream.
  28141. The thumb will automatically attempt to reload itself from its
  28142. AudioThumbnailCache.
  28143. */
  28144. void loadFrom (InputStream& input);
  28145. /** Saves the low res thumbnail data to an output stream.
  28146. The thumb will automatically attempt to save itself to its
  28147. AudioThumbnailCache after it finishes scanning the wave file.
  28148. */
  28149. void saveTo (OutputStream& output) const;
  28150. /** Returns the number of channels in the file.
  28151. */
  28152. int getNumChannels() const throw();
  28153. /** Returns the length of the audio file, in seconds.
  28154. */
  28155. double getTotalLength() const throw();
  28156. /** Renders the waveform shape for a channel.
  28157. The waveform will be drawn within the specified rectangle, where startTime
  28158. and endTime specify the times within the audio file that should be positioned
  28159. at the left and right edges of the rectangle.
  28160. The waveform will be scaled vertically so that a full-volume sample will fill
  28161. the rectangle vertically, but you can also specify an extra vertical scale factor
  28162. with the verticalZoomFactor parameter.
  28163. */
  28164. void drawChannel (Graphics& g,
  28165. int x, int y, int w, int h,
  28166. double startTimeSeconds,
  28167. double endTimeSeconds,
  28168. int channelNum,
  28169. const float verticalZoomFactor);
  28170. /** Returns true if the low res preview is fully generated.
  28171. */
  28172. bool isFullyLoaded() const throw();
  28173. /** @internal */
  28174. bool useTimeSlice();
  28175. /** @internal */
  28176. void timerCallback();
  28177. juce_UseDebuggingNewOperator
  28178. private:
  28179. AudioFormatManager& formatManagerToUse;
  28180. AudioThumbnailCache& cache;
  28181. InputSource* source;
  28182. CriticalSection readerLock;
  28183. AudioFormatReader* reader;
  28184. MemoryBlock data, cachedLevels;
  28185. int orginalSamplesPerThumbnailSample;
  28186. int numChannelsCached, numSamplesCached;
  28187. double cachedStart, cachedTimePerPixel;
  28188. bool cacheNeedsRefilling;
  28189. void clear();
  28190. AudioFormatReader* createReader() const;
  28191. void generateSection (AudioFormatReader& reader,
  28192. int64 startSample,
  28193. int numSamples);
  28194. char* getChannelData (int channel) const;
  28195. void refillCache (const int numSamples,
  28196. double startTime,
  28197. const double timePerPixel);
  28198. friend class AudioThumbnailCache;
  28199. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  28200. bool initialiseFromAudioFile (AudioFormatReader& reader);
  28201. // returns true if more needs to be read
  28202. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  28203. };
  28204. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28205. /********* End of inlined file: juce_AudioThumbnail.h *********/
  28206. #endif
  28207. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28208. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  28209. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28210. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28211. struct ThumbnailCacheEntry;
  28212. /**
  28213. An instance of this class is used to manage multiple AudioThumbnail objects.
  28214. The cache runs a single background thread that is shared by all the thumbnails
  28215. that need it, and it maintains a set of low-res previews in memory, to avoid
  28216. having to re-scan audio files too often.
  28217. @see AudioThumbnail
  28218. */
  28219. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28220. {
  28221. public:
  28222. /** Creates a cache object.
  28223. The maxNumThumbsToStore parameter lets you specify how many previews should
  28224. be kept in memory at once.
  28225. */
  28226. AudioThumbnailCache (const int maxNumThumbsToStore);
  28227. /** Destructor. */
  28228. ~AudioThumbnailCache();
  28229. /** Clears out any stored thumbnails.
  28230. */
  28231. void clear();
  28232. /** Reloads the specified thumb if this cache contains the appropriate stored
  28233. data.
  28234. This is called automatically by the AudioThumbnail class, so you shouldn't
  28235. normally need to call it directly.
  28236. */
  28237. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  28238. /** Stores the cachable data from the specified thumb in this cache.
  28239. This is called automatically by the AudioThumbnail class, so you shouldn't
  28240. normally need to call it directly.
  28241. */
  28242. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  28243. juce_UseDebuggingNewOperator
  28244. private:
  28245. OwnedArray <ThumbnailCacheEntry> thumbs;
  28246. int maxNumThumbsToStore;
  28247. friend class AudioThumbnail;
  28248. void addThumbnail (AudioThumbnail* const thumb);
  28249. void removeThumbnail (AudioThumbnail* const thumb);
  28250. };
  28251. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28252. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  28253. #endif
  28254. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28255. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  28256. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28257. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28258. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28259. /**
  28260. Reads and writes the lossless-compression FLAC audio format.
  28261. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28262. and make sure your include search path and library search path are set up to find
  28263. the FLAC header files and static libraries.
  28264. @see AudioFormat
  28265. */
  28266. class JUCE_API FlacAudioFormat : public AudioFormat
  28267. {
  28268. public:
  28269. FlacAudioFormat();
  28270. ~FlacAudioFormat();
  28271. const Array <int> getPossibleSampleRates();
  28272. const Array <int> getPossibleBitDepths();
  28273. bool canDoStereo();
  28274. bool canDoMono();
  28275. bool isCompressed();
  28276. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28277. const bool deleteStreamIfOpeningFails);
  28278. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28279. double sampleRateToUse,
  28280. unsigned int numberOfChannels,
  28281. int bitsPerSample,
  28282. const StringPairArray& metadataValues,
  28283. int qualityOptionIndex);
  28284. juce_UseDebuggingNewOperator
  28285. };
  28286. #endif
  28287. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28288. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  28289. #endif
  28290. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28291. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  28292. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28293. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28294. /**
  28295. Reads and Writes WAV format audio files.
  28296. @see AudioFormat
  28297. */
  28298. class JUCE_API WavAudioFormat : public AudioFormat
  28299. {
  28300. public:
  28301. /** Creates a format object. */
  28302. WavAudioFormat();
  28303. /** Destructor. */
  28304. ~WavAudioFormat();
  28305. /** Metadata property name used by wav readers and writers for adding
  28306. a BWAV chunk to the file.
  28307. @see AudioFormatReader::metadataValues, createWriterFor
  28308. */
  28309. static const tchar* const bwavDescription;
  28310. /** Metadata property name used by wav readers and writers for adding
  28311. a BWAV chunk to the file.
  28312. @see AudioFormatReader::metadataValues, createWriterFor
  28313. */
  28314. static const tchar* const bwavOriginator;
  28315. /** Metadata property name used by wav readers and writers for adding
  28316. a BWAV chunk to the file.
  28317. @see AudioFormatReader::metadataValues, createWriterFor
  28318. */
  28319. static const tchar* const bwavOriginatorRef;
  28320. /** Metadata property name used by wav readers and writers for adding
  28321. a BWAV chunk to the file.
  28322. Date format is: yyyy-mm-dd
  28323. @see AudioFormatReader::metadataValues, createWriterFor
  28324. */
  28325. static const tchar* const bwavOriginationDate;
  28326. /** Metadata property name used by wav readers and writers for adding
  28327. a BWAV chunk to the file.
  28328. Time format is: hh-mm-ss
  28329. @see AudioFormatReader::metadataValues, createWriterFor
  28330. */
  28331. static const tchar* const bwavOriginationTime;
  28332. /** Metadata property name used by wav readers and writers for adding
  28333. a BWAV chunk to the file.
  28334. This is the number of samples from the start of an edit that the
  28335. file is supposed to begin at. Seems like an obvious mistake to
  28336. only allow a file to occur in an edit once, but that's the way
  28337. it is..
  28338. @see AudioFormatReader::metadataValues, createWriterFor
  28339. */
  28340. static const tchar* const bwavTimeReference;
  28341. /** Metadata property name used by wav readers and writers for adding
  28342. a BWAV chunk to the file.
  28343. This is a
  28344. @see AudioFormatReader::metadataValues, createWriterFor
  28345. */
  28346. static const tchar* const bwavCodingHistory;
  28347. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28348. This just makes it easier than using the property names directly, and it
  28349. fills out the time and date in the right format.
  28350. */
  28351. static const StringPairArray createBWAVMetadata (const String& description,
  28352. const String& originator,
  28353. const String& originatorRef,
  28354. const Time& dateAndTime,
  28355. const int64 timeReferenceSamples,
  28356. const String& codingHistory);
  28357. const Array <int> getPossibleSampleRates();
  28358. const Array <int> getPossibleBitDepths();
  28359. bool canDoStereo();
  28360. bool canDoMono();
  28361. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28362. const bool deleteStreamIfOpeningFails);
  28363. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28364. double sampleRateToUse,
  28365. unsigned int numberOfChannels,
  28366. int bitsPerSample,
  28367. const StringPairArray& metadataValues,
  28368. int qualityOptionIndex);
  28369. /** Utility function to replace the metadata in a wav file with a new set of values.
  28370. If possible, this cheats by overwriting just the metadata region of the file, rather
  28371. than by copying the whole file again.
  28372. */
  28373. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28374. juce_UseDebuggingNewOperator
  28375. };
  28376. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28377. /********* End of inlined file: juce_WavAudioFormat.h *********/
  28378. #endif
  28379. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28380. /********* Start of inlined file: juce_AudioCDReader.h *********/
  28381. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28382. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28383. #if JUCE_USE_CDREADER
  28384. #if JUCE_MAC
  28385. #endif
  28386. /**
  28387. A type of AudioFormatReader that reads from an audio CD.
  28388. One of these can be used to read a CD as if it's one big audio stream. Use the
  28389. getPositionOfTrackStart() method to find where the individual tracks are
  28390. within the stream.
  28391. @see AudioFormatReader
  28392. */
  28393. class JUCE_API AudioCDReader : public AudioFormatReader
  28394. {
  28395. public:
  28396. /** Returns a list of names of Audio CDs currently available for reading.
  28397. If there's a CD drive but no CD in it, this might return an empty list, or
  28398. possibly a device that can be opened but which has no tracks, depending
  28399. on the platform.
  28400. @see createReaderForCD
  28401. */
  28402. static const StringArray getAvailableCDNames();
  28403. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28404. @param index the index of one of the available CDs - use getAvailableCDNames()
  28405. to find out how many there are.
  28406. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28407. caller will be responsible for deleting the object returned.
  28408. */
  28409. static AudioCDReader* createReaderForCD (const int index);
  28410. /** Destructor. */
  28411. ~AudioCDReader();
  28412. /** Implementation of the AudioFormatReader method. */
  28413. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28414. int64 startSampleInFile, int numSamples);
  28415. /** Checks whether the CD has been removed from the drive.
  28416. */
  28417. bool isCDStillPresent() const;
  28418. /** Returns the total number of tracks (audio + data).
  28419. */
  28420. int getNumTracks() const;
  28421. /** Finds the sample offset of the start of a track.
  28422. @param trackNum the track number, where 0 is the first track.
  28423. */
  28424. int getPositionOfTrackStart (int trackNum) const;
  28425. /** Returns true if a given track is an audio track.
  28426. @param trackNum the track number, where 0 is the first track.
  28427. */
  28428. bool isTrackAudio (int trackNum) const;
  28429. /** Refreshes the object's table of contents.
  28430. If the disc has been ejected and a different one put in since this
  28431. object was created, this will cause it to update its idea of how many tracks
  28432. there are, etc.
  28433. */
  28434. void refreshTrackLengths();
  28435. /** Enables scanning for indexes within tracks.
  28436. @see getLastIndex
  28437. */
  28438. void enableIndexScanning (bool enabled);
  28439. /** Returns the index number found during the last read() call.
  28440. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28441. Then when the read() method is called, if it comes across an index within that
  28442. block, the index number is stored and returned by this method.
  28443. Some devices might not support indexes, of course.
  28444. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28445. @see enableIndexScanning
  28446. */
  28447. int getLastIndex() const;
  28448. /** Scans a track to find the position of any indexes within it.
  28449. @param trackNumber the track to look in, where 0 is the first track on the disc
  28450. @returns an array of sample positions of any index points found (not including
  28451. the index that marks the start of the track)
  28452. */
  28453. const Array <int> findIndexesInTrack (const int trackNumber);
  28454. /** Returns the CDDB id number for the CD.
  28455. It's not a great way of identifying a disc, but it's traditional.
  28456. */
  28457. int getCDDBId();
  28458. /** Tries to eject the disk.
  28459. Of course this might not be possible, if some other process is using it.
  28460. */
  28461. void ejectDisk();
  28462. juce_UseDebuggingNewOperator
  28463. private:
  28464. #if JUCE_MAC
  28465. File volumeDir;
  28466. OwnedArray<File> tracks;
  28467. Array <int> trackStartSamples;
  28468. int currentReaderTrack;
  28469. AudioFormatReader* reader;
  28470. AudioCDReader (const File& volume);
  28471. public:
  28472. static int compareElements (const File* const, const File* const) throw();
  28473. private:
  28474. #elif JUCE_WINDOWS
  28475. int numTracks;
  28476. int trackStarts[100];
  28477. bool audioTracks [100];
  28478. void* handle;
  28479. bool indexingEnabled;
  28480. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28481. MemoryBlock buffer;
  28482. AudioCDReader (void* handle);
  28483. int getIndexAt (int samplePos);
  28484. #elif JUCE_LINUX
  28485. AudioCDReader();
  28486. #endif
  28487. AudioCDReader (const AudioCDReader&);
  28488. const AudioCDReader& operator= (const AudioCDReader&);
  28489. };
  28490. #endif
  28491. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28492. /********* End of inlined file: juce_AudioCDReader.h *********/
  28493. #endif
  28494. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28495. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  28496. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28497. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28498. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28499. /**
  28500. Reads and writes the Ogg-Vorbis audio format.
  28501. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28502. and make sure your include search path and library search path are set up to find
  28503. the Vorbis and Ogg header files and static libraries.
  28504. @see AudioFormat,
  28505. */
  28506. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28507. {
  28508. public:
  28509. OggVorbisAudioFormat();
  28510. ~OggVorbisAudioFormat();
  28511. const Array <int> getPossibleSampleRates();
  28512. const Array <int> getPossibleBitDepths();
  28513. bool canDoStereo();
  28514. bool canDoMono();
  28515. bool isCompressed();
  28516. const StringArray getQualityOptions();
  28517. /** Tries to estimate the quality level of an ogg file based on its size.
  28518. If it can't read the file for some reason, this will just return 1 (medium quality),
  28519. otherwise it will return the approximate quality setting that would have been used
  28520. to create the file.
  28521. @see getQualityOptions
  28522. */
  28523. int estimateOggFileQuality (const File& source);
  28524. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28525. const bool deleteStreamIfOpeningFails);
  28526. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28527. double sampleRateToUse,
  28528. unsigned int numberOfChannels,
  28529. int bitsPerSample,
  28530. const StringPairArray& metadataValues,
  28531. int qualityOptionIndex);
  28532. juce_UseDebuggingNewOperator
  28533. };
  28534. #endif
  28535. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28536. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  28537. #endif
  28538. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28539. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  28540. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28541. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28542. #if JUCE_QUICKTIME
  28543. /**
  28544. Uses QuickTime to read the audio track a movie or media file.
  28545. As well as QuickTime movies, this should also manage to open other audio
  28546. files that quicktime can understand, like mp3, m4a, etc.
  28547. @see AudioFormat
  28548. */
  28549. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28550. {
  28551. public:
  28552. /** Creates a format object. */
  28553. QuickTimeAudioFormat();
  28554. /** Destructor. */
  28555. ~QuickTimeAudioFormat();
  28556. const Array <int> getPossibleSampleRates();
  28557. const Array <int> getPossibleBitDepths();
  28558. bool canDoStereo();
  28559. bool canDoMono();
  28560. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28561. const bool deleteStreamIfOpeningFails);
  28562. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28563. double sampleRateToUse,
  28564. unsigned int numberOfChannels,
  28565. int bitsPerSample,
  28566. const StringPairArray& metadataValues,
  28567. int qualityOptionIndex);
  28568. juce_UseDebuggingNewOperator
  28569. };
  28570. #endif
  28571. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28572. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  28573. #endif
  28574. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28575. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  28576. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28577. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28578. #if JUCE_USE_CDBURNER
  28579. /**
  28580. */
  28581. class AudioCDBurner
  28582. {
  28583. public:
  28584. /** Returns a list of available optical drives.
  28585. Use openDevice() to open one of the items from this list.
  28586. */
  28587. static const StringArray findAvailableDevices();
  28588. /** Tries to open one of the optical drives.
  28589. The deviceIndex is an index into the array returned by findAvailableDevices().
  28590. */
  28591. static AudioCDBurner* openDevice (const int deviceIndex);
  28592. /** Destructor. */
  28593. ~AudioCDBurner();
  28594. /** Returns true if there's a writable disk in the drive.
  28595. */
  28596. bool isDiskPresent() const;
  28597. /** Returns the number of free blocks on the disk.
  28598. There are 75 blocks per second, at 44100Hz.
  28599. */
  28600. int getNumAvailableAudioBlocks() const;
  28601. /** Adds a track to be written.
  28602. The source passed-in here will be kept by this object, and it will
  28603. be used and deleted at some point in the future, either during the
  28604. burn() method or when this AudioCDBurner object is deleted. Your caller
  28605. method shouldn't keep a reference to it or use it again after passing
  28606. it in here.
  28607. */
  28608. bool addAudioTrack (AudioSource* source, int numSamples);
  28609. /**
  28610. Return true to cancel the current burn operation
  28611. */
  28612. class BurnProgressListener
  28613. {
  28614. public:
  28615. BurnProgressListener() throw() {}
  28616. virtual ~BurnProgressListener() {}
  28617. /** Called at intervals to report on the progress of the AudioCDBurner.
  28618. To cancel the burn, return true from this.
  28619. */
  28620. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28621. };
  28622. const String burn (BurnProgressListener* listener,
  28623. const bool ejectDiscAfterwards,
  28624. const bool peformFakeBurnForTesting);
  28625. juce_UseDebuggingNewOperator
  28626. private:
  28627. AudioCDBurner (const int deviceIndex);
  28628. void* internal;
  28629. };
  28630. #endif
  28631. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28632. /********* End of inlined file: juce_AudioCDBurner.h *********/
  28633. #endif
  28634. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28635. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  28636. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28637. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28638. /********* Start of inlined file: juce_ActionListenerList.h *********/
  28639. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28640. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28641. /**
  28642. A set of ActionListeners.
  28643. Listeners can be added and removed from the list, and messages can be
  28644. broadcast to all the listeners.
  28645. @see ActionListener, ActionBroadcaster
  28646. */
  28647. class JUCE_API ActionListenerList : public MessageListener
  28648. {
  28649. public:
  28650. /** Creates an empty list. */
  28651. ActionListenerList() throw();
  28652. /** Destructor. */
  28653. ~ActionListenerList() throw();
  28654. /** Adds a listener to the list.
  28655. (Trying to add a listener that's already on the list will have no effect).
  28656. */
  28657. void addActionListener (ActionListener* const listener) throw();
  28658. /** Removes a listener from the list.
  28659. If the listener isn't on the list, this won't have any effect.
  28660. */
  28661. void removeActionListener (ActionListener* const listener) throw();
  28662. /** Removes all listeners from the list. */
  28663. void removeAllActionListeners() throw();
  28664. /** Broadcasts a message to all the registered listeners.
  28665. This sends the message asynchronously.
  28666. If a listener is on the list when this method is called but is removed from
  28667. the list before the message arrives, it won't receive the message. Similarly
  28668. listeners that are added to the list after the message is sent but before it
  28669. arrives won't get the message either.
  28670. */
  28671. void sendActionMessage (const String& message) const;
  28672. /** @internal */
  28673. void handleMessage (const Message&);
  28674. juce_UseDebuggingNewOperator
  28675. private:
  28676. SortedSet <void*> actionListeners_;
  28677. CriticalSection actionListenerLock_;
  28678. ActionListenerList (const ActionListenerList&);
  28679. const ActionListenerList& operator= (const ActionListenerList&);
  28680. };
  28681. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28682. /********* End of inlined file: juce_ActionListenerList.h *********/
  28683. /** Manages a list of ActionListeners, and can send them messages.
  28684. To quickly add methods to your class that can add/remove action
  28685. listeners and broadcast to them, you can derive from this.
  28686. @see ActionListenerList, ActionListener
  28687. */
  28688. class JUCE_API ActionBroadcaster
  28689. {
  28690. public:
  28691. /** Creates an ActionBroadcaster. */
  28692. ActionBroadcaster() throw();
  28693. /** Destructor. */
  28694. virtual ~ActionBroadcaster();
  28695. /** Adds a listener to the list.
  28696. (Trying to add a listener that's already on the list will have no effect).
  28697. */
  28698. void addActionListener (ActionListener* const listener);
  28699. /** Removes a listener from the list.
  28700. If the listener isn't on the list, this won't have any effect.
  28701. */
  28702. void removeActionListener (ActionListener* const listener);
  28703. /** Removes all listeners from the list. */
  28704. void removeAllActionListeners();
  28705. /** Broadcasts a message to all the registered listeners.
  28706. @see ActionListenerList::sendActionMessage
  28707. */
  28708. void sendActionMessage (const String& message) const;
  28709. private:
  28710. ActionListenerList actionListenerList;
  28711. ActionBroadcaster (const ActionBroadcaster&);
  28712. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  28713. };
  28714. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28715. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  28716. #endif
  28717. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  28718. #endif
  28719. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28720. #endif
  28721. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  28722. #endif
  28723. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28724. /********* Start of inlined file: juce_CallbackMessage.h *********/
  28725. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28726. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28727. /**
  28728. A message that calls a custom function when it gets delivered.
  28729. You can use this class to fire off actions that you want to be performed later
  28730. on the message thread.
  28731. Unlike other Message objects, these don't get sent to a MessageListener, you
  28732. just call the post() method to send them, and when they arrive, your
  28733. messageCallback() method will automatically be invoked.
  28734. @see MessageListener, MessageManager, ActionListener, ChangeListener
  28735. */
  28736. class JUCE_API CallbackMessage : public Message
  28737. {
  28738. public:
  28739. CallbackMessage() throw();
  28740. /** Destructor. */
  28741. ~CallbackMessage() throw();
  28742. /** Called when the message is delivered.
  28743. You should implement this method and make it do whatever action you want
  28744. to perform.
  28745. Note that like all other messages, this object will be deleted immediately
  28746. after this method has been invoked.
  28747. */
  28748. virtual void messageCallback() = 0;
  28749. /** Instead of sending this message to a MessageListener, just call this method
  28750. to post it to the event queue.
  28751. After you've called this, this object will belong to the MessageManager,
  28752. which will delete it later. So make sure you don't delete the object yourself,
  28753. call post() more than once, or call post() on a stack-based obect!
  28754. */
  28755. void post();
  28756. juce_UseDebuggingNewOperator
  28757. private:
  28758. CallbackMessage (const CallbackMessage&);
  28759. const CallbackMessage& operator= (const CallbackMessage&);
  28760. };
  28761. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28762. /********* End of inlined file: juce_CallbackMessage.h *********/
  28763. #endif
  28764. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  28765. #endif
  28766. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  28767. #endif
  28768. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  28769. #endif
  28770. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28771. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  28772. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28773. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28774. class InterprocessConnectionServer;
  28775. /**
  28776. Manages a simple two-way messaging connection to another process, using either
  28777. a socket or a named pipe as the transport medium.
  28778. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  28779. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  28780. and incoming messages will result in a callback via the messageReceived()
  28781. method.
  28782. To open a pipe and wait for another client to connect to it, use the createPipe()
  28783. method.
  28784. To act as a socket server and create connections for one or more client, see the
  28785. InterprocessConnectionServer class.
  28786. @see InterprocessConnectionServer, Socket, NamedPipe
  28787. */
  28788. class JUCE_API InterprocessConnection : public Thread,
  28789. private MessageListener
  28790. {
  28791. public:
  28792. /** Creates a connection.
  28793. Connections are created manually, connecting them with the connectToSocket()
  28794. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  28795. when a client wants to connect.
  28796. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  28797. connectionLost() and messageReceived() methods will
  28798. always be made using the message thread; if false,
  28799. these will be called immediately on the connection's
  28800. own thread.
  28801. @param magicMessageHeaderNumber a magic number to use in the header to check the
  28802. validity of the data blocks being sent and received. This
  28803. can be any number, but the sender and receiver must obviously
  28804. use matching values or they won't recognise each other.
  28805. */
  28806. InterprocessConnection (const bool callbacksOnMessageThread = true,
  28807. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  28808. /** Destructor. */
  28809. ~InterprocessConnection();
  28810. /** Tries to connect this object to a socket.
  28811. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  28812. object waiting to receive client connections on this port number.
  28813. @param hostName the host computer, either a network address or name
  28814. @param portNumber the socket port number to try to connect to
  28815. @param timeOutMillisecs how long to keep trying before giving up
  28816. @returns true if the connection is established successfully
  28817. @see Socket
  28818. */
  28819. bool connectToSocket (const String& hostName,
  28820. const int portNumber,
  28821. const int timeOutMillisecs);
  28822. /** Tries to connect the object to an existing named pipe.
  28823. For this to work, another process on the same computer must already have opened
  28824. an InterprocessConnection object and used createPipe() to create a pipe for this
  28825. to connect to.
  28826. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28827. @returns true if it connects successfully.
  28828. @see createPipe, NamedPipe
  28829. */
  28830. bool connectToPipe (const String& pipeName,
  28831. const int pipeReceiveMessageTimeoutMs = -1);
  28832. /** Tries to create a new pipe for other processes to connect to.
  28833. This creates a pipe with the given name, so that other processes can use
  28834. connectToPipe() to connect to the other end.
  28835. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28836. If another process is already using this pipe, this will fail and return false.
  28837. */
  28838. bool createPipe (const String& pipeName,
  28839. const int pipeReceiveMessageTimeoutMs = -1);
  28840. /** Disconnects and closes any currently-open sockets or pipes. */
  28841. void disconnect();
  28842. /** True if a socket or pipe is currently active. */
  28843. bool isConnected() const;
  28844. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  28845. StreamingSocket* getSocket() const throw() { return socket; }
  28846. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  28847. NamedPipe* getPipe() const throw() { return pipe; }
  28848. /** Returns the name of the machine at the other end of this connection.
  28849. This will return an empty string if the other machine isn't known for
  28850. some reason.
  28851. */
  28852. const String getConnectedHostName() const;
  28853. /** Tries to send a message to the other end of this connection.
  28854. This will fail if it's not connected, or if there's some kind of write error. If
  28855. it succeeds, the connection object at the other end will receive the message by
  28856. a callback to its messageReceived() method.
  28857. @see messageReceived
  28858. */
  28859. bool sendMessage (const MemoryBlock& message);
  28860. /** Called when the connection is first connected.
  28861. If the connection was created with the callbacksOnMessageThread flag set, then
  28862. this will be called on the message thread; otherwise it will be called on a server
  28863. thread.
  28864. */
  28865. virtual void connectionMade() = 0;
  28866. /** Called when the connection is broken.
  28867. If the connection was created with the callbacksOnMessageThread flag set, then
  28868. this will be called on the message thread; otherwise it will be called on a server
  28869. thread.
  28870. */
  28871. virtual void connectionLost() = 0;
  28872. /** Called when a message arrives.
  28873. When the object at the other end of this connection sends us a message with sendMessage(),
  28874. this callback is used to deliver it to us.
  28875. If the connection was created with the callbacksOnMessageThread flag set, then
  28876. this will be called on the message thread; otherwise it will be called on a server
  28877. thread.
  28878. @see sendMessage
  28879. */
  28880. virtual void messageReceived (const MemoryBlock& message) = 0;
  28881. juce_UseDebuggingNewOperator
  28882. private:
  28883. CriticalSection pipeAndSocketLock;
  28884. StreamingSocket* socket;
  28885. NamedPipe* pipe;
  28886. bool callbackConnectionState;
  28887. const bool useMessageThread;
  28888. const uint32 magicMessageHeader;
  28889. int pipeReceiveMessageTimeout;
  28890. friend class InterprocessConnectionServer;
  28891. void initialiseWithSocket (StreamingSocket* const socket_);
  28892. void initialiseWithPipe (NamedPipe* const pipe_);
  28893. void handleMessage (const Message& message);
  28894. void connectionMadeInt();
  28895. void connectionLostInt();
  28896. void deliverDataInt (const MemoryBlock& data);
  28897. bool readNextMessageInt();
  28898. void run();
  28899. InterprocessConnection (const InterprocessConnection&);
  28900. const InterprocessConnection& operator= (const InterprocessConnection&);
  28901. };
  28902. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28903. /********* End of inlined file: juce_InterprocessConnection.h *********/
  28904. #endif
  28905. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28906. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  28907. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28908. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28909. /**
  28910. An object that waits for client sockets to connect to a port on this host, and
  28911. creates InterprocessConnection objects for each one.
  28912. To use this, create a class derived from it which implements the createConnectionObject()
  28913. method, so that it creates suitable connection objects for each client that tries
  28914. to connect.
  28915. @see InterprocessConnection
  28916. */
  28917. class JUCE_API InterprocessConnectionServer : private Thread
  28918. {
  28919. public:
  28920. /** Creates an uninitialised server object.
  28921. */
  28922. InterprocessConnectionServer();
  28923. /** Destructor. */
  28924. ~InterprocessConnectionServer();
  28925. /** Starts an internal thread which listens on the given port number.
  28926. While this is running, in another process tries to connect with the
  28927. InterprocessConnection::connectToSocket() method, this object will call
  28928. createConnectionObject() to create a connection to that client.
  28929. Use stop() to stop the thread running.
  28930. @see createConnectionObject, stop
  28931. */
  28932. bool beginWaitingForSocket (const int portNumber);
  28933. /** Terminates the listener thread, if it's active.
  28934. @see beginWaitingForSocket
  28935. */
  28936. void stop();
  28937. protected:
  28938. /** Creates a suitable connection object for a client process that wants to
  28939. connect to this one.
  28940. This will be called by the listener thread when a client process tries
  28941. to connect, and must return a new InterprocessConnection object that will
  28942. then run as this end of the connection.
  28943. @see InterprocessConnection
  28944. */
  28945. virtual InterprocessConnection* createConnectionObject() = 0;
  28946. public:
  28947. juce_UseDebuggingNewOperator
  28948. private:
  28949. StreamingSocket* volatile socket;
  28950. void run();
  28951. InterprocessConnectionServer (const InterprocessConnectionServer&);
  28952. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  28953. };
  28954. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28955. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  28956. #endif
  28957. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  28958. #endif
  28959. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  28960. #endif
  28961. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28962. /********* Start of inlined file: juce_MessageManager.h *********/
  28963. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28964. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28965. class Component;
  28966. class MessageManagerLock;
  28967. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  28968. */
  28969. typedef void* (MessageCallbackFunction) (void* userData);
  28970. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  28971. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  28972. */
  28973. class JUCE_API MessageManager
  28974. {
  28975. public:
  28976. /** Returns the global instance of the MessageManager. */
  28977. static MessageManager* getInstance() throw();
  28978. /** Runs the event dispatch loop until a stop message is posted.
  28979. This method is only intended to be run by the application's startup routine,
  28980. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  28981. @see stopDispatchLoop
  28982. */
  28983. void runDispatchLoop();
  28984. /** Sends a signal that the dispatch loop should terminate.
  28985. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  28986. will be interrupted and will return.
  28987. @see runDispatchLoop
  28988. */
  28989. void stopDispatchLoop();
  28990. /** Returns true if the stopDispatchLoop() method has been called.
  28991. */
  28992. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  28993. /** Synchronously dispatches messages until a given time has elapsed.
  28994. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  28995. otherwise returns true.
  28996. */
  28997. bool runDispatchLoopUntil (int millisecondsToRunFor);
  28998. /** Calls a function using the message-thread.
  28999. This can be used by any thread to cause this function to be called-back
  29000. by the message thread. If it's the message-thread that's calling this method,
  29001. then the function will just be called; if another thread is calling, a message
  29002. will be posted to the queue, and this method will block until that message
  29003. is delivered, the function is called, and the result is returned.
  29004. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  29005. thread has a critical section locked, which an unrelated message callback then tries to lock
  29006. before the message thread gets round to processing this callback.
  29007. @param callback the function to call - its signature must be @code
  29008. void* myCallbackFunction (void*) @endcode
  29009. @param userData a user-defined pointer that will be passed to the function that gets called
  29010. @returns the value that the callback function returns.
  29011. @see MessageManagerLock
  29012. */
  29013. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  29014. void* userData);
  29015. /** Returns true if the caller-thread is the message thread. */
  29016. bool isThisTheMessageThread() const throw();
  29017. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  29018. (Best to ignore this method unless you really know what you're doing..)
  29019. @see getCurrentMessageThread
  29020. */
  29021. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  29022. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  29023. (Best to ignore this method unless you really know what you're doing..)
  29024. @see setCurrentMessageThread
  29025. */
  29026. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  29027. /** Returns true if the caller thread has currenltly got the message manager locked.
  29028. see the MessageManagerLock class for more info about this.
  29029. This will be true if the caller is the message thread, because that automatically
  29030. gains a lock while a message is being dispatched.
  29031. */
  29032. bool currentThreadHasLockedMessageManager() const throw();
  29033. /** Sends a message to all other JUCE applications that are running.
  29034. @param messageText the string that will be passed to the actionListenerCallback()
  29035. method of the broadcast listeners in the other app.
  29036. @see registerBroadcastListener, ActionListener
  29037. */
  29038. static void broadcastMessage (const String& messageText) throw();
  29039. /** Registers a listener to get told about broadcast messages.
  29040. The actionListenerCallback() callback's string parameter
  29041. is the message passed into broadcastMessage().
  29042. @see broadcastMessage
  29043. */
  29044. void registerBroadcastListener (ActionListener* listener) throw();
  29045. /** Deregisters a broadcast listener. */
  29046. void deregisterBroadcastListener (ActionListener* listener) throw();
  29047. /** @internal */
  29048. void deliverMessage (void*);
  29049. /** @internal */
  29050. void deliverBroadcastMessage (const String&);
  29051. /** @internal */
  29052. ~MessageManager() throw();
  29053. juce_UseDebuggingNewOperator
  29054. private:
  29055. MessageManager() throw();
  29056. friend class MessageListener;
  29057. friend class ChangeBroadcaster;
  29058. friend class ActionBroadcaster;
  29059. friend class CallbackMessage;
  29060. static MessageManager* instance;
  29061. SortedSet<const MessageListener*> messageListeners;
  29062. ActionListenerList* broadcastListeners;
  29063. friend class JUCEApplication;
  29064. bool quitMessagePosted, quitMessageReceived;
  29065. Thread::ThreadID messageThreadId;
  29066. VoidArray modalComponents;
  29067. static void* exitModalLoopCallback (void*);
  29068. void postMessageToQueue (Message* const message);
  29069. void postCallbackMessage (Message* const message);
  29070. static void doPlatformSpecificInitialisation();
  29071. static void doPlatformSpecificShutdown();
  29072. friend class MessageManagerLock;
  29073. Thread::ThreadID volatile threadWithLock;
  29074. CriticalSection lockingLock;
  29075. MessageManager (const MessageManager&);
  29076. const MessageManager& operator= (const MessageManager&);
  29077. };
  29078. /** Used to make sure that the calling thread has exclusive access to the message loop.
  29079. Because it's not thread-safe to call any of the Component or other UI classes
  29080. from threads other than the message thread, one of these objects can be used to
  29081. lock the message loop and allow this to be done. The message thread will be
  29082. suspended for the lifetime of the MessageManagerLock object, so create one on
  29083. the stack like this: @code
  29084. void MyThread::run()
  29085. {
  29086. someData = 1234;
  29087. const MessageManagerLock mmLock;
  29088. // the event loop will now be locked so it's safe to make a few calls..
  29089. myComponent->setBounds (newBounds);
  29090. myComponent->repaint();
  29091. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  29092. }
  29093. @endcode
  29094. Obviously be careful not to create one of these and leave it lying around, or
  29095. your app will grind to a halt!
  29096. Another caveat is that using this in conjunction with other CriticalSections
  29097. can create lots of interesting ways of producing a deadlock! In particular, if
  29098. your message thread calls stopThread() for a thread that uses these locks,
  29099. you'll get an (occasional) deadlock..
  29100. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  29101. */
  29102. class JUCE_API MessageManagerLock
  29103. {
  29104. public:
  29105. /** Tries to acquire a lock on the message manager.
  29106. The constructor attempts to gain a lock on the message loop, and the lock will be
  29107. kept for the lifetime of this object.
  29108. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  29109. this method will keep checking whether the thread has been given the
  29110. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  29111. without gaining the lock. If you pass a thread, you must check whether the lock was
  29112. successful by calling lockWasGained(). If this is false, your thread is being told to
  29113. die, so you should take evasive action.
  29114. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  29115. careful when doing this, because it's very easy to deadlock if your message thread
  29116. attempts to call stopThread() on a thread just as that thread attempts to get the
  29117. message lock.
  29118. If the calling thread already has the lock, nothing will be done, so it's safe and
  29119. quick to use these locks recursively.
  29120. E.g.
  29121. @code
  29122. void run()
  29123. {
  29124. ...
  29125. while (! threadShouldExit())
  29126. {
  29127. MessageManagerLock mml (Thread::getCurrentThread());
  29128. if (! mml.lockWasGained())
  29129. return; // another thread is trying to kill us!
  29130. ..do some locked stuff here..
  29131. }
  29132. ..and now the MM is now unlocked..
  29133. }
  29134. @endcode
  29135. */
  29136. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  29137. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  29138. instead of a thread.
  29139. See the MessageManagerLock (Thread*) constructor for details on how this works.
  29140. */
  29141. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  29142. /** Releases the current thread's lock on the message manager.
  29143. Make sure this object is created and deleted by the same thread,
  29144. otherwise there are no guarantees what will happen!
  29145. */
  29146. ~MessageManagerLock() throw();
  29147. /** Returns true if the lock was successfully acquired.
  29148. (See the constructor that takes a Thread for more info).
  29149. */
  29150. bool lockWasGained() const throw() { return locked; }
  29151. private:
  29152. bool locked, needsUnlocking;
  29153. void* sharedEvents;
  29154. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  29155. };
  29156. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29157. /********* End of inlined file: juce_MessageManager.h *********/
  29158. #endif
  29159. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  29160. /********* Start of inlined file: juce_MultiTimer.h *********/
  29161. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  29162. #define __JUCE_MULTITIMER_JUCEHEADER__
  29163. /**
  29164. A type of timer class that can run multiple timers with different frequencies,
  29165. all of which share a single callback.
  29166. This class is very similar to the Timer class, but allows you run multiple
  29167. separate timers, where each one has a unique ID number. The methods in this
  29168. class are exactly equivalent to those in Timer, but with the addition of
  29169. this ID number.
  29170. To use it, you need to create a subclass of MultiTimer, implementing the
  29171. timerCallback() method. Then you can start timers with startTimer(), and
  29172. each time the callback is triggered, it passes in the ID of the timer that
  29173. caused it.
  29174. @see Timer
  29175. */
  29176. class JUCE_API MultiTimer
  29177. {
  29178. protected:
  29179. /** Creates a MultiTimer.
  29180. When created, no timers are running, so use startTimer() to start things off.
  29181. */
  29182. MultiTimer() throw();
  29183. /** Creates a copy of another timer.
  29184. Note that this timer will not contain any running timers, even if the one you're
  29185. copying from was running.
  29186. */
  29187. MultiTimer (const MultiTimer& other) throw();
  29188. public:
  29189. /** Destructor. */
  29190. virtual ~MultiTimer();
  29191. /** The user-defined callback routine that actually gets called by each of the
  29192. timers that are running.
  29193. It's perfectly ok to call startTimer() or stopTimer() from within this
  29194. callback to change the subsequent intervals.
  29195. */
  29196. virtual void timerCallback (const int timerId) = 0;
  29197. /** Starts a timer and sets the length of interval required.
  29198. If the timer is already started, this will reset it, so the
  29199. time between calling this method and the next timer callback
  29200. will not be less than the interval length passed in.
  29201. @param timerId a unique Id number that identifies the timer to
  29202. start. This is the id that will be passed back
  29203. to the timerCallback() method when this timer is
  29204. triggered
  29205. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  29206. rounded up to 1)
  29207. */
  29208. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  29209. /** Stops a timer.
  29210. If a timer has been started with the given ID number, it will be cancelled.
  29211. No more callbacks will be made for the specified timer after this method returns.
  29212. If this is called from a different thread, any callbacks that may
  29213. be currently executing may be allowed to finish before the method
  29214. returns.
  29215. */
  29216. void stopTimer (const int timerId) throw();
  29217. /** Checks whether a timer has been started for a specified ID.
  29218. @returns true if a timer with the given ID is running.
  29219. */
  29220. bool isTimerRunning (const int timerId) const throw();
  29221. /** Returns the interval for a specified timer ID.
  29222. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  29223. is running for the ID number specified.
  29224. */
  29225. int getTimerInterval (const int timerId) const throw();
  29226. private:
  29227. CriticalSection timerListLock;
  29228. VoidArray timers;
  29229. const MultiTimer& operator= (const MultiTimer&);
  29230. };
  29231. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  29232. /********* End of inlined file: juce_MultiTimer.h *********/
  29233. #endif
  29234. #ifndef __JUCE_TIMER_JUCEHEADER__
  29235. #endif
  29236. #ifndef __JUCE_COLOUR_JUCEHEADER__
  29237. #endif
  29238. #ifndef __JUCE_COLOURS_JUCEHEADER__
  29239. #endif
  29240. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  29241. #endif
  29242. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  29243. #endif
  29244. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29245. #endif
  29246. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29247. /********* Start of inlined file: juce_TextLayout.h *********/
  29248. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29249. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  29250. class Graphics;
  29251. /**
  29252. A laid-out arrangement of text.
  29253. You can add text in different fonts to a TextLayout object, then call its
  29254. layout() method to word-wrap it into lines. The layout can then be drawn
  29255. using a graphics context.
  29256. It's handy if you've got a message to display, because you can format it,
  29257. measure the extent of the layout, and then create a suitably-sized window
  29258. to show it in.
  29259. @see Font, Graphics::drawFittedText, GlyphArrangement
  29260. */
  29261. class JUCE_API TextLayout
  29262. {
  29263. public:
  29264. /** Creates an empty text layout.
  29265. Text can then be appended using the appendText() method.
  29266. */
  29267. TextLayout() throw();
  29268. /** Creates a copy of another layout object. */
  29269. TextLayout (const TextLayout& other) throw();
  29270. /** Creates a text layout from an initial string and font. */
  29271. TextLayout (const String& text, const Font& font) throw();
  29272. /** Destructor. */
  29273. ~TextLayout() throw();
  29274. /** Copies another layout onto this one. */
  29275. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  29276. /** Clears the layout, removing all its text. */
  29277. void clear() throw();
  29278. /** Adds a string to the end of the arrangement.
  29279. The string will be broken onto new lines wherever it contains
  29280. carriage-returns or linefeeds. After adding it, you can call layout()
  29281. to wrap long lines into a paragraph and justify it.
  29282. */
  29283. void appendText (const String& textToAppend,
  29284. const Font& fontToUse) throw();
  29285. /** Replaces all the text with a new string.
  29286. This is equivalent to calling clear() followed by appendText().
  29287. */
  29288. void setText (const String& newText,
  29289. const Font& fontToUse) throw();
  29290. /** Breaks the text up to form a paragraph with the given width.
  29291. @param maximumWidth any text wider than this will be split
  29292. across multiple lines
  29293. @param justification how the lines are to be laid-out horizontally
  29294. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29295. width that keeps all the lines of text at a
  29296. similar length - this is good when you're displaying
  29297. a short message and don't want it to get split
  29298. onto two lines with only a couple of words on
  29299. the second line, which looks untidy.
  29300. */
  29301. void layout (int maximumWidth,
  29302. const Justification& justification,
  29303. const bool attemptToBalanceLineLengths) throw();
  29304. /** Returns the overall width of the entire text layout. */
  29305. int getWidth() const throw();
  29306. /** Returns the overall height of the entire text layout. */
  29307. int getHeight() const throw();
  29308. /** Returns the total number of lines of text. */
  29309. int getNumLines() const throw() { return totalLines; }
  29310. /** Returns the width of a particular line of text.
  29311. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29312. */
  29313. int getLineWidth (const int lineNumber) const throw();
  29314. /** Renders the text at a specified position using a graphics context.
  29315. */
  29316. void draw (Graphics& g,
  29317. const int topLeftX,
  29318. const int topLeftY) const throw();
  29319. /** Renders the text within a specified rectangle using a graphics context.
  29320. The justification flags dictate how the block of text should be positioned
  29321. within the rectangle.
  29322. */
  29323. void drawWithin (Graphics& g,
  29324. int x, int y, int w, int h,
  29325. const Justification& layoutFlags) const throw();
  29326. juce_UseDebuggingNewOperator
  29327. private:
  29328. VoidArray tokens;
  29329. int totalLines;
  29330. };
  29331. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29332. /********* End of inlined file: juce_TextLayout.h *********/
  29333. #endif
  29334. #ifndef __JUCE_FONT_JUCEHEADER__
  29335. #endif
  29336. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29337. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  29338. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29339. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29340. /**
  29341. A glyph from a particular font, with a particular size, style,
  29342. typeface and position.
  29343. @see GlyphArrangement, Font
  29344. */
  29345. class JUCE_API PositionedGlyph
  29346. {
  29347. public:
  29348. /** Returns the character the glyph represents. */
  29349. juce_wchar getCharacter() const throw() { return character; }
  29350. /** Checks whether the glyph is actually empty. */
  29351. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  29352. /** Returns the position of the glyph's left-hand edge. */
  29353. float getLeft() const throw() { return x; }
  29354. /** Returns the position of the glyph's right-hand edge. */
  29355. float getRight() const throw() { return x + w; }
  29356. /** Returns the y position of the glyph's baseline. */
  29357. float getBaselineY() const throw() { return y; }
  29358. /** Returns the y position of the top of the glyph. */
  29359. float getTop() const throw() { return y - font.getAscent(); }
  29360. /** Returns the y position of the bottom of the glyph. */
  29361. float getBottom() const throw() { return y + font.getDescent(); }
  29362. /** Shifts the glyph's position by a relative amount. */
  29363. void moveBy (const float deltaX,
  29364. const float deltaY) throw();
  29365. /** Draws the glyph into a graphics context. */
  29366. void draw (const Graphics& g) const throw();
  29367. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  29368. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29369. /** Returns the path for this glyph.
  29370. @param path the glyph's outline will be appended to this path
  29371. */
  29372. void createPath (Path& path) const throw();
  29373. /** Checks to see if a point lies within this glyph. */
  29374. bool hitTest (float x, float y) const throw();
  29375. juce_UseDebuggingNewOperator
  29376. private:
  29377. friend class GlyphArrangement;
  29378. float x, y, w;
  29379. Font font;
  29380. juce_wchar character;
  29381. int glyph;
  29382. PositionedGlyph() throw();
  29383. };
  29384. /**
  29385. A set of glyphs, each with a position.
  29386. You can create a GlyphArrangement, text to it and then draw it onto a
  29387. graphics context. It's used internally by the text methods in the
  29388. Graphics class, but can be used directly if more control is needed.
  29389. @see Font, PositionedGlyph
  29390. */
  29391. class JUCE_API GlyphArrangement
  29392. {
  29393. public:
  29394. /** Creates an empty arrangement. */
  29395. GlyphArrangement() throw();
  29396. /** Takes a copy of another arrangement. */
  29397. GlyphArrangement (const GlyphArrangement& other) throw();
  29398. /** Copies another arrangement onto this one.
  29399. To add another arrangement without clearing this one, use addGlyphArrangement().
  29400. */
  29401. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  29402. /** Destructor. */
  29403. ~GlyphArrangement() throw();
  29404. /** Returns the total number of glyphs in the arrangement. */
  29405. int getNumGlyphs() const throw() { return glyphs.size(); }
  29406. /** Returns one of the glyphs from the arrangement.
  29407. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  29408. careful not to pass an out-of-range index here, as it
  29409. doesn't do any bounds-checking.
  29410. */
  29411. PositionedGlyph& getGlyph (const int index) const throw();
  29412. /** Clears all text from the arrangement and resets it.
  29413. */
  29414. void clear() throw();
  29415. /** Appends a line of text to the arrangement.
  29416. This will add the text as a single line, where x is the left-hand edge of the
  29417. first character, and y is the position for the text's baseline.
  29418. If the text contains new-lines or carriage-returns, this will ignore them - use
  29419. addJustifiedText() to add multi-line arrangements.
  29420. */
  29421. void addLineOfText (const Font& font,
  29422. const String& text,
  29423. const float x,
  29424. const float y) throw();
  29425. /** Adds a line of text, truncating it if it's wider than a specified size.
  29426. This is the same as addLineOfText(), but if the line's width exceeds the value
  29427. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  29428. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  29429. */
  29430. void addCurtailedLineOfText (const Font& font,
  29431. const String& text,
  29432. float x,
  29433. const float y,
  29434. const float maxWidthPixels,
  29435. const bool useEllipsis) throw();
  29436. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  29437. This will add text to the arrangement, breaking it into new lines either where there
  29438. is a new-line or carriage-return character in the text, or where a line's width
  29439. exceeds the value set in maxLineWidth.
  29440. Each line that is added will be laid out using the flags set in horizontalLayout, so
  29441. the lines can be left- or right-justified, or centred horizontally in the space
  29442. between x and (x + maxLineWidth).
  29443. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  29444. lines will be placed below it, separated by a distance of font.getHeight().
  29445. */
  29446. void addJustifiedText (const Font& font,
  29447. const String& text,
  29448. float x, float y,
  29449. const float maxLineWidth,
  29450. const Justification& horizontalLayout) throw();
  29451. /** Tries to fit some text withing a given space.
  29452. This does its best to make the given text readable within the specified rectangle,
  29453. so it useful for labelling things.
  29454. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  29455. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  29456. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  29457. it's been truncated.
  29458. A Justification parameter lets you specify how the text is laid out within the rectangle,
  29459. both horizontally and vertically.
  29460. @see Graphics::drawFittedText
  29461. */
  29462. void addFittedText (const Font& font,
  29463. const String& text,
  29464. const float x, const float y,
  29465. const float width, const float height,
  29466. const Justification& layout,
  29467. int maximumLinesToUse,
  29468. const float minimumHorizontalScale = 0.7f) throw();
  29469. /** Appends another glyph arrangement to this one. */
  29470. void addGlyphArrangement (const GlyphArrangement& other) throw();
  29471. /** Draws this glyph arrangement to a graphics context.
  29472. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  29473. method, which renders the glyphs as filled vectors.
  29474. */
  29475. void draw (const Graphics& g) const throw();
  29476. /** Draws this glyph arrangement to a graphics context.
  29477. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  29478. method for non-transformed arrangements.
  29479. */
  29480. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29481. /** Converts the set of glyphs into a path.
  29482. @param path the glyphs' outlines will be appended to this path
  29483. */
  29484. void createPath (Path& path) const throw();
  29485. /** Looks for a glyph that contains the given co-ordinate.
  29486. @returns the index of the glyph, or -1 if none were found.
  29487. */
  29488. int findGlyphIndexAt (float x, float y) const throw();
  29489. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  29490. @param startIndex the first glyph to test
  29491. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  29492. startIndex will be included
  29493. @param left on return, the leftmost co-ordinate of the rectangle
  29494. @param top on return, the top co-ordinate of the rectangle
  29495. @param right on return, the rightmost co-ordinate of the rectangle
  29496. @param bottom on return, the bottom co-ordinate of the rectangle
  29497. @param includeWhitespace if true, the extent of any whitespace characters will also
  29498. be taken into account
  29499. */
  29500. void getBoundingBox (int startIndex,
  29501. int numGlyphs,
  29502. float& left,
  29503. float& top,
  29504. float& right,
  29505. float& bottom,
  29506. const bool includeWhitespace) const throw();
  29507. /** Shifts a set of glyphs by a given amount.
  29508. @param startIndex the first glyph to transform
  29509. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  29510. startIndex will be used
  29511. @param deltaX the amount to add to their x-positions
  29512. @param deltaY the amount to add to their y-positions
  29513. */
  29514. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  29515. const float deltaX,
  29516. const float deltaY) throw();
  29517. /** Removes a set of glyphs from the arrangement.
  29518. @param startIndex the first glyph to remove
  29519. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  29520. startIndex will be deleted
  29521. */
  29522. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  29523. /** Expands or compresses a set of glyphs horizontally.
  29524. @param startIndex the first glyph to transform
  29525. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  29526. startIndex will be used
  29527. @param horizontalScaleFactor how much to scale their horizontal width by
  29528. */
  29529. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  29530. const float horizontalScaleFactor) throw();
  29531. /** Justifies a set of glyphs within a given space.
  29532. This moves the glyphs as a block so that the whole thing is located within the
  29533. given rectangle with the specified layout.
  29534. If the Justification::horizontallyJustified flag is specified, each line will
  29535. be stretched out to fill the specified width.
  29536. */
  29537. void justifyGlyphs (const int startIndex, const int numGlyphs,
  29538. const float x,
  29539. const float y,
  29540. const float width,
  29541. const float height,
  29542. const Justification& justification) throw();
  29543. juce_UseDebuggingNewOperator
  29544. private:
  29545. OwnedArray <PositionedGlyph> glyphs;
  29546. int insertEllipsis (const Font& font, const float maxXPos, const int startIndex, int endIndex) throw();
  29547. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  29548. const Justification& justification, float minimumHorizontalScale) throw();
  29549. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  29550. };
  29551. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29552. /********* End of inlined file: juce_GlyphArrangement.h *********/
  29553. #endif
  29554. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29555. #endif
  29556. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29557. #endif
  29558. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29559. #endif
  29560. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29561. #endif
  29562. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29563. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29564. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29565. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29566. /********* Start of inlined file: juce_Image.h *********/
  29567. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29568. #define __JUCE_IMAGE_JUCEHEADER__
  29569. /**
  29570. Holds a fixed-size bitmap.
  29571. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  29572. To draw into an image, create a Graphics object for it.
  29573. e.g. @code
  29574. // create a transparent 500x500 image..
  29575. Image myImage (Image::RGB, 500, 500, true);
  29576. Graphics g (myImage);
  29577. g.setColour (Colours::red);
  29578. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  29579. @endcode
  29580. Other useful ways to create an image are with the ImageCache class, or the
  29581. ImageFileFormat, which provides a way to load common image files.
  29582. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  29583. */
  29584. class JUCE_API Image
  29585. {
  29586. public:
  29587. enum PixelFormat
  29588. {
  29589. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  29590. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  29591. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  29592. };
  29593. /** Creates an in-memory image with a specified size and format.
  29594. To create an image that can use native OS rendering methods, see createNativeImage().
  29595. @param format the number of colour channels in the image
  29596. @param imageWidth the desired width of the image, in pixels - this value must be
  29597. greater than zero (otherwise a width of 1 will be used)
  29598. @param imageHeight the desired width of the image, in pixels - this value must be
  29599. greater than zero (otherwise a height of 1 will be used)
  29600. @param clearImage if true, the image will initially be cleared to black or transparent
  29601. black. If false, the image may contain random data, and the
  29602. user will have to deal with this
  29603. */
  29604. Image (const PixelFormat format,
  29605. const int imageWidth,
  29606. const int imageHeight,
  29607. const bool clearImage);
  29608. /** Creates a copy of another image.
  29609. @see createCopy
  29610. */
  29611. Image (const Image& other);
  29612. /** Destructor. */
  29613. virtual ~Image();
  29614. /** Tries to create an image that is uses native drawing methods when you render
  29615. onto it.
  29616. On some platforms this will just return a normal software-based image.
  29617. */
  29618. static Image* createNativeImage (const PixelFormat format,
  29619. const int imageWidth,
  29620. const int imageHeight,
  29621. const bool clearImage);
  29622. /** Returns the image's width (in pixels). */
  29623. int getWidth() const throw() { return imageWidth; }
  29624. /** Returns the image's height (in pixels). */
  29625. int getHeight() const throw() { return imageHeight; }
  29626. /** Returns the image's pixel format. */
  29627. PixelFormat getFormat() const throw() { return format; }
  29628. /** True if the image's format is ARGB. */
  29629. bool isARGB() const throw() { return format == ARGB; }
  29630. /** True if the image's format is RGB. */
  29631. bool isRGB() const throw() { return format == RGB; }
  29632. /** True if the image contains an alpha-channel. */
  29633. bool hasAlphaChannel() const throw() { return format != RGB; }
  29634. /** Clears a section of the image with a given colour.
  29635. This won't do any alpha-blending - it just sets all pixels in the image to
  29636. the given colour (which may be non-opaque if the image has an alpha channel).
  29637. */
  29638. virtual void clear (int x, int y, int w, int h,
  29639. const Colour& colourToClearTo = Colour (0x00000000));
  29640. /** Returns a new image that's a copy of this one.
  29641. A new size for the copied image can be specified, or values less than
  29642. zero can be passed-in to use the image's existing dimensions.
  29643. It's up to the caller to delete the image when no longer needed.
  29644. */
  29645. virtual Image* createCopy (int newWidth = -1,
  29646. int newHeight = -1,
  29647. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  29648. /** Returns a new single-channel image which is a copy of the alpha-channel of this image.
  29649. */
  29650. virtual Image* createCopyOfAlphaChannel() const;
  29651. /** Returns the colour of one of the pixels in the image.
  29652. If the co-ordinates given are beyond the image's boundaries, this will
  29653. return Colours::transparentBlack.
  29654. (0, 0) is the image's top-left corner.
  29655. @see getAlphaAt, setPixelAt, blendPixelAt
  29656. */
  29657. virtual const Colour getPixelAt (const int x, const int y) const;
  29658. /** Sets the colour of one of the image's pixels.
  29659. If the co-ordinates are beyond the image's boundaries, then nothing will
  29660. happen.
  29661. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  29662. just replace the existing pixel with the given one. The colour's opacity
  29663. will be ignored if this image doesn't have an alpha-channel.
  29664. (0, 0) is the image's top-left corner.
  29665. @see blendPixelAt
  29666. */
  29667. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  29668. /** Changes the opacity of a pixel.
  29669. This only has an effect if the image has an alpha channel and if the
  29670. given co-ordinates are inside the image's boundary.
  29671. The multiplier must be in the range 0 to 1.0, and the current alpha
  29672. at the given co-ordinates will be multiplied by this value.
  29673. @see getAlphaAt, setPixelAt
  29674. */
  29675. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  29676. /** Changes the overall opacity of the image.
  29677. This will multiply the alpha value of each pixel in the image by the given
  29678. amount (limiting the resulting alpha values between 0 and 255). This allows
  29679. you to make an image more or less transparent.
  29680. If the image doesn't have an alpha channel, this won't have any effect.
  29681. */
  29682. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  29683. /** Changes all the colours to be shades of grey, based on their current luminosity.
  29684. */
  29685. virtual void desaturate();
  29686. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  29687. You should only use this class as a last resort - messing about with the internals of
  29688. an image is only recommended for people who really know what they're doing!
  29689. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  29690. hanging around while the image is being used elsewhere.
  29691. Depending on the way the image class is implemented, this may create a temporary buffer
  29692. which is copied back to the image when the object is deleted, or it may just get a pointer
  29693. directly into the image's raw data.
  29694. You can use the stride and data values in this class directly, but don't alter them!
  29695. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  29696. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  29697. */
  29698. class BitmapData
  29699. {
  29700. public:
  29701. BitmapData (Image& image, int x, int y, int w, int h, const bool needsToBeWritable) throw();
  29702. BitmapData (const Image& image, int x, int y, int w, int h) throw();
  29703. ~BitmapData() throw();
  29704. /** Returns a pointer to the start of a line in the image.
  29705. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  29706. sure it's not out-of-range.
  29707. */
  29708. inline uint8* getLinePointer (const int y) const throw() { return data + y * lineStride; }
  29709. /** Returns a pointer to a pixel in the image.
  29710. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  29711. not out-of-range.
  29712. */
  29713. inline uint8* getPixelPointer (const int x, const int y) const throw() { return data + y * lineStride + x * pixelStride; }
  29714. uint8* data;
  29715. int lineStride, pixelStride, width, height;
  29716. };
  29717. /** Copies some pixel values to a rectangle of the image.
  29718. The format of the pixel data must match that of the image itself, and the
  29719. rectangle supplied must be within the image's bounds.
  29720. */
  29721. virtual void setPixelData (int destX, int destY, int destW, int destH,
  29722. const uint8* sourcePixelData, int sourceLineStride);
  29723. /** Copies a section of the image to somewhere else within itself.
  29724. */
  29725. virtual void moveImageSection (int destX, int destY,
  29726. int sourceX, int sourceY,
  29727. int width, int height);
  29728. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  29729. of the image.
  29730. @param result the list that will have the area added to it
  29731. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  29732. above this level will be considered opaque
  29733. */
  29734. void createSolidAreaMask (RectangleList& result,
  29735. const float alphaThreshold = 0.5f) const;
  29736. juce_UseDebuggingNewOperator
  29737. /** Creates a context suitable for drawing onto this image.
  29738. Don't call this method directly! It's used internally by the Graphics class.
  29739. */
  29740. virtual LowLevelGraphicsContext* createLowLevelContext();
  29741. protected:
  29742. friend class BitmapData;
  29743. const PixelFormat format;
  29744. const int imageWidth, imageHeight;
  29745. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  29746. Image (const PixelFormat format,
  29747. const int imageWidth,
  29748. const int imageHeight);
  29749. int pixelStride, lineStride;
  29750. uint8* imageData;
  29751. private:
  29752. const Image& operator= (const Image&);
  29753. };
  29754. #endif // __JUCE_IMAGE_JUCEHEADER__
  29755. /********* End of inlined file: juce_Image.h *********/
  29756. /**
  29757. Interface class for graphics context objects, used internally by the Graphics class.
  29758. Users are not supposed to create instances of this class directly - do your drawing
  29759. via the Graphics object instead.
  29760. It's a base class for different types of graphics context, that may perform software-based
  29761. or OS-accelerated rendering.
  29762. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29763. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29764. context.
  29765. */
  29766. class JUCE_API LowLevelGraphicsContext
  29767. {
  29768. protected:
  29769. LowLevelGraphicsContext();
  29770. public:
  29771. virtual ~LowLevelGraphicsContext();
  29772. /** Returns true if this device is vector-based, e.g. a printer. */
  29773. virtual bool isVectorDevice() const = 0;
  29774. /** Moves the origin to a new position.
  29775. The co-ords are relative to the current origin, and indicate the new position
  29776. of (0, 0).
  29777. */
  29778. virtual void setOrigin (int x, int y) = 0;
  29779. virtual bool clipToRectangle (const Rectangle& r) = 0;
  29780. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  29781. virtual void excludeClipRectangle (const Rectangle& r) = 0;
  29782. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  29783. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform) = 0;
  29784. virtual bool clipRegionIntersects (const Rectangle& r) = 0;
  29785. virtual const Rectangle getClipBounds() const = 0;
  29786. virtual bool isClipEmpty() const = 0;
  29787. virtual void saveState() = 0;
  29788. virtual void restoreState() = 0;
  29789. virtual void setFill (const FillType& fillType) = 0;
  29790. virtual void setOpacity (float newOpacity) = 0;
  29791. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  29792. virtual void fillRect (const Rectangle& r, const bool replaceExistingContents) = 0;
  29793. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  29794. virtual void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  29795. const AffineTransform& transform, const bool fillEntireClipAsTiles) = 0;
  29796. virtual void drawLine (double x1, double y1, double x2, double y2) = 0;
  29797. virtual void drawVerticalLine (const int x, double top, double bottom) = 0;
  29798. virtual void drawHorizontalLine (const int y, double left, double right) = 0;
  29799. virtual void setFont (const Font& newFont) = 0;
  29800. virtual const Font getFont() = 0;
  29801. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  29802. };
  29803. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29804. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29805. #endif
  29806. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29807. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29808. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29809. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29810. class LLGCSavedState;
  29811. /**
  29812. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29813. its rendering in memory.
  29814. User code is not supposed to create instances of this class directly - do all your
  29815. rendering via the Graphics class instead.
  29816. */
  29817. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29818. {
  29819. public:
  29820. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29821. ~LowLevelGraphicsSoftwareRenderer();
  29822. bool isVectorDevice() const;
  29823. void setOrigin (int x, int y);
  29824. bool clipToRectangle (const Rectangle& r);
  29825. bool clipToRectangleList (const RectangleList& clipRegion);
  29826. void excludeClipRectangle (const Rectangle& r);
  29827. void clipToPath (const Path& path, const AffineTransform& transform);
  29828. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  29829. bool clipRegionIntersects (const Rectangle& r);
  29830. const Rectangle getClipBounds() const;
  29831. bool isClipEmpty() const;
  29832. void saveState();
  29833. void restoreState();
  29834. void setFill (const FillType& fillType);
  29835. void setOpacity (float opacity);
  29836. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  29837. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  29838. void fillPath (const Path& path, const AffineTransform& transform);
  29839. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  29840. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  29841. void drawLine (double x1, double y1, double x2, double y2);
  29842. void drawVerticalLine (const int x, double top, double bottom);
  29843. void drawHorizontalLine (const int x, double top, double bottom);
  29844. void setFont (const Font& newFont);
  29845. const Font getFont();
  29846. void drawGlyph (int glyphNumber, float x, float y);
  29847. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  29848. juce_UseDebuggingNewOperator
  29849. protected:
  29850. Image& image;
  29851. LLGCSavedState* currentState;
  29852. OwnedArray <LLGCSavedState> stateStack;
  29853. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29854. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29855. };
  29856. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29857. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29858. #endif
  29859. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29860. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29861. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29862. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29863. /**
  29864. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29865. into a PostScript document.
  29866. */
  29867. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29868. {
  29869. public:
  29870. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29871. const String& documentTitle,
  29872. const int totalWidth,
  29873. const int totalHeight);
  29874. ~LowLevelGraphicsPostScriptRenderer();
  29875. bool isVectorDevice() const;
  29876. void setOrigin (int x, int y);
  29877. bool clipToRectangle (const Rectangle& r);
  29878. bool clipToRectangleList (const RectangleList& clipRegion);
  29879. void excludeClipRectangle (const Rectangle& r);
  29880. void clipToPath (const Path& path, const AffineTransform& transform);
  29881. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  29882. void saveState();
  29883. void restoreState();
  29884. bool clipRegionIntersects (const Rectangle& r);
  29885. const Rectangle getClipBounds() const;
  29886. bool isClipEmpty() const;
  29887. void setFill (const FillType& fillType);
  29888. void setOpacity (float opacity);
  29889. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  29890. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  29891. void fillPath (const Path& path, const AffineTransform& transform);
  29892. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  29893. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  29894. void drawLine (double x1, double y1, double x2, double y2);
  29895. void drawVerticalLine (const int x, double top, double bottom);
  29896. void drawHorizontalLine (const int x, double top, double bottom);
  29897. const Font getFont();
  29898. void setFont (const Font& newFont);
  29899. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  29900. juce_UseDebuggingNewOperator
  29901. protected:
  29902. OutputStream& out;
  29903. int totalWidth, totalHeight;
  29904. bool needToClip;
  29905. Colour lastColour;
  29906. struct SavedState
  29907. {
  29908. SavedState();
  29909. ~SavedState();
  29910. RectangleList clip;
  29911. int xOffset, yOffset;
  29912. FillType fillType;
  29913. Font font;
  29914. private:
  29915. const SavedState& operator= (const SavedState&);
  29916. };
  29917. OwnedArray <SavedState> stateStack;
  29918. void writeClip();
  29919. void writeColour (const Colour& colour);
  29920. void writePath (const Path& path) const;
  29921. void writeXY (const float x, const float y) const;
  29922. void writeTransform (const AffineTransform& trans) const;
  29923. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29924. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29925. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29926. };
  29927. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29928. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29929. #endif
  29930. #ifndef __JUCE_PATH_JUCEHEADER__
  29931. #endif
  29932. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29933. #endif
  29934. #ifndef __JUCE_LINE_JUCEHEADER__
  29935. #endif
  29936. #ifndef __JUCE_POINT_JUCEHEADER__
  29937. #endif
  29938. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29939. #endif
  29940. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29941. #endif
  29942. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29943. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29944. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29945. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29946. /**
  29947. A rectangle whose co-ordinates can be defined in terms of absolute or
  29948. proportional distances.
  29949. Designed mainly for storing component positions, this gives you a lot of
  29950. control over how each co-ordinate is stored, either as an absolute position,
  29951. or as a proportion of the size of a parent rectangle.
  29952. It also allows you to define the anchor points by which the rectangle is
  29953. positioned, so for example you could specify that the top right of the
  29954. rectangle should be an absolute distance from its parent's bottom-right corner.
  29955. This object can be stored as a string, which takes the form "x y w h", including
  29956. symbols like '%' and letters to indicate the anchor point. See its toString()
  29957. method for more info.
  29958. Example usage:
  29959. @code
  29960. class MyComponent
  29961. {
  29962. void resized()
  29963. {
  29964. // this will set the child component's x to be 20% of our width, its y
  29965. // to be 30, its width to be 150, and its height to be 50% of our
  29966. // height..
  29967. const PositionedRectangle pos1 ("20% 30 150 50%");
  29968. pos1.applyToComponent (*myChildComponent1);
  29969. // this will inset the child component with a gap of 10 pixels
  29970. // around each of its edges..
  29971. const PositionedRectangle pos2 ("10 10 20M 20M");
  29972. pos2.applyToComponent (*myChildComponent2);
  29973. }
  29974. };
  29975. @endcode
  29976. */
  29977. class JUCE_API PositionedRectangle
  29978. {
  29979. public:
  29980. /** Creates an empty rectangle with all co-ordinates set to zero.
  29981. The default anchor point is top-left; the default
  29982. */
  29983. PositionedRectangle() throw();
  29984. /** Initialises a PositionedRectangle from a saved string version.
  29985. The string must be in the format generated by toString().
  29986. */
  29987. PositionedRectangle (const String& stringVersion) throw();
  29988. /** Creates a copy of another PositionedRectangle. */
  29989. PositionedRectangle (const PositionedRectangle& other) throw();
  29990. /** Copies another PositionedRectangle. */
  29991. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29992. /** Destructor. */
  29993. ~PositionedRectangle() throw();
  29994. /** Returns a string version of this position, from which it can later be
  29995. re-generated.
  29996. The format is four co-ordinates, "x y w h".
  29997. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29998. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29999. as a percentage, e.g. "80%".
  30000. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  30001. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  30002. the parent's right-hand edge.
  30003. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  30004. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  30005. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  30006. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  30007. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  30008. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  30009. has "c" appended to it. So "-50Rc" would mean that this component's
  30010. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  30011. this component's centre should be placed 40% across the parent's width.
  30012. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  30013. the number has "M" appended to it.
  30014. To reload a stored string, use the constructor that takes a string parameter.
  30015. */
  30016. const String toString() const throw();
  30017. /** Calculates the absolute position, given the size of the space that
  30018. it should go in.
  30019. This will work out any proportional distances and sizes relative to the
  30020. target rectangle, and will return the absolute position.
  30021. @see applyToComponent
  30022. */
  30023. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  30024. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  30025. */
  30026. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  30027. double& x,
  30028. double& y,
  30029. double& width,
  30030. double& height) const throw();
  30031. /** This sets the bounds of the given component to this position.
  30032. This is equivalent to writing:
  30033. @code
  30034. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  30035. @endcode
  30036. @see getRectangle, updateFromComponent
  30037. */
  30038. void applyToComponent (Component& comp) const throw();
  30039. /** Updates this object's co-ordinates to match the given rectangle.
  30040. This will set all co-ordinates based on the given rectangle, re-calculating
  30041. any proportional distances, and using the current anchor points.
  30042. So for example if the x co-ordinate mode is currently proportional, this will
  30043. re-calculate x based on the rectangle's relative position within the target
  30044. rectangle's width.
  30045. If the target rectangle's width or height are zero then it may not be possible
  30046. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  30047. will not be changed.
  30048. */
  30049. void updateFrom (const Rectangle& newPosition,
  30050. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30051. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  30052. */
  30053. void updateFromDouble (const double x, const double y,
  30054. const double width, const double height,
  30055. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30056. /** Updates this object's co-ordinates to match the bounds of this component.
  30057. This is equivalent to calling updateFrom() with the component's bounds and
  30058. it parent size.
  30059. If the component doesn't currently have a parent, then proportional co-ordinates
  30060. might not be updated because it would need to know the parent's size to do the
  30061. maths for this.
  30062. */
  30063. void updateFromComponent (const Component& comp) throw();
  30064. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  30065. enum AnchorPoint
  30066. {
  30067. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  30068. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  30069. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  30070. };
  30071. /** Specifies how an x or y co-ordinate should be interpreted. */
  30072. enum PositionMode
  30073. {
  30074. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  30075. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  30076. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  30077. 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. */
  30078. };
  30079. /** Specifies how the width or height should be interpreted. */
  30080. enum SizeMode
  30081. {
  30082. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  30083. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  30084. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  30085. };
  30086. /** Sets all options for all co-ordinates.
  30087. This requires a reference rectangle to be specified, because if you're changing any
  30088. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  30089. the co-ordinates, and will need to know the parent size so it can calculate this.
  30090. */
  30091. void setModes (const AnchorPoint xAnchorMode,
  30092. const PositionMode xPositionMode,
  30093. const AnchorPoint yAnchorMode,
  30094. const PositionMode yPositionMode,
  30095. const SizeMode widthMode,
  30096. const SizeMode heightMode,
  30097. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30098. /** Returns the anchoring mode for the x co-ordinate.
  30099. To change any of the modes, use setModes().
  30100. */
  30101. AnchorPoint getAnchorPointX() const throw();
  30102. /** Returns the positioning mode for the x co-ordinate.
  30103. To change any of the modes, use setModes().
  30104. */
  30105. PositionMode getPositionModeX() const throw();
  30106. /** Returns the raw x co-ordinate.
  30107. If the x position mode is absolute, then this will be the absolute value. If it's
  30108. proportional, then this will be a fractional proportion, where 1.0 means the full
  30109. width of the parent space.
  30110. */
  30111. double getX() const throw() { return x; }
  30112. /** Sets the raw value of the x co-ordinate.
  30113. See getX() for the meaning of this value.
  30114. */
  30115. void setX (const double newX) throw() { x = newX; }
  30116. /** Returns the anchoring mode for the y co-ordinate.
  30117. To change any of the modes, use setModes().
  30118. */
  30119. AnchorPoint getAnchorPointY() const throw();
  30120. /** Returns the positioning mode for the y co-ordinate.
  30121. To change any of the modes, use setModes().
  30122. */
  30123. PositionMode getPositionModeY() const throw();
  30124. /** Returns the raw y co-ordinate.
  30125. If the y position mode is absolute, then this will be the absolute value. If it's
  30126. proportional, then this will be a fractional proportion, where 1.0 means the full
  30127. height of the parent space.
  30128. */
  30129. double getY() const throw() { return y; }
  30130. /** Sets the raw value of the y co-ordinate.
  30131. See getY() for the meaning of this value.
  30132. */
  30133. void setY (const double newY) throw() { y = newY; }
  30134. /** Returns the mode used to calculate the width.
  30135. To change any of the modes, use setModes().
  30136. */
  30137. SizeMode getWidthMode() const throw();
  30138. /** Returns the raw width value.
  30139. If the width mode is absolute, then this will be the absolute value. If the mode is
  30140. proportional, then this will be a fractional proportion, where 1.0 means the full
  30141. width of the parent space.
  30142. */
  30143. double getWidth() const throw() { return w; }
  30144. /** Sets the raw width value.
  30145. See getWidth() for the details about what this value means.
  30146. */
  30147. void setWidth (const double newWidth) throw() { w = newWidth; }
  30148. /** Returns the mode used to calculate the height.
  30149. To change any of the modes, use setModes().
  30150. */
  30151. SizeMode getHeightMode() const throw();
  30152. /** Returns the raw height value.
  30153. If the height mode is absolute, then this will be the absolute value. If the mode is
  30154. proportional, then this will be a fractional proportion, where 1.0 means the full
  30155. height of the parent space.
  30156. */
  30157. double getHeight() const throw() { return h; }
  30158. /** Sets the raw height value.
  30159. See getHeight() for the details about what this value means.
  30160. */
  30161. void setHeight (const double newHeight) throw() { h = newHeight; }
  30162. /** If the size and position are constance, and wouldn't be affected by changes
  30163. in the parent's size, then this will return true.
  30164. */
  30165. bool isPositionAbsolute() const throw();
  30166. /** Compares two objects. */
  30167. const bool operator== (const PositionedRectangle& other) const throw();
  30168. /** Compares two objects. */
  30169. const bool operator!= (const PositionedRectangle& other) const throw();
  30170. juce_UseDebuggingNewOperator
  30171. private:
  30172. double x, y, w, h;
  30173. uint8 xMode, yMode, wMode, hMode;
  30174. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  30175. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  30176. void decodePosString (const String& s, uint8& mode, double& value) throw();
  30177. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  30178. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  30179. const uint8 xMode, const uint8 wMode,
  30180. const int parentPos, const int parentSize) const throw();
  30181. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  30182. const uint8 xMode, const uint8 wMode,
  30183. const int parentPos, const int parentSize) const throw();
  30184. };
  30185. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30186. /********* End of inlined file: juce_PositionedRectangle.h *********/
  30187. #endif
  30188. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  30189. #endif
  30190. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  30191. /********* Start of inlined file: juce_PathIterator.h *********/
  30192. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  30193. #define __JUCE_PATHITERATOR_JUCEHEADER__
  30194. /**
  30195. Flattens a Path object into a series of straight-line sections.
  30196. Use one of these to iterate through a Path object, and it will convert
  30197. all the curves into line sections so it's easy to render or perform
  30198. geometric operations on.
  30199. @see Path
  30200. */
  30201. class JUCE_API PathFlatteningIterator
  30202. {
  30203. public:
  30204. /** Creates a PathFlatteningIterator.
  30205. After creation, use the next() method to initialise the fields in the
  30206. object with the first line's position.
  30207. @param path the path to iterate along
  30208. @param transform a transform to apply to each point in the path being iterated
  30209. @param tolerence the amount by which the curves are allowed to deviate from the
  30210. lines into which they are being broken down - a higher tolerence
  30211. is a bit faster, but less smooth.
  30212. */
  30213. PathFlatteningIterator (const Path& path,
  30214. const AffineTransform& transform = AffineTransform::identity,
  30215. float tolerence = 6.0f) throw();
  30216. /** Destructor. */
  30217. ~PathFlatteningIterator() throw();
  30218. /** Fetches the next line segment from the path.
  30219. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  30220. so that they describe the new line segment.
  30221. @returns false when there are no more lines to fetch.
  30222. */
  30223. bool next() throw();
  30224. /** The x position of the start of the current line segment. */
  30225. float x1;
  30226. /** The y position of the start of the current line segment. */
  30227. float y1;
  30228. /** The x position of the end of the current line segment. */
  30229. float x2;
  30230. /** The y position of the end of the current line segment. */
  30231. float y2;
  30232. /** Indicates whether the current line segment is closing a sub-path.
  30233. If the current line is the one that connects the end of a sub-path
  30234. back to the start again, this will be true.
  30235. */
  30236. bool closesSubPath;
  30237. /** The index of the current line within the current sub-path.
  30238. E.g. you can use this to see whether the line is the first one in the
  30239. subpath by seeing if it's 0.
  30240. */
  30241. int subPathIndex;
  30242. /** Returns true if the current segment is the last in the current sub-path. */
  30243. bool isLastInSubpath() const throw() { return stackPos == stackBase
  30244. && (index >= path.numElements
  30245. || points [index] == Path::moveMarker); }
  30246. juce_UseDebuggingNewOperator
  30247. private:
  30248. const Path& path;
  30249. const AffineTransform transform;
  30250. float* points;
  30251. float tolerence, subPathCloseX, subPathCloseY;
  30252. bool isIdentityTransform;
  30253. float* stackBase;
  30254. float* stackPos;
  30255. int index, stackSize;
  30256. PathFlatteningIterator (const PathFlatteningIterator&);
  30257. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  30258. };
  30259. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  30260. /********* End of inlined file: juce_PathIterator.h *********/
  30261. #endif
  30262. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  30263. #endif
  30264. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30265. /********* Start of inlined file: juce_CameraDevice.h *********/
  30266. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30267. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  30268. #if JUCE_USE_CAMERA
  30269. /**
  30270. Receives callbacks with images from a CameraDevice.
  30271. @see CameraDevice::addListener
  30272. */
  30273. class CameraImageListener
  30274. {
  30275. public:
  30276. CameraImageListener() {}
  30277. virtual ~CameraImageListener() {}
  30278. /** This method is called when a new image arrives.
  30279. This may be called by any thread, so be careful about thread-safety,
  30280. and make sure that you process the data as quickly as possible to
  30281. avoid glitching!
  30282. */
  30283. virtual void imageReceived (Image& image) = 0;
  30284. };
  30285. /**
  30286. Controls any camera capture devices that might be available.
  30287. Use getAvailableDevices() to list the devices that are attached to the
  30288. system, then call openDevice to open one for use. Once you have a CameraDevice
  30289. object, you can get a viewer component from it, and use its methods to
  30290. stream to a file or capture still-frames.
  30291. */
  30292. class JUCE_API CameraDevice
  30293. {
  30294. public:
  30295. /** Destructor. */
  30296. virtual ~CameraDevice();
  30297. /** Returns a list of the available cameras on this machine.
  30298. You can open one of these devices by calling openDevice().
  30299. */
  30300. static const StringArray getAvailableDevices();
  30301. /** Opens a camera device.
  30302. The index parameter indicates which of the items returned by getAvailableDevices()
  30303. to open.
  30304. The size constraints allow the method to choose between different resolutions if
  30305. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  30306. then these will be ignored.
  30307. */
  30308. static CameraDevice* openDevice (int deviceIndex,
  30309. int minWidth = 128, int minHeight = 64,
  30310. int maxWidth = 1024, int maxHeight = 768);
  30311. /** Returns the name of this device */
  30312. const String getName() const throw() { return name; }
  30313. /** Creates a component that can be used to display a preview of the
  30314. video from this camera.
  30315. */
  30316. Component* createViewerComponent();
  30317. /** Starts recording video to the specified file.
  30318. You should use getFileExtension() to find out the correct extension to
  30319. use for your filename.
  30320. If the file exists, it will be deleted before the recording starts.
  30321. This method may not start recording instantly, so if you need to know the
  30322. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  30323. after the recording has finished.
  30324. */
  30325. void startRecordingToFile (const File& file);
  30326. /** Stops recording, after a call to startRecordingToFile().
  30327. */
  30328. void stopRecording();
  30329. /** Returns the file extension that should be used for the files
  30330. that you pass to startRecordingToFile().
  30331. This may be platform-specific, e.g. ".mov" or ".avi".
  30332. */
  30333. static const String getFileExtension();
  30334. /** After calling stopRecording(), this method can be called to return the timestamp
  30335. of the first frame that was written to the file.
  30336. */
  30337. const Time getTimeOfFirstRecordedFrame() const;
  30338. /** Adds a listener to receive images from the camera.
  30339. Be very careful not to delete the listener without first removing it by calling
  30340. removeListener().
  30341. */
  30342. void addListener (CameraImageListener* listenerToAdd);
  30343. /** Removes a listener that was previously added with addListener().
  30344. */
  30345. void removeListener (CameraImageListener* listenerToRemove);
  30346. juce_UseDebuggingNewOperator
  30347. protected:
  30348. /** @internal */
  30349. CameraDevice (const String& name, int index);
  30350. private:
  30351. void* internal;
  30352. bool isRecording;
  30353. String name;
  30354. CameraDevice (const CameraDevice&);
  30355. const CameraDevice& operator= (const CameraDevice&);
  30356. };
  30357. #endif
  30358. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  30359. /********* End of inlined file: juce_CameraDevice.h *********/
  30360. #endif
  30361. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30362. /********* Start of inlined file: juce_ImageCache.h *********/
  30363. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30364. #define __JUCE_IMAGECACHE_JUCEHEADER__
  30365. /**
  30366. A global cache of images that have been loaded from files or memory.
  30367. If you're loading an image and may need to use the image in more than one
  30368. place, this is used to allow the same image to be shared rather than loading
  30369. multiple copies into memory.
  30370. Another advantage is that after images are released, they will be kept in
  30371. memory for a few seconds before it is actually deleted, so if you're repeatedly
  30372. loading/deleting the same image, it'll reduce the chances of having to reload it
  30373. each time.
  30374. @see Image, ImageFileFormat
  30375. */
  30376. class JUCE_API ImageCache : private DeletedAtShutdown,
  30377. private Timer
  30378. {
  30379. public:
  30380. /** Loads an image from a file, (or just returns the image if it's already cached).
  30381. If the cache already contains an image that was loaded from this file,
  30382. that image will be returned. Otherwise, this method will try to load the
  30383. file, add it to the cache, and return it.
  30384. It's very important not to delete the image that is returned - instead use
  30385. the ImageCache::release() method.
  30386. Also, remember that the image returned is shared, so drawing into it might
  30387. affect other things that are using it!
  30388. @param file the file to try to load
  30389. @returns the image, or null if it there was an error loading it
  30390. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30391. */
  30392. static Image* getFromFile (const File& file);
  30393. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  30394. If the cache already contains an image that was loaded from this block of memory,
  30395. that image will be returned. Otherwise, this method will try to load the
  30396. file, add it to the cache, and return it.
  30397. It's very important not to delete the image that is returned - instead use
  30398. the ImageCache::release() method.
  30399. Also, remember that the image returned is shared, so drawing into it might
  30400. affect other things that are using it!
  30401. @param imageData the block of memory containing the image data
  30402. @param dataSize the data size in bytes
  30403. @returns the image, or null if it there was an error loading it
  30404. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30405. */
  30406. static Image* getFromMemory (const void* imageData,
  30407. const int dataSize);
  30408. /** Releases an image that was previously created by the ImageCache.
  30409. If an image has been returned by the getFromFile() or getFromMemory() methods,
  30410. it mustn't be deleted directly, but should be released with this method
  30411. instead.
  30412. @see getFromFile, getFromMemory
  30413. */
  30414. static void release (Image* const imageToRelease);
  30415. /** Checks whether an image is in the cache or not.
  30416. @returns true if the image is currently in the cache
  30417. */
  30418. static bool isImageInCache (Image* const imageToLookFor);
  30419. /** Increments the reference-count for a cached image.
  30420. If the image isn't in the cache, this method won't do anything.
  30421. */
  30422. static void incReferenceCount (Image* const image);
  30423. /** Checks the cache for an image with a particular hashcode.
  30424. If there's an image in the cache with this hashcode, it will be returned,
  30425. otherwise it will return zero.
  30426. If an image is returned, it must be released with the release() method
  30427. when no longer needed, to maintain the correct reference counts.
  30428. @param hashCode the hash code that would have been associated with the
  30429. image by addImageToCache()
  30430. @see addImageToCache
  30431. */
  30432. static Image* getFromHashCode (const int64 hashCode);
  30433. /** Adds an image to the cache with a user-defined hash-code.
  30434. After calling this, responsibilty for deleting the image will be taken
  30435. by the ImageCache.
  30436. The image will be initially be given a reference count of 1, so call
  30437. the release() method to delete it.
  30438. @param image the image to add
  30439. @param hashCode the hash-code to associate with it
  30440. @see getFromHashCode
  30441. */
  30442. static void addImageToCache (Image* const image,
  30443. const int64 hashCode);
  30444. /** Changes the amount of time before an unused image will be removed from the cache.
  30445. By default this is about 5 seconds.
  30446. */
  30447. static void setCacheTimeout (const int millisecs);
  30448. juce_UseDebuggingNewOperator
  30449. private:
  30450. CriticalSection lock;
  30451. VoidArray images;
  30452. ImageCache() throw();
  30453. ImageCache (const ImageCache&);
  30454. const ImageCache& operator= (const ImageCache&);
  30455. ~ImageCache();
  30456. void timerCallback();
  30457. };
  30458. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  30459. /********* End of inlined file: juce_ImageCache.h *********/
  30460. #endif
  30461. #ifndef __JUCE_IMAGE_JUCEHEADER__
  30462. #endif
  30463. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30464. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30465. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30466. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30467. /**
  30468. Base-class for codecs that can read and write image file formats such
  30469. as PNG, JPEG, etc.
  30470. This class also contains static methods to make it easy to load images
  30471. from files, streams or from memory.
  30472. @see Image, ImageCache
  30473. */
  30474. class JUCE_API ImageFileFormat
  30475. {
  30476. protected:
  30477. /** Creates an ImageFormat. */
  30478. ImageFileFormat() throw() {}
  30479. public:
  30480. /** Destructor. */
  30481. virtual ~ImageFileFormat() throw() {}
  30482. /** Returns a description of this file format.
  30483. E.g. "JPEG", "PNG"
  30484. */
  30485. virtual const String getFormatName() = 0;
  30486. /** Returns true if the given stream seems to contain data that this format
  30487. understands.
  30488. The format class should only read the first few bytes of the stream and sniff
  30489. for header bytes that it understands.
  30490. @see decodeImage
  30491. */
  30492. virtual bool canUnderstand (InputStream& input) = 0;
  30493. /** Tries to decode and return an image from the given stream.
  30494. This will be called for an image format after calling its canUnderStand() method
  30495. to see if it can handle the stream.
  30496. @param input the stream to read the data from. The stream will be positioned
  30497. at the start of the image data (but this may not necessarily
  30498. be position 0)
  30499. @returns the image that was decoded, or 0 if it fails. It's the
  30500. caller's responsibility to delete this image when no longer needed.
  30501. @see loadFrom
  30502. */
  30503. virtual Image* decodeImage (InputStream& input) = 0;
  30504. /** Attempts to write an image to a stream.
  30505. To specify extra information like encoding quality, there will be appropriate parameters
  30506. in the subclasses of the specific file types.
  30507. @returns true if it nothing went wrong.
  30508. */
  30509. virtual bool writeImageToStream (const Image& sourceImage,
  30510. OutputStream& destStream) = 0;
  30511. /** Tries the built-in decoders to see if it can find one to read this stream.
  30512. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30513. The object that is returned should not be deleted by the caller.
  30514. @see canUnderstand, decodeImage, loadFrom
  30515. */
  30516. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30517. /** Tries to load an image from a stream.
  30518. This will use the findImageFormatForStream() method to locate a suitable
  30519. codec, and use that to load the image.
  30520. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30521. caller's responsibility to delete this image when no longer needed.
  30522. */
  30523. static Image* loadFrom (InputStream& input);
  30524. /** Tries to load an image from a file.
  30525. This will use the findImageFormatForStream() method to locate a suitable
  30526. codec, and use that to load the image.
  30527. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30528. caller's responsibility to delete this image when no longer needed.
  30529. */
  30530. static Image* loadFrom (const File& file);
  30531. /** Tries to load an image from a block of raw image data.
  30532. This will use the findImageFormatForStream() method to locate a suitable
  30533. codec, and use that to load the image.
  30534. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30535. caller's responsibility to delete this image when no longer needed.
  30536. */
  30537. static Image* loadFrom (const void* rawData,
  30538. const int numBytesOfData);
  30539. };
  30540. /**
  30541. A type of ImageFileFormat for reading and writing PNG files.
  30542. @see ImageFileFormat, JPEGImageFormat
  30543. */
  30544. class JUCE_API PNGImageFormat : public ImageFileFormat
  30545. {
  30546. public:
  30547. PNGImageFormat() throw();
  30548. ~PNGImageFormat() throw();
  30549. const String getFormatName();
  30550. bool canUnderstand (InputStream& input);
  30551. Image* decodeImage (InputStream& input);
  30552. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30553. };
  30554. /**
  30555. A type of ImageFileFormat for reading and writing JPEG files.
  30556. @see ImageFileFormat, PNGImageFormat
  30557. */
  30558. class JUCE_API JPEGImageFormat : public ImageFileFormat
  30559. {
  30560. public:
  30561. JPEGImageFormat() throw();
  30562. ~JPEGImageFormat() throw();
  30563. /** Specifies the quality to be used when writing a JPEG file.
  30564. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30565. any negative value is "default" quality
  30566. */
  30567. void setQuality (const float newQuality);
  30568. const String getFormatName();
  30569. bool canUnderstand (InputStream& input);
  30570. Image* decodeImage (InputStream& input);
  30571. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30572. private:
  30573. float quality;
  30574. };
  30575. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30576. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30577. #endif
  30578. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30579. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  30580. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30581. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30582. /**
  30583. Represents a filter kernel to use in convoluting an image.
  30584. @see Image::applyConvolution
  30585. */
  30586. class JUCE_API ImageConvolutionKernel
  30587. {
  30588. public:
  30589. /** Creates an empty convulution kernel.
  30590. @param size the length of each dimension of the kernel, so e.g. if the size
  30591. is 5, it will create a 5x5 kernel
  30592. */
  30593. ImageConvolutionKernel (const int size) throw();
  30594. /** Destructor. */
  30595. ~ImageConvolutionKernel() throw();
  30596. /** Resets all values in the kernel to zero.
  30597. */
  30598. void clear() throw();
  30599. /** Sets the value of a specific cell in the kernel.
  30600. The x and y parameters must be in the range 0 < x < getKernelSize().
  30601. @see setOverallSum
  30602. */
  30603. void setKernelValue (const int x,
  30604. const int y,
  30605. const float value) throw();
  30606. /** Rescales all values in the kernel to make the total add up to a fixed value.
  30607. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  30608. */
  30609. void setOverallSum (const float desiredTotalSum) throw();
  30610. /** Multiplies all values in the kernel by a value. */
  30611. void rescaleAllValues (const float multiplier) throw();
  30612. /** Intialises the kernel for a gaussian blur.
  30613. @param blurRadius this may be larger or smaller than the kernel's actual
  30614. size but this will obviously be wasteful or clip at the
  30615. edges. Ideally the kernel should be just larger than
  30616. (blurRadius * 2).
  30617. */
  30618. void createGaussianBlur (const float blurRadius) throw();
  30619. /** Returns the size of the kernel.
  30620. E.g. if it's a 3x3 kernel, this returns 3.
  30621. */
  30622. int getKernelSize() const throw() { return size; }
  30623. /** Returns a 2-dimensional array of the kernel's values.
  30624. The size of each dimension of the array will be getKernelSize().
  30625. */
  30626. float** getValues() const throw() { return values; }
  30627. /** Applies the kernel to an image.
  30628. @param destImage the image that will receive the resultant convoluted pixels.
  30629. @param sourceImage an optional source image to read from - if this is 0, then the
  30630. destination image will be used as the source. If an image is
  30631. specified, it must be exactly the same size and type as the destination
  30632. image.
  30633. @param x the region of the image to apply the filter to
  30634. @param y the region of the image to apply the filter to
  30635. @param width the region of the image to apply the filter to
  30636. @param height the region of the image to apply the filter to
  30637. */
  30638. void applyToImage (Image& destImage,
  30639. const Image* sourceImage,
  30640. int x,
  30641. int y,
  30642. int width,
  30643. int height) const;
  30644. juce_UseDebuggingNewOperator
  30645. private:
  30646. float** values;
  30647. int size;
  30648. // no reason not to implement these one day..
  30649. ImageConvolutionKernel (const ImageConvolutionKernel&);
  30650. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  30651. };
  30652. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30653. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  30654. #endif
  30655. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30656. /********* Start of inlined file: juce_Drawable.h *********/
  30657. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30658. #define __JUCE_DRAWABLE_JUCEHEADER__
  30659. /**
  30660. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30661. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30662. */
  30663. class JUCE_API Drawable
  30664. {
  30665. protected:
  30666. /** The base class can't be instantiated directly.
  30667. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30668. */
  30669. Drawable();
  30670. public:
  30671. /** Destructor. */
  30672. virtual ~Drawable();
  30673. /** Creates a deep copy of this Drawable object.
  30674. Use this to create a new copy of this and any sub-objects in the tree.
  30675. */
  30676. virtual Drawable* createCopy() const = 0;
  30677. /** Renders this Drawable object.
  30678. @see drawWithin
  30679. */
  30680. void draw (Graphics& g, const float opacity,
  30681. const AffineTransform& transform = AffineTransform::identity) const;
  30682. /** Renders the Drawable at a given offset within the Graphics context.
  30683. The co-ordinates passed-in are used to translate the object relative to its own
  30684. origin before drawing it - this is basically a quick way of saying:
  30685. @code
  30686. draw (g, AffineTransform::translation (x, y)).
  30687. @endcode
  30688. */
  30689. void drawAt (Graphics& g,
  30690. const float x,
  30691. const float y,
  30692. const float opacity) const;
  30693. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30694. changing its aspect-ratio.
  30695. The object can placed arbitrarily within the rectangle based on a Justification type,
  30696. and can either be made as big as possible, or just reduced to fit.
  30697. @param g the graphics context to render onto
  30698. @param destX top-left of the target rectangle to fit it into
  30699. @param destY top-left of the target rectangle to fit it into
  30700. @param destWidth size of the target rectangle to fit the image into
  30701. @param destHeight size of the target rectangle to fit the image into
  30702. @param placement defines the alignment and rescaling to use to fit
  30703. this object within the target rectangle.
  30704. @param opacity the opacity to use, in the range 0 to 1.0
  30705. */
  30706. void drawWithin (Graphics& g,
  30707. const int destX,
  30708. const int destY,
  30709. const int destWidth,
  30710. const int destHeight,
  30711. const RectanglePlacement& placement,
  30712. const float opacity) const;
  30713. /** Holds the information needed when telling a drawable to render itself.
  30714. @see Drawable::draw
  30715. */
  30716. class RenderingContext
  30717. {
  30718. public:
  30719. RenderingContext (Graphics& g, const AffineTransform& transform, const float opacity) throw();
  30720. Graphics& g;
  30721. AffineTransform transform;
  30722. float opacity;
  30723. private:
  30724. const RenderingContext& operator= (const RenderingContext&);
  30725. };
  30726. /** Renders this Drawable object.
  30727. @see draw
  30728. */
  30729. virtual void render (const RenderingContext& context) const = 0;
  30730. /** Returns the smallest rectangle that can contain this Drawable object.
  30731. Co-ordinates are relative to the object's own origin.
  30732. */
  30733. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30734. /** Returns true if the given point is somewhere inside this Drawable.
  30735. Co-ordinates are relative to the object's own origin.
  30736. */
  30737. virtual bool hitTest (float x, float y) const = 0;
  30738. /** Returns the name given to this drawable.
  30739. @see setName
  30740. */
  30741. const String& getName() const throw() { return name; }
  30742. /** Assigns a name to this drawable. */
  30743. void setName (const String& newName) throw() { name = newName; }
  30744. /** Tries to turn some kind of image file into a drawable.
  30745. The data could be an image that the ImageFileFormat class understands, or it
  30746. could be SVG.
  30747. */
  30748. static Drawable* createFromImageData (const void* data, const int numBytes);
  30749. /** Tries to turn a stream containing some kind of image data into a drawable.
  30750. The data could be an image that the ImageFileFormat class understands, or it
  30751. could be SVG.
  30752. */
  30753. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30754. /** Tries to turn a file containing some kind of image data into a drawable.
  30755. The data could be an image that the ImageFileFormat class understands, or it
  30756. could be SVG.
  30757. */
  30758. static Drawable* createFromImageFile (const File& file);
  30759. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30760. into a Drawable tree.
  30761. The object returned must be deleted by the caller. If something goes wrong
  30762. while parsing, it may return 0.
  30763. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30764. implementation, but it can return the basic vector objects.
  30765. */
  30766. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30767. /**
  30768. */
  30769. static Drawable* readFromBinaryStream (InputStream& input);
  30770. /**
  30771. */
  30772. bool writeToBinaryStream (OutputStream& output) const;
  30773. /**
  30774. */
  30775. static Drawable* readFromXml (const XmlElement& xml);
  30776. /**
  30777. */
  30778. XmlElement* createXml() const;
  30779. /** @internal */
  30780. virtual bool readBinary (InputStream& input) = 0;
  30781. /** @internal */
  30782. virtual bool writeBinary (OutputStream& output) const = 0;
  30783. /** @internal */
  30784. virtual bool readXml (const XmlElement& xml) = 0;
  30785. /** @internal */
  30786. virtual void writeXml (XmlElement& xml) const = 0;
  30787. juce_UseDebuggingNewOperator
  30788. private:
  30789. Drawable (const Drawable&);
  30790. const Drawable& operator= (const Drawable&);
  30791. String name;
  30792. };
  30793. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30794. /********* End of inlined file: juce_Drawable.h *********/
  30795. #endif
  30796. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30797. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30798. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30799. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30800. /**
  30801. A drawable object which acts as a container for a set of other Drawables.
  30802. @see Drawable
  30803. */
  30804. class JUCE_API DrawableComposite : public Drawable
  30805. {
  30806. public:
  30807. /** Creates a composite Drawable.
  30808. */
  30809. DrawableComposite();
  30810. /** Destructor. */
  30811. virtual ~DrawableComposite();
  30812. /** Adds a new sub-drawable to this one.
  30813. This passes in a Drawable pointer for this object to look after. To add a copy
  30814. of a drawable, use the form of this method that takes a Drawable reference instead.
  30815. @param drawable the object to add - this will be deleted automatically
  30816. when no longer needed, so the caller mustn't keep any
  30817. pointers to it.
  30818. @param transform the transform to apply to this drawable when it's being
  30819. drawn
  30820. @param index where to insert it in the list of drawables. 0 is the back,
  30821. -1 is the front, or any value from 0 and getNumDrawables()
  30822. can be used
  30823. @see removeDrawable
  30824. */
  30825. void insertDrawable (Drawable* drawable,
  30826. const AffineTransform& transform = AffineTransform::identity,
  30827. const int index = -1);
  30828. /** Adds a new sub-drawable to this one.
  30829. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30830. for this object to look after, use the form of this method that takes a Drawable
  30831. pointer instead.
  30832. @param drawable the object to add - an internal copy will be made of this object
  30833. @param transform the transform to apply to this drawable when it's being
  30834. drawn
  30835. @param index where to insert it in the list of drawables. 0 is the back,
  30836. -1 is the front, or any value from 0 and getNumDrawables()
  30837. can be used
  30838. @see removeDrawable
  30839. */
  30840. void insertDrawable (const Drawable& drawable,
  30841. const AffineTransform& transform = AffineTransform::identity,
  30842. const int index = -1);
  30843. /** Deletes one of the Drawable objects.
  30844. @param index the index of the drawable to delete, between 0
  30845. and (getNumDrawables() - 1).
  30846. @param deleteDrawable if this is true, the drawable that is removed will also
  30847. be deleted. If false, it'll just be removed.
  30848. @see insertDrawable, getNumDrawables
  30849. */
  30850. void removeDrawable (const int index, const bool deleteDrawable = true);
  30851. /** Returns the number of drawables contained inside this one.
  30852. @see getDrawable
  30853. */
  30854. int getNumDrawables() const throw() { return drawables.size(); }
  30855. /** Returns one of the drawables that are contained in this one.
  30856. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30857. to find it.
  30858. The pointer returned is managed by this object and will be deleted when no longer
  30859. needed, so be careful what you do with it.
  30860. @see getNumDrawables
  30861. */
  30862. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30863. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30864. The pointer returned is managed by this object and will be deleted when no longer
  30865. needed, so be careful what you do with it.
  30866. @see getNumDrawables
  30867. */
  30868. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30869. /** Brings one of the Drawables to the front.
  30870. @param index the index of the drawable to move, between 0
  30871. and (getNumDrawables() - 1).
  30872. @see insertDrawable, getNumDrawables
  30873. */
  30874. void bringToFront (const int index);
  30875. /** @internal */
  30876. void render (const Drawable::RenderingContext& context) const;
  30877. /** @internal */
  30878. void getBounds (float& x, float& y, float& width, float& height) const;
  30879. /** @internal */
  30880. bool hitTest (float x, float y) const;
  30881. /** @internal */
  30882. Drawable* createCopy() const;
  30883. /** @internal */
  30884. bool readBinary (InputStream& input);
  30885. /** @internal */
  30886. bool writeBinary (OutputStream& output) const;
  30887. /** @internal */
  30888. bool readXml (const XmlElement& xml);
  30889. /** @internal */
  30890. void writeXml (XmlElement& xml) const;
  30891. juce_UseDebuggingNewOperator
  30892. private:
  30893. OwnedArray <Drawable> drawables;
  30894. OwnedArray <AffineTransform> transforms;
  30895. DrawableComposite (const DrawableComposite&);
  30896. const DrawableComposite& operator= (const DrawableComposite&);
  30897. };
  30898. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30899. /********* End of inlined file: juce_DrawableComposite.h *********/
  30900. #endif
  30901. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30902. /********* Start of inlined file: juce_DrawableImage.h *********/
  30903. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30904. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30905. /**
  30906. A drawable object which is a bitmap image.
  30907. @see Drawable
  30908. */
  30909. class JUCE_API DrawableImage : public Drawable
  30910. {
  30911. public:
  30912. DrawableImage();
  30913. /** Destructor. */
  30914. virtual ~DrawableImage();
  30915. /** Sets the image that this drawable will render.
  30916. An internal copy is made of the image passed-in. If you want to provide an
  30917. image that this object can take charge of without needing to create a copy,
  30918. use the other setImage() method.
  30919. */
  30920. void setImage (const Image& imageToCopy);
  30921. /** Sets the image that this drawable will render.
  30922. An internal copy of this will not be made, so the caller mustn't delete
  30923. the image while it's still being used by this object.
  30924. A good way to use this is with the ImageCache - if you create an image
  30925. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30926. it'll be released neatly with its reference count being decreased.
  30927. @param imageToUse the image to render
  30928. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30929. then the image will be deleted when this object no longer
  30930. needs it - unless the image was created by the ImageCache,
  30931. in which case it will be released with ImageCache::release().
  30932. */
  30933. void setImage (Image* imageToUse,
  30934. const bool releaseWhenNotNeeded);
  30935. /** Returns the current image. */
  30936. Image* getImage() const throw() { return image; }
  30937. /** Clears (and possibly deletes) the currently set image. */
  30938. void clearImage();
  30939. /** Sets the opacity to use when drawing the image. */
  30940. void setOpacity (const float newOpacity);
  30941. /** Returns the image's opacity. */
  30942. float getOpacity() const throw() { return opacity; }
  30943. /** Sets a colour to draw over the image's alpha channel.
  30944. By default this is transparent so isn't drawn, but if you set a non-transparent
  30945. colour here, then it will be overlaid on the image, using the image's alpha
  30946. channel as a mask.
  30947. This is handy for doing things like darkening or lightening an image by overlaying
  30948. it with semi-transparent black or white.
  30949. */
  30950. void setOverlayColour (const Colour& newOverlayColour);
  30951. /** Returns the overlay colour. */
  30952. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30953. /** @internal */
  30954. void render (const Drawable::RenderingContext& context) const;
  30955. /** @internal */
  30956. void getBounds (float& x, float& y, float& width, float& height) const;
  30957. /** @internal */
  30958. bool hitTest (float x, float y) const;
  30959. /** @internal */
  30960. Drawable* createCopy() const;
  30961. /** @internal */
  30962. bool readBinary (InputStream& input);
  30963. /** @internal */
  30964. bool writeBinary (OutputStream& output) const;
  30965. /** @internal */
  30966. bool readXml (const XmlElement& xml);
  30967. /** @internal */
  30968. void writeXml (XmlElement& xml) const;
  30969. juce_UseDebuggingNewOperator
  30970. private:
  30971. Image* image;
  30972. bool canDeleteImage;
  30973. float opacity;
  30974. Colour overlayColour;
  30975. DrawableImage (const DrawableImage&);
  30976. const DrawableImage& operator= (const DrawableImage&);
  30977. };
  30978. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30979. /********* End of inlined file: juce_DrawableImage.h *********/
  30980. #endif
  30981. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30982. /********* Start of inlined file: juce_DrawableText.h *********/
  30983. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30984. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30985. /**
  30986. A drawable object which renders a line of text.
  30987. @see Drawable
  30988. */
  30989. class JUCE_API DrawableText : public Drawable
  30990. {
  30991. public:
  30992. /** Creates a DrawableText object. */
  30993. DrawableText();
  30994. /** Destructor. */
  30995. virtual ~DrawableText();
  30996. /** Sets the block of text to render */
  30997. void setText (const GlyphArrangement& newText);
  30998. /** Sets a single line of text to render.
  30999. This is a convenient method of adding a single line - for
  31000. more complex text, use the setText() that takes a
  31001. GlyphArrangement instead.
  31002. */
  31003. void setText (const String& newText, const Font& fontToUse);
  31004. /** Returns the text arrangement that was set with setText(). */
  31005. const GlyphArrangement& getText() const throw() { return text; }
  31006. /** Sets the colour of the text. */
  31007. void setColour (const Colour& newColour);
  31008. /** Returns the current text colour. */
  31009. const Colour& getColour() const throw() { return colour; }
  31010. /** @internal */
  31011. void render (const Drawable::RenderingContext& context) const;
  31012. /** @internal */
  31013. void getBounds (float& x, float& y, float& width, float& height) const;
  31014. /** @internal */
  31015. bool hitTest (float x, float y) const;
  31016. /** @internal */
  31017. Drawable* createCopy() const;
  31018. /** @internal */
  31019. bool readBinary (InputStream& input);
  31020. /** @internal */
  31021. bool writeBinary (OutputStream& output) const;
  31022. /** @internal */
  31023. bool readXml (const XmlElement& xml);
  31024. /** @internal */
  31025. void writeXml (XmlElement& xml) const;
  31026. juce_UseDebuggingNewOperator
  31027. private:
  31028. GlyphArrangement text;
  31029. Colour colour;
  31030. DrawableText (const DrawableText&);
  31031. const DrawableText& operator= (const DrawableText&);
  31032. };
  31033. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  31034. /********* End of inlined file: juce_DrawableText.h *********/
  31035. #endif
  31036. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  31037. /********* Start of inlined file: juce_DrawablePath.h *********/
  31038. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  31039. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  31040. /**
  31041. A drawable object which renders a filled or outlined shape.
  31042. @see Drawable
  31043. */
  31044. class JUCE_API DrawablePath : public Drawable
  31045. {
  31046. public:
  31047. /** Creates a DrawablePath.
  31048. */
  31049. DrawablePath();
  31050. /** Destructor. */
  31051. virtual ~DrawablePath();
  31052. /** Changes the path that will be drawn.
  31053. @see setFillColour, setStrokeType
  31054. */
  31055. void setPath (const Path& newPath) throw();
  31056. /** Returns the current path. */
  31057. const Path& getPath() const throw() { return path; }
  31058. /** Sets a fill type for the path.
  31059. This colour is used to fill the path - if you don't want the path to be
  31060. filled (e.g. if you're just drawing an outline), set this to a transparent
  31061. colour.
  31062. @see setPath, setStrokeFill
  31063. */
  31064. void setFill (const FillType& newFill) throw();
  31065. /** Returns the current fill type.
  31066. @see setFill
  31067. */
  31068. const FillType& getFill() const throw() { return mainFill; }
  31069. /** Sets the fill type with which the outline will be drawn.
  31070. @see setFill
  31071. */
  31072. void setStrokeFill (const FillType& newStrokeFill) throw();
  31073. /** Returns the current stroke fill.
  31074. @see setStrokeFill
  31075. */
  31076. const FillType& getStrokeFill() const throw() { return strokeFill; }
  31077. /** Changes the properties of the outline that will be drawn around the path.
  31078. If the stroke has 0 thickness, no stroke will be drawn.
  31079. @see setStrokeThickness, setStrokeColour
  31080. */
  31081. void setStrokeType (const PathStrokeType& newStrokeType) throw();
  31082. /** Changes the stroke thickness.
  31083. This is a shortcut for calling setStrokeType.
  31084. */
  31085. void setStrokeThickness (const float newThickness) throw();
  31086. /** Returns the current outline style. */
  31087. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  31088. /** @internal */
  31089. void render (const Drawable::RenderingContext& context) const;
  31090. /** @internal */
  31091. void getBounds (float& x, float& y, float& width, float& height) const;
  31092. /** @internal */
  31093. bool hitTest (float x, float y) const;
  31094. /** @internal */
  31095. Drawable* createCopy() const;
  31096. /** @internal */
  31097. bool readBinary (InputStream& input);
  31098. /** @internal */
  31099. bool writeBinary (OutputStream& output) const;
  31100. /** @internal */
  31101. bool readXml (const XmlElement& xml);
  31102. /** @internal */
  31103. void writeXml (XmlElement& xml) const;
  31104. juce_UseDebuggingNewOperator
  31105. private:
  31106. Path path, stroke;
  31107. FillType mainFill, strokeFill;
  31108. PathStrokeType strokeType;
  31109. void updateOutline();
  31110. DrawablePath (const DrawablePath&);
  31111. const DrawablePath& operator= (const DrawablePath&);
  31112. };
  31113. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  31114. /********* End of inlined file: juce_DrawablePath.h *********/
  31115. #endif
  31116. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  31117. #endif
  31118. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  31119. #endif
  31120. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  31121. #endif
  31122. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  31123. #endif
  31124. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31125. /********* Start of inlined file: juce_ArrowButton.h *********/
  31126. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31127. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31128. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  31129. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31130. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31131. /**
  31132. An effect filter that adds a drop-shadow behind the image's content.
  31133. (This will only work on images/components that aren't opaque, of course).
  31134. When added to a component, this effect will draw a soft-edged
  31135. shadow based on what gets drawn inside it. The shadow will also
  31136. be applied to the component's children.
  31137. For speed, this doesn't use a proper gaussian blur, but cheats by
  31138. using a simple bilinear filter. If you need a really high-quality
  31139. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31140. @see Component::setComponentEffect
  31141. */
  31142. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31143. {
  31144. public:
  31145. /** Creates a default drop-shadow effect.
  31146. To customise the shadow's appearance, use the setShadowProperties()
  31147. method.
  31148. */
  31149. DropShadowEffect();
  31150. /** Destructor. */
  31151. ~DropShadowEffect();
  31152. /** Sets up parameters affecting the shadow's appearance.
  31153. @param newRadius the (approximate) radius of the blur used
  31154. @param newOpacity the opacity with which the shadow is rendered
  31155. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31156. component's contents
  31157. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31158. component's contents
  31159. */
  31160. void setShadowProperties (const float newRadius,
  31161. const float newOpacity,
  31162. const int newShadowOffsetX,
  31163. const int newShadowOffsetY);
  31164. /** @internal */
  31165. void applyEffect (Image& sourceImage, Graphics& destContext);
  31166. juce_UseDebuggingNewOperator
  31167. private:
  31168. int offsetX, offsetY;
  31169. float radius, opacity;
  31170. };
  31171. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31172. /********* End of inlined file: juce_DropShadowEffect.h *********/
  31173. /**
  31174. A button with an arrow in it.
  31175. @see Button
  31176. */
  31177. class JUCE_API ArrowButton : public Button
  31178. {
  31179. public:
  31180. /** Creates an ArrowButton.
  31181. @param buttonName the name to give the button
  31182. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31183. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31184. @param arrowColour the colour to use for the arrow
  31185. */
  31186. ArrowButton (const String& buttonName,
  31187. float arrowDirection,
  31188. const Colour& arrowColour);
  31189. /** Destructor. */
  31190. ~ArrowButton();
  31191. juce_UseDebuggingNewOperator
  31192. protected:
  31193. /** @internal */
  31194. void paintButton (Graphics& g,
  31195. bool isMouseOverButton,
  31196. bool isButtonDown);
  31197. /** @internal */
  31198. void buttonStateChanged();
  31199. private:
  31200. Colour colour;
  31201. DropShadowEffect shadow;
  31202. Path path;
  31203. int offset;
  31204. ArrowButton (const ArrowButton&);
  31205. const ArrowButton& operator= (const ArrowButton&);
  31206. };
  31207. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31208. /********* End of inlined file: juce_ArrowButton.h *********/
  31209. #endif
  31210. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31211. #endif
  31212. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31213. /********* Start of inlined file: juce_DrawableButton.h *********/
  31214. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31215. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31216. /**
  31217. A button that displays a Drawable.
  31218. Up to three Drawable objects can be given to this button, to represent the
  31219. 'normal', 'over' and 'down' states.
  31220. @see Button
  31221. */
  31222. class JUCE_API DrawableButton : public Button
  31223. {
  31224. public:
  31225. enum ButtonStyle
  31226. {
  31227. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  31228. ImageRaw, /**< The button will just display the images in their normal size and position.
  31229. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  31230. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  31231. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  31232. };
  31233. /** Creates a DrawableButton.
  31234. After creating one of these, use setImages() to specify the drawables to use.
  31235. @param buttonName the name to give the component
  31236. @param buttonStyle the layout to use
  31237. @see ButtonStyle, setButtonStyle, setImages
  31238. */
  31239. DrawableButton (const String& buttonName,
  31240. const ButtonStyle buttonStyle);
  31241. /** Destructor. */
  31242. ~DrawableButton();
  31243. /** Sets up the images to draw for the various button states.
  31244. The button will keep its own internal copies of these drawables.
  31245. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  31246. will be made of the object passed-in if it is non-zero.
  31247. @param overImage the thing to draw for the button's 'over' state - if this is
  31248. zero, the button's normal image will be used when the mouse is
  31249. over it. An internal copy will be made of the object passed-in
  31250. if it is non-zero.
  31251. @param downImage the thing to draw for the button's 'down' state - if this is
  31252. zero, the 'over' image will be used instead (or the normal image
  31253. as a last resort). An internal copy will be made of the object
  31254. passed-in if it is non-zero.
  31255. @param disabledImage an image to draw when the button is disabled. If this is zero,
  31256. the normal image will be drawn with a reduced opacity instead.
  31257. An internal copy will be made of the object passed-in if it is
  31258. non-zero.
  31259. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  31260. state is 'on'. If this is 0, the normal image is used instead
  31261. @param overImageOn same as the overImage, but this is used when the button's toggle
  31262. state is 'on'. If this is 0, the normalImageOn is drawn instead
  31263. @param downImageOn same as the downImage, but this is used when the button's toggle
  31264. state is 'on'. If this is 0, the overImageOn is drawn instead
  31265. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  31266. state is 'on'. If this is 0, the normal image will be drawn instead
  31267. with a reduced opacity
  31268. */
  31269. void setImages (const Drawable* normalImage,
  31270. const Drawable* overImage = 0,
  31271. const Drawable* downImage = 0,
  31272. const Drawable* disabledImage = 0,
  31273. const Drawable* normalImageOn = 0,
  31274. const Drawable* overImageOn = 0,
  31275. const Drawable* downImageOn = 0,
  31276. const Drawable* disabledImageOn = 0);
  31277. /** Changes the button's style.
  31278. @see ButtonStyle
  31279. */
  31280. void setButtonStyle (const ButtonStyle newStyle);
  31281. /** Changes the button's background colours.
  31282. The toggledOffColour is the colour to use when the button's toggle state
  31283. is off, and toggledOnColour when it's on.
  31284. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  31285. used to fill the background of the component.
  31286. For an ImageOnButtonBackground style, the colour is used to draw the
  31287. button's lozenge shape and exactly how the colour's used will depend
  31288. on the LookAndFeel.
  31289. */
  31290. void setBackgroundColours (const Colour& toggledOffColour,
  31291. const Colour& toggledOnColour);
  31292. /** Returns the current background colour being used.
  31293. @see setBackgroundColour
  31294. */
  31295. const Colour& getBackgroundColour() const throw();
  31296. /** Gives the button an optional amount of space around the edge of the drawable.
  31297. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  31298. ones on a button background. If the button is too small for the given gap, a
  31299. smaller gap will be used.
  31300. By default there's a gap of about 3 pixels.
  31301. */
  31302. void setEdgeIndent (const int numPixelsIndent);
  31303. /** Returns the image that the button is currently displaying. */
  31304. const Drawable* getCurrentImage() const throw();
  31305. const Drawable* getNormalImage() const throw();
  31306. const Drawable* getOverImage() const throw();
  31307. const Drawable* getDownImage() const throw();
  31308. juce_UseDebuggingNewOperator
  31309. protected:
  31310. /** @internal */
  31311. void paintButton (Graphics& g,
  31312. bool isMouseOverButton,
  31313. bool isButtonDown);
  31314. private:
  31315. ButtonStyle style;
  31316. Drawable* normalImage;
  31317. Drawable* overImage;
  31318. Drawable* downImage;
  31319. Drawable* disabledImage;
  31320. Drawable* normalImageOn;
  31321. Drawable* overImageOn;
  31322. Drawable* downImageOn;
  31323. Drawable* disabledImageOn;
  31324. Colour backgroundOff, backgroundOn;
  31325. int edgeIndent;
  31326. void deleteImages();
  31327. DrawableButton (const DrawableButton&);
  31328. const DrawableButton& operator= (const DrawableButton&);
  31329. };
  31330. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31331. /********* End of inlined file: juce_DrawableButton.h *********/
  31332. #endif
  31333. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31334. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  31335. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31336. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31337. /**
  31338. A button showing an underlined weblink, that will launch the link
  31339. when it's clicked.
  31340. @see Button
  31341. */
  31342. class JUCE_API HyperlinkButton : public Button
  31343. {
  31344. public:
  31345. /** Creates a HyperlinkButton.
  31346. @param linkText the text that will be displayed in the button - this is
  31347. also set as the Component's name, but the text can be
  31348. changed later with the Button::getButtonText() method
  31349. @param linkURL the URL to launch when the user clicks the button
  31350. */
  31351. HyperlinkButton (const String& linkText,
  31352. const URL& linkURL);
  31353. /** Destructor. */
  31354. ~HyperlinkButton();
  31355. /** Changes the font to use for the text.
  31356. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  31357. to match the size of the component.
  31358. */
  31359. void setFont (const Font& newFont,
  31360. const bool resizeToMatchComponentHeight,
  31361. const Justification& justificationType = Justification::horizontallyCentred);
  31362. /** A set of colour IDs to use to change the colour of various aspects of the link.
  31363. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31364. methods.
  31365. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31366. */
  31367. enum ColourIds
  31368. {
  31369. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  31370. };
  31371. /** Changes the URL that the button will trigger. */
  31372. void setURL (const URL& newURL) throw();
  31373. /** Returns the URL that the button will trigger. */
  31374. const URL& getURL() const throw() { return url; }
  31375. /** Resizes the button horizontally to fit snugly around the text.
  31376. This won't affect the button's height.
  31377. */
  31378. void changeWidthToFitText();
  31379. juce_UseDebuggingNewOperator
  31380. protected:
  31381. /** @internal */
  31382. void clicked();
  31383. /** @internal */
  31384. void colourChanged();
  31385. /** @internal */
  31386. void paintButton (Graphics& g,
  31387. bool isMouseOverButton,
  31388. bool isButtonDown);
  31389. private:
  31390. URL url;
  31391. Font font;
  31392. bool resizeFont;
  31393. Justification justification;
  31394. const Font getFontToUse() const;
  31395. HyperlinkButton (const HyperlinkButton&);
  31396. const HyperlinkButton& operator= (const HyperlinkButton&);
  31397. };
  31398. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31399. /********* End of inlined file: juce_HyperlinkButton.h *********/
  31400. #endif
  31401. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31402. /********* Start of inlined file: juce_ImageButton.h *********/
  31403. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31404. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  31405. /**
  31406. As the title suggests, this is a button containing an image.
  31407. The colour and transparency of the image can be set to vary when the
  31408. button state changes.
  31409. @see Button, ShapeButton, TextButton
  31410. */
  31411. class JUCE_API ImageButton : public Button
  31412. {
  31413. public:
  31414. /** Creates an ImageButton.
  31415. Use setImage() to specify the image to use. The colours and opacities that
  31416. are specified here can be changed later using setDrawingOptions().
  31417. @param name the name to give the component
  31418. */
  31419. ImageButton (const String& name);
  31420. /** Destructor. */
  31421. ~ImageButton();
  31422. /** Sets up the images to draw in various states.
  31423. Important! Bear in mind that if you pass the same image in for more than one of
  31424. these parameters, this button will delete it (or release from the ImageCache)
  31425. multiple times!
  31426. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  31427. resized to the same dimensions as the normal image
  31428. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  31429. button when the button's size changes
  31430. @param preserveImageProportions if true then any rescaling of the image to fit
  31431. the button will keep the image's x and y proportions
  31432. correct - i.e. it won't distort its shape, although
  31433. this might create gaps around the edges
  31434. @param normalImage the image to use when the button is in its normal state. The
  31435. image passed in will be deleted (or released if it
  31436. was created by the ImageCache class) when the
  31437. button no longer needs it.
  31438. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  31439. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  31440. normal image - if this colour is transparent, no overlay
  31441. will be drawn. The overlay will be drawn over the top of the
  31442. image, so you can basically add a solid or semi-transparent
  31443. colour to the image to brighten or darken it
  31444. @param overImage the image to use when the mouse is over the button. If
  31445. you want to use the same image as was set in the normalImage
  31446. parameter, this value can be 0. As for normalImage, it
  31447. will be deleted or released by the button when no longer
  31448. needed
  31449. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  31450. is over the button
  31451. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  31452. image when the mouse is over - if this colour is transparent,
  31453. no overlay will be drawn
  31454. @param downImage an image to use when the button is pressed down. If set
  31455. to zero, the 'over' image will be drawn instead (or the
  31456. normal image if there isn't an 'over' image either). This
  31457. image will be deleted or released by the button when no
  31458. longer needed
  31459. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  31460. is pressed
  31461. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  31462. image when the button is pressed down - if this colour is
  31463. transparent, no overlay will be drawn
  31464. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  31465. whenever it's inside the button's bounding rectangle. If
  31466. set to values higher than 0, the mouse will only be
  31467. considered to be over the image when the value of the
  31468. image's alpha channel at that position is greater than
  31469. this level.
  31470. */
  31471. void setImages (const bool resizeButtonNowToFitThisImage,
  31472. const bool rescaleImagesWhenButtonSizeChanges,
  31473. const bool preserveImageProportions,
  31474. Image* const normalImage,
  31475. const float imageOpacityWhenNormal,
  31476. const Colour& overlayColourWhenNormal,
  31477. Image* const overImage,
  31478. const float imageOpacityWhenOver,
  31479. const Colour& overlayColourWhenOver,
  31480. Image* const downImage,
  31481. const float imageOpacityWhenDown,
  31482. const Colour& overlayColourWhenDown,
  31483. const float hitTestAlphaThreshold = 0.0f);
  31484. /** Returns the currently set 'normal' image. */
  31485. Image* getNormalImage() const throw();
  31486. /** Returns the image that's drawn when the mouse is over the button.
  31487. If an 'over' image has been set, this will return it; otherwise it'll
  31488. just return the normal image.
  31489. */
  31490. Image* getOverImage() const throw();
  31491. /** Returns the image that's drawn when the button is held down.
  31492. If a 'down' image has been set, this will return it; otherwise it'll
  31493. return the 'over' image or normal image, depending on what's available.
  31494. */
  31495. Image* getDownImage() const throw();
  31496. juce_UseDebuggingNewOperator
  31497. protected:
  31498. /** @internal */
  31499. bool hitTest (int x, int y);
  31500. /** @internal */
  31501. void paintButton (Graphics& g,
  31502. bool isMouseOverButton,
  31503. bool isButtonDown);
  31504. private:
  31505. bool scaleImageToFit, preserveProportions;
  31506. unsigned char alphaThreshold;
  31507. int imageX, imageY, imageW, imageH;
  31508. Image* normalImage;
  31509. Image* overImage;
  31510. Image* downImage;
  31511. float normalOpacity, overOpacity, downOpacity;
  31512. Colour normalOverlay, overOverlay, downOverlay;
  31513. Image* getCurrentImage() const;
  31514. void deleteImages();
  31515. ImageButton (const ImageButton&);
  31516. const ImageButton& operator= (const ImageButton&);
  31517. };
  31518. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  31519. /********* End of inlined file: juce_ImageButton.h *********/
  31520. #endif
  31521. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31522. /********* Start of inlined file: juce_ShapeButton.h *********/
  31523. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31524. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  31525. /**
  31526. A button that contains a filled shape.
  31527. @see Button, ImageButton, TextButton, ArrowButton
  31528. */
  31529. class JUCE_API ShapeButton : public Button
  31530. {
  31531. public:
  31532. /** Creates a ShapeButton.
  31533. @param name a name to give the component - see Component::setName()
  31534. @param normalColour the colour to fill the shape with when the mouse isn't over
  31535. @param overColour the colour to use when the mouse is over the shape
  31536. @param downColour the colour to use when the button is in the pressed-down state
  31537. */
  31538. ShapeButton (const String& name,
  31539. const Colour& normalColour,
  31540. const Colour& overColour,
  31541. const Colour& downColour);
  31542. /** Destructor. */
  31543. ~ShapeButton();
  31544. /** Sets the shape to use.
  31545. @param newShape the shape to use
  31546. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  31547. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  31548. the button is resized
  31549. @param hasDropShadow if true, the button will be given a drop-shadow effect
  31550. */
  31551. void setShape (const Path& newShape,
  31552. const bool resizeNowToFitThisShape,
  31553. const bool maintainShapeProportions,
  31554. const bool hasDropShadow);
  31555. /** Set the colours to use for drawing the shape.
  31556. @param normalColour the colour to fill the shape with when the mouse isn't over
  31557. @param overColour the colour to use when the mouse is over the shape
  31558. @param downColour the colour to use when the button is in the pressed-down state
  31559. */
  31560. void setColours (const Colour& normalColour,
  31561. const Colour& overColour,
  31562. const Colour& downColour);
  31563. /** Sets up an outline to draw around the shape.
  31564. @param outlineColour the colour to use
  31565. @param outlineStrokeWidth the thickness of line to draw
  31566. */
  31567. void setOutline (const Colour& outlineColour,
  31568. const float outlineStrokeWidth);
  31569. juce_UseDebuggingNewOperator
  31570. protected:
  31571. /** @internal */
  31572. void paintButton (Graphics& g,
  31573. bool isMouseOverButton,
  31574. bool isButtonDown);
  31575. private:
  31576. Colour normalColour, overColour, downColour, outlineColour;
  31577. DropShadowEffect shadow;
  31578. Path shape;
  31579. bool maintainShapeProportions;
  31580. float outlineWidth;
  31581. ShapeButton (const ShapeButton&);
  31582. const ShapeButton& operator= (const ShapeButton&);
  31583. };
  31584. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31585. /********* End of inlined file: juce_ShapeButton.h *********/
  31586. #endif
  31587. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31588. #endif
  31589. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31590. /********* Start of inlined file: juce_ToggleButton.h *********/
  31591. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31592. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31593. /**
  31594. A button that can be toggled on/off.
  31595. All buttons can be toggle buttons, but this lets you create one of the
  31596. standard ones which has a tick-box and a text label next to it.
  31597. @see Button, DrawableButton, TextButton
  31598. */
  31599. class JUCE_API ToggleButton : public Button
  31600. {
  31601. public:
  31602. /** Creates a ToggleButton.
  31603. @param buttonText the text to put in the button (the component's name is also
  31604. initially set to this string, but these can be changed later
  31605. using the setName() and setButtonText() methods)
  31606. */
  31607. ToggleButton (const String& buttonText);
  31608. /** Destructor. */
  31609. ~ToggleButton();
  31610. /** Resizes the button to fit neatly around its current text.
  31611. The button's height won't be affected, only its width.
  31612. */
  31613. void changeWidthToFitText();
  31614. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31615. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31616. methods.
  31617. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31618. */
  31619. enum ColourIds
  31620. {
  31621. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31622. };
  31623. juce_UseDebuggingNewOperator
  31624. protected:
  31625. /** @internal */
  31626. void paintButton (Graphics& g,
  31627. bool isMouseOverButton,
  31628. bool isButtonDown);
  31629. /** @internal */
  31630. void colourChanged();
  31631. private:
  31632. ToggleButton (const ToggleButton&);
  31633. const ToggleButton& operator= (const ToggleButton&);
  31634. };
  31635. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31636. /********* End of inlined file: juce_ToggleButton.h *********/
  31637. #endif
  31638. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31639. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31640. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31641. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31642. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31643. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31644. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31645. /********* Start of inlined file: juce_Toolbar.h *********/
  31646. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31647. #define __JUCE_TOOLBAR_JUCEHEADER__
  31648. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31649. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31650. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31651. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31652. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31653. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31654. /**
  31655. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31656. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31657. derive your component from this class, and make sure that it is somewhere inside a
  31658. DragAndDropContainer component.
  31659. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31660. the operating system onto your component, you don't need any of these classes: instead
  31661. see the FileDragAndDropTarget class.
  31662. @see DragAndDropContainer, FileDragAndDropTarget
  31663. */
  31664. class JUCE_API DragAndDropTarget
  31665. {
  31666. public:
  31667. /** Destructor. */
  31668. virtual ~DragAndDropTarget() {}
  31669. /** Callback to check whether this target is interested in the type of object being
  31670. dragged.
  31671. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31672. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31673. @returns true if this component wants to receive the other callbacks regarging this
  31674. type of object; if it returns false, no other callbacks will be made.
  31675. */
  31676. virtual bool isInterestedInDragSource (const String& sourceDescription,
  31677. Component* sourceComponent) = 0;
  31678. /** Callback to indicate that something is being dragged over this component.
  31679. This gets called when the user moves the mouse into this component while dragging
  31680. something.
  31681. Use this callback as a trigger to make your component repaint itself to give the
  31682. user feedback about whether the item can be dropped here or not.
  31683. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31684. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31685. @param x the mouse x position, relative to this component
  31686. @param y the mouse y position, relative to this component
  31687. @see itemDragExit
  31688. */
  31689. virtual void itemDragEnter (const String& sourceDescription,
  31690. Component* sourceComponent,
  31691. int x,
  31692. int y);
  31693. /** Callback to indicate that the user is dragging something over this component.
  31694. This gets called when the user moves the mouse over this component while dragging
  31695. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  31696. this lets you know what happens in-between.
  31697. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31698. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31699. @param x the mouse x position, relative to this component
  31700. @param y the mouse y position, relative to this component
  31701. */
  31702. virtual void itemDragMove (const String& sourceDescription,
  31703. Component* sourceComponent,
  31704. int x,
  31705. int y);
  31706. /** Callback to indicate that something has been dragged off the edge of this component.
  31707. This gets called when the user moves the mouse out of this component while dragging
  31708. something.
  31709. If you've used itemDragEnter() to repaint your component and give feedback, use this
  31710. as a signal to repaint it in its normal state.
  31711. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31712. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31713. @see itemDragEnter
  31714. */
  31715. virtual void itemDragExit (const String& sourceDescription,
  31716. Component* sourceComponent);
  31717. /** Callback to indicate that the user has dropped something onto this component.
  31718. When the user drops an item this get called, and you can use the description to
  31719. work out whether your object wants to deal with it or not.
  31720. Note that after this is called, the itemDragExit method may not be called, so you should
  31721. clean up in here if there's anything you need to do when the drag finishes.
  31722. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31723. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31724. @param x the mouse x position, relative to this component
  31725. @param y the mouse y position, relative to this component
  31726. */
  31727. virtual void itemDropped (const String& sourceDescription,
  31728. Component* sourceComponent,
  31729. int x,
  31730. int y) = 0;
  31731. /** Overriding this allows the target to tell the drag container whether to
  31732. draw the drag image while the cursor is over it.
  31733. By default it returns true, but if you return false, then the normal drag
  31734. image will not be shown when the cursor is over this target.
  31735. */
  31736. virtual bool shouldDrawDragImageWhenOver();
  31737. };
  31738. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31739. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  31740. /**
  31741. Enables drag-and-drop behaviour for a component and all its sub-components.
  31742. For a component to be able to make or receive drag-and-drop events, one of its parent
  31743. components must derive from this class. It's probably best for the top-level
  31744. component to implement it.
  31745. Then to start a drag operation, any sub-component can just call the startDragging()
  31746. method, and this object will take over, tracking the mouse and sending appropriate
  31747. callbacks to any child components derived from DragAndDropTarget which the mouse
  31748. moves over.
  31749. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31750. the operating system onto your component, you don't need any of these classes: you can do this
  31751. simply by overriding Component::filesDropped().
  31752. @see DragAndDropTarget
  31753. */
  31754. class JUCE_API DragAndDropContainer
  31755. {
  31756. public:
  31757. /** Creates a DragAndDropContainer.
  31758. The object that derives from this class must also be a Component.
  31759. */
  31760. DragAndDropContainer();
  31761. /** Destructor. */
  31762. virtual ~DragAndDropContainer();
  31763. /** Begins a drag-and-drop operation.
  31764. This starts a drag-and-drop operation - call it when the user drags the
  31765. mouse in your drag-source component, and this object will track mouse
  31766. movements until the user lets go of the mouse button, and will send
  31767. appropriate messages to DragAndDropTarget objects that the mouse moves
  31768. over.
  31769. findParentDragContainerFor() is a handy method to call to find the
  31770. drag container to use for a component.
  31771. @param sourceDescription a string to use as the description of the thing being
  31772. dragged - this will be passed to the objects that might be
  31773. dropped-onto so they can decide if they want to handle it or
  31774. not
  31775. @param sourceComponent the component that is being dragged
  31776. @param dragImage the image to drag around underneath the mouse. If this is
  31777. zero, a snapshot of the sourceComponent will be used instead. An
  31778. image passed-in will be deleted by this object when no longer
  31779. needed.
  31780. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  31781. window, and can be dragged to DragAndDropTargets that are the
  31782. children of components other than this one.
  31783. */
  31784. void startDragging (const String& sourceDescription,
  31785. Component* sourceComponent,
  31786. Image* dragImage = 0,
  31787. const bool allowDraggingToOtherJuceWindows = false);
  31788. /** Returns true if something is currently being dragged. */
  31789. bool isDragAndDropActive() const;
  31790. /** Returns the description of the thing that's currently being dragged.
  31791. If nothing's being dragged, this will return an empty string, otherwise it's the
  31792. string that was passed into startDragging().
  31793. @see startDragging
  31794. */
  31795. const String getCurrentDragDescription() const;
  31796. /** Utility to find the DragAndDropContainer for a given Component.
  31797. This will search up this component's parent hierarchy looking for the first
  31798. parent component which is a DragAndDropContainer.
  31799. It's useful when a component wants to call startDragging but doesn't know
  31800. the DragAndDropContainer it should to use.
  31801. Obviously this may return 0 if it doesn't find a suitable component.
  31802. */
  31803. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  31804. /** This performs a synchronous drag-and-drop of a set of files to some external
  31805. application.
  31806. You can call this function in response to a mouseDrag callback, and it will
  31807. block, running its own internal message loop and tracking the mouse, while it
  31808. uses a native operating system drag-and-drop operation to move or copy some
  31809. files to another application.
  31810. @param files a list of filenames to drag
  31811. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  31812. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  31813. @returns true if the files were successfully dropped somewhere, or false if it
  31814. was interrupted
  31815. @see performExternalDragDropOfText
  31816. */
  31817. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  31818. /** This performs a synchronous drag-and-drop of a block of text to some external
  31819. application.
  31820. You can call this function in response to a mouseDrag callback, and it will
  31821. block, running its own internal message loop and tracking the mouse, while it
  31822. uses a native operating system drag-and-drop operation to move or copy some
  31823. text to another application.
  31824. @param text the text to copy
  31825. @returns true if the text was successfully dropped somewhere, or false if it
  31826. was interrupted
  31827. @see performExternalDragDropOfFiles
  31828. */
  31829. static bool performExternalDragDropOfText (const String& text);
  31830. juce_UseDebuggingNewOperator
  31831. protected:
  31832. /** Override this if you want to be able to perform an external drag a set of files
  31833. when the user drags outside of this container component.
  31834. This method will be called when a drag operation moves outside the Juce-based window,
  31835. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31836. to the array passed in, and return true.
  31837. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31838. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31839. @param files on return, the filenames you want to drag
  31840. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31841. it must make a copy of them (see the performExternalDragDropOfFiles()
  31842. method)
  31843. @see performExternalDragDropOfFiles
  31844. */
  31845. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31846. Component* dragSourceComponent,
  31847. StringArray& files,
  31848. bool& canMoveFiles);
  31849. private:
  31850. friend class DragImageComponent;
  31851. Component* dragImageComponent;
  31852. String currentDragDesc;
  31853. };
  31854. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31855. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31856. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31857. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31858. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31859. /**
  31860. Animates a set of components, moving it to a new position.
  31861. To use this, create a ComponentAnimator, and use its animateComponent() method
  31862. to tell it to move components to destination positions. Any number of
  31863. components can be animated by one ComponentAnimator object (if you've got a
  31864. lot of components to move, it's much more efficient to share a single animator
  31865. than to have many animators running at once).
  31866. You'll need to make sure the animator object isn't deleted before it finishes
  31867. moving the components.
  31868. The class is a ChangeBroadcaster and sends a notification when any components
  31869. start or finish being animated.
  31870. */
  31871. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  31872. private Timer
  31873. {
  31874. public:
  31875. /** Creates a ComponentAnimator. */
  31876. ComponentAnimator();
  31877. /** Destructor. */
  31878. ~ComponentAnimator();
  31879. /** Starts a component moving from its current position to a specified position.
  31880. If the component is already in the middle of an animation, that will be abandoned,
  31881. and a new animation will begin, moving the component from its current location.
  31882. The start and end speed parameters let you apply some acceleration to the component's
  31883. movement.
  31884. @param component the component to move
  31885. @param finalPosition the destination position and size to move it to
  31886. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31887. to arrive at its destination
  31888. @param startSpeed a value to indicate the relative start speed of the
  31889. animation. If this is 0, the component will start
  31890. by accelerating from rest; higher values mean that it
  31891. will have an initial speed greater than zero. If the
  31892. value if greater than 1, it will decelerate towards the
  31893. middle of its journey. To move the component at a constant
  31894. rate for its entire animation, set both the start and
  31895. end speeds to 1.0
  31896. @param endSpeed a relative speed at which the component should be moving
  31897. when the animation finishes. If this is 0, the component
  31898. will decelerate to a standstill at its final position; higher
  31899. values mean the component will still be moving when it stops.
  31900. To move the component at a constant rate for its entire
  31901. animation, set both the start and end speeds to 1.0
  31902. */
  31903. void animateComponent (Component* const component,
  31904. const Rectangle& finalPosition,
  31905. const int millisecondsToSpendMoving,
  31906. const double startSpeed = 1.0,
  31907. const double endSpeed = 1.0);
  31908. /** Stops a component if it's currently being animated.
  31909. If moveComponentToItsFinalPosition is true, then the component will
  31910. be immediately moved to its destination position and size. If false, it will be
  31911. left in whatever location it currently occupies.
  31912. */
  31913. void cancelAnimation (Component* const component,
  31914. const bool moveComponentToItsFinalPosition);
  31915. /** Clears all of the active animations.
  31916. If moveComponentsToTheirFinalPositions is true, all the components will
  31917. be immediately set to their final positions. If false, they will be
  31918. left in whatever locations they currently occupy.
  31919. */
  31920. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31921. /** Returns the destination position for a component.
  31922. If the component is being animated, this will return the target position that
  31923. was specified when animateComponent() was called.
  31924. If the specified component isn't currently being animated, this method will just
  31925. return its current position.
  31926. */
  31927. const Rectangle getComponentDestination (Component* const component);
  31928. /** Returns true if the specified component is currently being animated.
  31929. */
  31930. bool isAnimating (Component* component) const;
  31931. juce_UseDebuggingNewOperator
  31932. private:
  31933. VoidArray tasks;
  31934. uint32 lastTime;
  31935. void* findTaskFor (Component* const component) const;
  31936. void timerCallback();
  31937. };
  31938. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31939. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31940. class ToolbarItemComponent;
  31941. class ToolbarItemFactory;
  31942. class MissingItemsComponent;
  31943. /**
  31944. A toolbar component.
  31945. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31946. and looks after their order and layout.
  31947. Items (icon buttons or other custom components) are added to a toolbar using a
  31948. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31949. toolbar might contain more than one instance of a particular item type.
  31950. Toolbars can be interactively customised, allowing the user to drag the items
  31951. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31952. component as a source of new items.
  31953. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31954. */
  31955. class JUCE_API Toolbar : public Component,
  31956. public DragAndDropContainer,
  31957. public DragAndDropTarget,
  31958. private ButtonListener
  31959. {
  31960. public:
  31961. /** Creates an empty toolbar component.
  31962. To add some icons or other components to your toolbar, you'll need to
  31963. create a ToolbarItemFactory class that can create a suitable set of
  31964. ToolbarItemComponents.
  31965. @see ToolbarItemFactory, ToolbarItemComponents
  31966. */
  31967. Toolbar();
  31968. /** Destructor.
  31969. Any items on the bar will be deleted when the toolbar is deleted.
  31970. */
  31971. ~Toolbar();
  31972. /** Changes the bar's orientation.
  31973. @see isVertical
  31974. */
  31975. void setVertical (const bool shouldBeVertical);
  31976. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31977. You can change the bar's orientation with setVertical().
  31978. */
  31979. bool isVertical() const throw() { return vertical; }
  31980. /** Returns the depth of the bar.
  31981. If the bar is horizontal, this will return its height; if it's vertical, it
  31982. will return its width.
  31983. @see getLength
  31984. */
  31985. int getThickness() const throw();
  31986. /** Returns the length of the bar.
  31987. If the bar is horizontal, this will return its width; if it's vertical, it
  31988. will return its height.
  31989. @see getThickness
  31990. */
  31991. int getLength() const throw();
  31992. /** Deletes all items from the bar.
  31993. */
  31994. void clear();
  31995. /** Adds an item to the toolbar.
  31996. The factory's ToolbarItemFactory::createItem() will be called by this method
  31997. to create the component that will actually be added to the bar.
  31998. The new item will be inserted at the specified index (if the index is -1, it
  31999. will be added to the right-hand or bottom end of the bar).
  32000. Once added, the component will be automatically deleted by this object when it
  32001. is no longer needed.
  32002. @see ToolbarItemFactory
  32003. */
  32004. void addItem (ToolbarItemFactory& factory,
  32005. const int itemId,
  32006. const int insertIndex = -1);
  32007. /** Deletes one of the items from the bar.
  32008. */
  32009. void removeToolbarItem (const int itemIndex);
  32010. /** Returns the number of items currently on the toolbar.
  32011. @see getItemId, getItemComponent
  32012. */
  32013. int getNumItems() const throw();
  32014. /** Returns the ID of the item with the given index.
  32015. If the index is less than zero or greater than the number of items,
  32016. this will return 0.
  32017. @see getNumItems
  32018. */
  32019. int getItemId (const int itemIndex) const throw();
  32020. /** Returns the component being used for the item with the given index.
  32021. If the index is less than zero or greater than the number of items,
  32022. this will return 0.
  32023. @see getNumItems
  32024. */
  32025. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  32026. /** Clears this toolbar and adds to it the default set of items that the specified
  32027. factory creates.
  32028. @see ToolbarItemFactory::getDefaultItemSet
  32029. */
  32030. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  32031. /** Options for the way items should be displayed.
  32032. @see setStyle, getStyle
  32033. */
  32034. enum ToolbarItemStyle
  32035. {
  32036. iconsOnly, /**< Means that the toolbar should just contain icons. */
  32037. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  32038. textOnly /**< Means that the toolbar only display text labels for each item. */
  32039. };
  32040. /** Returns the toolbar's current style.
  32041. @see ToolbarItemStyle, setStyle
  32042. */
  32043. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32044. /** Changes the toolbar's current style.
  32045. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  32046. */
  32047. void setStyle (const ToolbarItemStyle& newStyle);
  32048. /** Flags used by the showCustomisationDialog() method. */
  32049. enum CustomisationFlags
  32050. {
  32051. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  32052. show the "icons only" option on its choice of toolbar styles. */
  32053. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  32054. show the "icons with text" option on its choice of toolbar styles. */
  32055. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  32056. show the "text only" option on its choice of toolbar styles. */
  32057. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  32058. show a button to reset the toolbar to its default set of items. */
  32059. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  32060. };
  32061. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  32062. The dialog contains a ToolbarItemPalette and various controls for editing other
  32063. aspects of the toolbar. This method will block and run the dialog box modally,
  32064. returning when the user closes it.
  32065. The factory is used to determine the set of items that will be shown on the
  32066. palette.
  32067. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  32068. enum.
  32069. @see ToolbarItemPalette
  32070. */
  32071. void showCustomisationDialog (ToolbarItemFactory& factory,
  32072. const int optionFlags = allCustomisationOptionsEnabled);
  32073. /** Turns on or off the toolbar's editing mode, in which its items can be
  32074. rearranged by the user.
  32075. (In most cases it's easier just to use showCustomisationDialog() instead of
  32076. trying to enable editing directly).
  32077. @see ToolbarItemPalette
  32078. */
  32079. void setEditingActive (const bool editingEnabled);
  32080. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  32081. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32082. methods.
  32083. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32084. */
  32085. enum ColourIds
  32086. {
  32087. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  32088. more control over this, override LookAndFeel::paintToolbarBackground(). */
  32089. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  32090. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  32091. over them. */
  32092. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  32093. held down on them. */
  32094. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  32095. when the style is set to iconsWithText or textOnly. */
  32096. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  32097. the customisation dialog is active and the mouse moves over them. */
  32098. };
  32099. /** Returns a string that represents the toolbar's current set of items.
  32100. This lets you later restore the same item layout using restoreFromString().
  32101. @see restoreFromString
  32102. */
  32103. const String toString() const;
  32104. /** Restores a set of items that was previously stored in a string by the toString()
  32105. method.
  32106. The factory object is used to create any item components that are needed.
  32107. @see toString
  32108. */
  32109. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  32110. const String& savedVersion);
  32111. /** @internal */
  32112. void paint (Graphics& g);
  32113. /** @internal */
  32114. void resized();
  32115. /** @internal */
  32116. void buttonClicked (Button*);
  32117. /** @internal */
  32118. void mouseDown (const MouseEvent&);
  32119. /** @internal */
  32120. bool isInterestedInDragSource (const String&, Component*);
  32121. /** @internal */
  32122. void itemDragMove (const String&, Component*, int, int);
  32123. /** @internal */
  32124. void itemDragExit (const String&, Component*);
  32125. /** @internal */
  32126. void itemDropped (const String&, Component*, int, int);
  32127. /** @internal */
  32128. void updateAllItemPositions (const bool animate);
  32129. /** @internal */
  32130. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  32131. juce_UseDebuggingNewOperator
  32132. private:
  32133. Button* missingItemsButton;
  32134. bool vertical, isEditingActive;
  32135. ToolbarItemStyle toolbarStyle;
  32136. ComponentAnimator animator;
  32137. friend class MissingItemsComponent;
  32138. Array <ToolbarItemComponent*> items;
  32139. friend class ItemDragAndDropOverlayComponent;
  32140. static const tchar* const toolbarDragDescriptor;
  32141. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  32142. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  32143. Toolbar (const Toolbar&);
  32144. const Toolbar& operator= (const Toolbar&);
  32145. };
  32146. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  32147. /********* End of inlined file: juce_Toolbar.h *********/
  32148. class ItemDragAndDropOverlayComponent;
  32149. /**
  32150. A component that can be used as one of the items in a Toolbar.
  32151. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  32152. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  32153. class for further info about creating them.
  32154. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  32155. components too. To do this, set the value of isBeingUsedAsAButton to false when
  32156. calling the constructor, and override contentAreaChanged(), in which you can position
  32157. any sub-components you need to add.
  32158. To add basic buttons without writing a special subclass, have a look at the
  32159. ToolbarButton class.
  32160. @see ToolbarButton, Toolbar, ToolbarItemFactory
  32161. */
  32162. class JUCE_API ToolbarItemComponent : public Button
  32163. {
  32164. public:
  32165. /** Constructor.
  32166. @param itemId the ID of the type of toolbar item which this represents
  32167. @param labelText the text to display if the toolbar's style is set to
  32168. Toolbar::iconsWithText or Toolbar::textOnly
  32169. @param isBeingUsedAsAButton set this to false if you don't want the button
  32170. to draw itself with button over/down states when the mouse
  32171. moves over it or clicks
  32172. */
  32173. ToolbarItemComponent (const int itemId,
  32174. const String& labelText,
  32175. const bool isBeingUsedAsAButton);
  32176. /** Destructor. */
  32177. ~ToolbarItemComponent();
  32178. /** Returns the item type ID that this component represents.
  32179. This value is in the constructor.
  32180. */
  32181. int getItemId() const throw() { return itemId; }
  32182. /** Returns the toolbar that contains this component, or 0 if it's not currently
  32183. inside one.
  32184. */
  32185. Toolbar* getToolbar() const;
  32186. /** Returns true if this component is currently inside a toolbar which is vertical.
  32187. @see Toolbar::isVertical
  32188. */
  32189. bool isToolbarVertical() const;
  32190. /** Returns the current style setting of this item.
  32191. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  32192. @see setStyle, Toolbar::getStyle
  32193. */
  32194. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32195. /** Changes the current style setting of this item.
  32196. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  32197. by the toolbar that holds this item.
  32198. @see setStyle, Toolbar::setStyle
  32199. */
  32200. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  32201. /** Returns the area of the component that should be used to display the button image or
  32202. other contents of the item.
  32203. This content area may change when the item's style changes, and may leave a space around the
  32204. edge of the component where the text label can be shown.
  32205. @see contentAreaChanged
  32206. */
  32207. const Rectangle getContentArea() const throw() { return contentArea; }
  32208. /** This method must return the size criteria for this item, based on a given toolbar
  32209. size and orientation.
  32210. The preferredSize, minSize and maxSize values must all be set by your implementation
  32211. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  32212. toolbar, they refer to the item's height.
  32213. The preferredSize is the size that the component would like to be, and this must be
  32214. between the min and max sizes. For a fixed-size item, simply set all three variables to
  32215. the same value.
  32216. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  32217. Toolbar::getThickness().
  32218. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  32219. vertically.
  32220. */
  32221. virtual bool getToolbarItemSizes (int toolbarThickness,
  32222. bool isToolbarVertical,
  32223. int& preferredSize,
  32224. int& minSize,
  32225. int& maxSize) = 0;
  32226. /** Your subclass should use this method to draw its content area.
  32227. The graphics object that is passed-in will have been clipped and had its origin
  32228. moved to fit the content area as specified get getContentArea(). The width and height
  32229. parameters are the width and height of the content area.
  32230. If the component you're writing isn't a button, you can just do nothing in this method.
  32231. */
  32232. virtual void paintButtonArea (Graphics& g,
  32233. int width, int height,
  32234. bool isMouseOver, bool isMouseDown) = 0;
  32235. /** Callback to indicate that the content area of this item has changed.
  32236. This might be because the component was resized, or because the style changed and
  32237. the space needed for the text label is different.
  32238. See getContentArea() for a description of what the area is.
  32239. */
  32240. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  32241. /** Editing modes.
  32242. These are used by setEditingMode(), but will be rarely needed in user code.
  32243. */
  32244. enum ToolbarEditingMode
  32245. {
  32246. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  32247. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  32248. customisation mode, and the items can be dragged around. */
  32249. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  32250. dragged onto a toolbar to add it to that bar.*/
  32251. };
  32252. /** Changes the editing mode of this component.
  32253. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32254. and is unlikely to be of much use in end-user-code.
  32255. */
  32256. void setEditingMode (const ToolbarEditingMode newMode);
  32257. /** Returns the current editing mode of this component.
  32258. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32259. and is unlikely to be of much use in end-user-code.
  32260. */
  32261. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  32262. /** @internal */
  32263. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  32264. /** @internal */
  32265. void resized();
  32266. juce_UseDebuggingNewOperator
  32267. private:
  32268. friend class Toolbar;
  32269. friend class ItemDragAndDropOverlayComponent;
  32270. const int itemId;
  32271. ToolbarEditingMode mode;
  32272. Toolbar::ToolbarItemStyle toolbarStyle;
  32273. Component* overlayComp;
  32274. int dragOffsetX, dragOffsetY;
  32275. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  32276. Rectangle contentArea;
  32277. ToolbarItemComponent (const ToolbarItemComponent&);
  32278. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  32279. };
  32280. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32281. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  32282. /**
  32283. A type of button designed to go on a toolbar.
  32284. This simple button can have two Drawable objects specified - one for normal
  32285. use and another one (optionally) for the button's "on" state if it's a
  32286. toggle button.
  32287. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  32288. */
  32289. class JUCE_API ToolbarButton : public ToolbarItemComponent
  32290. {
  32291. public:
  32292. /** Creates a ToolbarButton.
  32293. @param itemId the ID for this toolbar item type. This is passed through to the
  32294. ToolbarItemComponent constructor
  32295. @param labelText the text to display on the button (if the toolbar is using a style
  32296. that shows text labels). This is passed through to the
  32297. ToolbarItemComponent constructor
  32298. @param normalImage a drawable object that the button should use as its icon. The object
  32299. that is passed-in here will be kept by this object and will be
  32300. deleted when no longer needed or when this button is deleted.
  32301. @param toggledOnImage a drawable object that the button can use as its icon if the button
  32302. is in a toggled-on state (see the Button::getToggleState() method). If
  32303. 0 is passed-in here, then the normal image will be used instead, regardless
  32304. of the toggle state. The object that is passed-in here will be kept by
  32305. this object and will be deleted when no longer needed or when this button
  32306. is deleted.
  32307. */
  32308. ToolbarButton (const int itemId,
  32309. const String& labelText,
  32310. Drawable* const normalImage,
  32311. Drawable* const toggledOnImage);
  32312. /** Destructor. */
  32313. ~ToolbarButton();
  32314. /** @internal */
  32315. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  32316. int& minSize, int& maxSize);
  32317. /** @internal */
  32318. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  32319. /** @internal */
  32320. void contentAreaChanged (const Rectangle& newBounds);
  32321. juce_UseDebuggingNewOperator
  32322. private:
  32323. Drawable* const normalImage;
  32324. Drawable* const toggledOnImage;
  32325. ToolbarButton (const ToolbarButton&);
  32326. const ToolbarButton& operator= (const ToolbarButton&);
  32327. };
  32328. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32329. /********* End of inlined file: juce_ToolbarButton.h *********/
  32330. #endif
  32331. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32332. #endif
  32333. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32334. /********* Start of inlined file: juce_GlowEffect.h *********/
  32335. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32336. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  32337. /**
  32338. A component effect that adds a coloured blur around the component's contents.
  32339. (This will only work on non-opaque components).
  32340. @see Component::setComponentEffect, DropShadowEffect
  32341. */
  32342. class JUCE_API GlowEffect : public ImageEffectFilter
  32343. {
  32344. public:
  32345. /** Creates a default 'glow' effect.
  32346. To customise its appearance, use the setGlowProperties() method.
  32347. */
  32348. GlowEffect();
  32349. /** Destructor. */
  32350. ~GlowEffect();
  32351. /** Sets the glow's radius and colour.
  32352. The radius is how large the blur should be, and the colour is
  32353. used to render it (for a less intense glow, lower the colour's
  32354. opacity).
  32355. */
  32356. void setGlowProperties (const float newRadius,
  32357. const Colour& newColour);
  32358. /** @internal */
  32359. void applyEffect (Image& sourceImage, Graphics& destContext);
  32360. juce_UseDebuggingNewOperator
  32361. private:
  32362. float radius;
  32363. Colour colour;
  32364. };
  32365. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  32366. /********* End of inlined file: juce_GlowEffect.h *********/
  32367. #endif
  32368. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  32369. #endif
  32370. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32371. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  32372. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32373. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32374. /**
  32375. An effect filter that reduces the image's opacity.
  32376. This can be used to make a component (and its child components) more
  32377. transparent.
  32378. @see Component::setComponentEffect
  32379. */
  32380. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  32381. {
  32382. public:
  32383. /** Creates the effect object.
  32384. The opacity of the component to which the effect is applied will be
  32385. scaled by the given factor (in the range 0 to 1.0f).
  32386. */
  32387. ReduceOpacityEffect (const float opacity = 1.0f);
  32388. /** Destructor. */
  32389. ~ReduceOpacityEffect();
  32390. /** Sets how much to scale the component's opacity.
  32391. @param newOpacity should be between 0 and 1.0f
  32392. */
  32393. void setOpacity (const float newOpacity);
  32394. /** @internal */
  32395. void applyEffect (Image& sourceImage, Graphics& destContext);
  32396. juce_UseDebuggingNewOperator
  32397. private:
  32398. float opacity;
  32399. };
  32400. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32401. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  32402. #endif
  32403. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  32404. #endif
  32405. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32406. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  32407. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32408. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32409. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  32410. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32411. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32412. /**
  32413. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  32414. command in a ApplicationCommandManager.
  32415. Normally, you won't actually create a KeyPressMappingSet directly, because
  32416. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  32417. you'd create yourself an ApplicationCommandManager, and call its
  32418. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  32419. KeyPressMappingSet.
  32420. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  32421. to the top-level component for which you want to handle keystrokes. So for example:
  32422. @code
  32423. class MyMainWindow : public Component
  32424. {
  32425. ApplicationCommandManager* myCommandManager;
  32426. public:
  32427. MyMainWindow()
  32428. {
  32429. myCommandManager = new ApplicationCommandManager();
  32430. // first, make sure the command manager has registered all the commands that its
  32431. // targets can perform..
  32432. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  32433. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  32434. // this will use the command manager to initialise the KeyPressMappingSet with
  32435. // the default keypresses that were specified when the targets added their commands
  32436. // to the manager.
  32437. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  32438. // having set up the default key-mappings, you might now want to load the last set
  32439. // of mappings that the user configured.
  32440. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  32441. // Now tell our top-level window to send any keypresses that arrive to the
  32442. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  32443. addKeyListener (myCommandManager->getKeyMappings());
  32444. }
  32445. ...
  32446. }
  32447. @endcode
  32448. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  32449. register to be told when a command or mapping is added, removed, etc.
  32450. There's also a UI component called KeyMappingEditorComponent that can be used
  32451. to easily edit the key mappings.
  32452. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  32453. */
  32454. class JUCE_API KeyPressMappingSet : public KeyListener,
  32455. public ChangeBroadcaster,
  32456. public FocusChangeListener
  32457. {
  32458. public:
  32459. /** Creates a KeyPressMappingSet for a given command manager.
  32460. Normally, you won't actually create a KeyPressMappingSet directly, because
  32461. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  32462. best thing to do is to create your ApplicationCommandManager, and use the
  32463. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  32464. When a suitable keypress happens, the manager's invoke() method will be
  32465. used to invoke the appropriate command.
  32466. @see ApplicationCommandManager
  32467. */
  32468. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  32469. /** Creates an copy of a KeyPressMappingSet. */
  32470. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  32471. /** Destructor. */
  32472. ~KeyPressMappingSet();
  32473. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  32474. /** Returns a list of keypresses that are assigned to a particular command.
  32475. @param commandID the command's ID
  32476. */
  32477. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  32478. /** Assigns a keypress to a command.
  32479. If the keypress is already assigned to a different command, it will first be
  32480. removed from that command, to avoid it triggering multiple functions.
  32481. @param commandID the ID of the command that you want to add a keypress to. If
  32482. this is 0, the keypress will be removed from anything that it
  32483. was previously assigned to, but not re-assigned
  32484. @param newKeyPress the new key-press
  32485. @param insertIndex if this is less than zero, the key will be appended to the
  32486. end of the list of keypresses; otherwise the new keypress will
  32487. be inserted into the existing list at this index
  32488. */
  32489. void addKeyPress (const CommandID commandID,
  32490. const KeyPress& newKeyPress,
  32491. int insertIndex = -1) throw();
  32492. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  32493. @see resetToDefaultMapping
  32494. */
  32495. void resetToDefaultMappings() throw();
  32496. /** Resets all key-mappings to the defaults for a particular command.
  32497. @see resetToDefaultMappings
  32498. */
  32499. void resetToDefaultMapping (const CommandID commandID) throw();
  32500. /** Removes all keypresses that are assigned to any commands. */
  32501. void clearAllKeyPresses() throw();
  32502. /** Removes all keypresses that are assigned to a particular command. */
  32503. void clearAllKeyPresses (const CommandID commandID) throw();
  32504. /** Removes one of the keypresses that are assigned to a command.
  32505. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  32506. which the keyPressIndex refers.
  32507. */
  32508. void removeKeyPress (const CommandID commandID,
  32509. const int keyPressIndex) throw();
  32510. /** Removes a keypress from any command that it may be assigned to.
  32511. */
  32512. void removeKeyPress (const KeyPress& keypress) throw();
  32513. /** Returns true if the given command is linked to this key. */
  32514. bool containsMapping (const CommandID commandID,
  32515. const KeyPress& keyPress) const throw();
  32516. /** Looks for a command that corresponds to a keypress.
  32517. @returns the UID of the command or 0 if none was found
  32518. */
  32519. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  32520. /** Tries to recreate the mappings from a previously stored state.
  32521. The XML passed in must have been created by the createXml() method.
  32522. If the stored state makes any reference to commands that aren't
  32523. currently available, these will be ignored.
  32524. If the set of mappings being loaded was a set of differences (using createXml (true)),
  32525. then this will call resetToDefaultMappings() and then merge the saved mappings
  32526. on top. If the saved set was created with createXml (false), then this method
  32527. will first clear all existing mappings and load the saved ones as a complete set.
  32528. @returns true if it manages to load the XML correctly
  32529. @see createXml
  32530. */
  32531. bool restoreFromXml (const XmlElement& xmlVersion);
  32532. /** Creates an XML representation of the current mappings.
  32533. This will produce a lump of XML that can be later reloaded using
  32534. restoreFromXml() to recreate the current mapping state.
  32535. The object that is returned must be deleted by the caller.
  32536. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  32537. will be saved into the XML. If it's true, then the XML will
  32538. only store the differences between the current mappings and
  32539. the default mappings you'd get from calling resetToDefaultMappings().
  32540. The advantage of saving a set of differences from the default is that
  32541. if you change the default mappings (in a new version of your app, for
  32542. example), then these will be merged into a user's saved preferences.
  32543. @see restoreFromXml
  32544. */
  32545. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  32546. /** @internal */
  32547. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  32548. /** @internal */
  32549. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  32550. /** @internal */
  32551. void globalFocusChanged (Component* focusedComponent);
  32552. juce_UseDebuggingNewOperator
  32553. private:
  32554. ApplicationCommandManager* commandManager;
  32555. struct CommandMapping
  32556. {
  32557. CommandID commandID;
  32558. Array <KeyPress> keypresses;
  32559. bool wantsKeyUpDownCallbacks;
  32560. };
  32561. OwnedArray <CommandMapping> mappings;
  32562. struct KeyPressTime
  32563. {
  32564. KeyPress key;
  32565. uint32 timeWhenPressed;
  32566. };
  32567. OwnedArray <KeyPressTime> keysDown;
  32568. void handleMessage (const Message& message);
  32569. void invokeCommand (const CommandID commandID,
  32570. const KeyPress& keyPress,
  32571. const bool isKeyDown,
  32572. const int millisecsSinceKeyPressed,
  32573. Component* const originatingComponent) const;
  32574. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  32575. };
  32576. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32577. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  32578. /********* Start of inlined file: juce_TreeView.h *********/
  32579. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  32580. #define __JUCE_TREEVIEW_JUCEHEADER__
  32581. class TreeView;
  32582. /**
  32583. An item in a treeview.
  32584. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  32585. own sub-items.
  32586. To implement an item that contains sub-items, override the itemOpennessChanged()
  32587. method so that when it is opened, it adds the new sub-items to itself using the
  32588. addSubItem method. Depending on the nature of the item it might choose to only
  32589. do this the first time it's opened, or it might want to refresh itself each time.
  32590. It also has the option of deleting its sub-items when it is closed, or leaving them
  32591. in place.
  32592. */
  32593. class JUCE_API TreeViewItem
  32594. {
  32595. public:
  32596. /** Constructor. */
  32597. TreeViewItem();
  32598. /** Destructor. */
  32599. virtual ~TreeViewItem();
  32600. /** Returns the number of sub-items that have been added to this item.
  32601. Note that this doesn't mean much if the node isn't open.
  32602. @see getSubItem, mightContainSubItems, addSubItem
  32603. */
  32604. int getNumSubItems() const throw();
  32605. /** Returns one of the item's sub-items.
  32606. Remember that the object returned might get deleted at any time when its parent
  32607. item is closed or refreshed, depending on the nature of the items you're using.
  32608. @see getNumSubItems
  32609. */
  32610. TreeViewItem* getSubItem (const int index) const throw();
  32611. /** Removes any sub-items. */
  32612. void clearSubItems();
  32613. /** Adds a sub-item.
  32614. @param newItem the object to add to the item's sub-item list. Once added, these can be
  32615. found using getSubItem(). When the items are later removed with
  32616. removeSubItem() (or when this item is deleted), they will be deleted.
  32617. @param insertPosition the index which the new item should have when it's added. If this
  32618. value is less than 0, the item will be added to the end of the list.
  32619. */
  32620. void addSubItem (TreeViewItem* const newItem,
  32621. const int insertPosition = -1);
  32622. /** Removes one of the sub-items.
  32623. @param index the item to remove
  32624. @param deleteItem if true, the item that is removed will also be deleted.
  32625. */
  32626. void removeSubItem (const int index,
  32627. const bool deleteItem = true);
  32628. /** Returns the TreeView to which this item belongs. */
  32629. TreeView* getOwnerView() const throw() { return ownerView; }
  32630. /** Returns the item within which this item is contained. */
  32631. TreeViewItem* getParentItem() const throw() { return parentItem; }
  32632. /** True if this item is currently open in the treeview. */
  32633. bool isOpen() const throw();
  32634. /** Opens or closes the item.
  32635. When opened or closed, the item's itemOpennessChanged() method will be called,
  32636. and a subclass should use this callback to create and add any sub-items that
  32637. it needs to.
  32638. @see itemOpennessChanged, mightContainSubItems
  32639. */
  32640. void setOpen (const bool shouldBeOpen);
  32641. /** True if this item is currently selected.
  32642. Use this when painting the node, to decide whether to draw it as selected or not.
  32643. */
  32644. bool isSelected() const throw();
  32645. /** Selects or deselects the item.
  32646. This will cause a callback to itemSelectionChanged()
  32647. */
  32648. void setSelected (const bool shouldBeSelected,
  32649. const bool deselectOtherItemsFirst);
  32650. /** Returns the rectangle that this item occupies.
  32651. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  32652. top-left of the TreeView comp, so this will depend on the scroll-position of
  32653. the tree. If false, it is relative to the top-left of the topmost item in the
  32654. tree (so this would be unaffected by scrolling the view).
  32655. */
  32656. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  32657. /** Sends a signal to the treeview to make it refresh itself.
  32658. Call this if your items have changed and you want the tree to update to reflect
  32659. this.
  32660. */
  32661. void treeHasChanged() const throw();
  32662. /** Sends a repaint message to redraw just this item.
  32663. Note that you should only call this if you want to repaint a superficial change. If
  32664. you're altering the tree's nodes, you should instead call treeHasChanged().
  32665. */
  32666. void repaintItem() const;
  32667. /** Returns the row number of this item in the tree.
  32668. The row number of an item will change according to which items are open.
  32669. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  32670. */
  32671. int getRowNumberInTree() const throw();
  32672. /** Returns true if all the item's parent nodes are open.
  32673. This is useful to check whether the item might actually be visible or not.
  32674. */
  32675. bool areAllParentsOpen() const throw();
  32676. /** Changes whether lines are drawn to connect any sub-items to this item.
  32677. By default, line-drawing is turned on.
  32678. */
  32679. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  32680. /** Tells the tree whether this item can potentially be opened.
  32681. If your item could contain sub-items, this should return true; if it returns
  32682. false then the tree will not try to open the item. This determines whether or
  32683. not the item will be drawn with a 'plus' button next to it.
  32684. */
  32685. virtual bool mightContainSubItems() = 0;
  32686. /** Returns a string to uniquely identify this item.
  32687. If you're planning on using the TreeView::getOpennessState() method, then
  32688. these strings will be used to identify which nodes are open. The string
  32689. should be unique amongst the item's sibling items, but it's ok for there
  32690. to be duplicates at other levels of the tree.
  32691. If you're not going to store the state, then it's ok not to bother implementing
  32692. this method.
  32693. */
  32694. virtual const String getUniqueName() const;
  32695. /** Called when an item is opened or closed.
  32696. When setOpen() is called and the item has specified that it might
  32697. have sub-items with the mightContainSubItems() method, this method
  32698. is called to let the item create or manage its sub-items.
  32699. So when this is called with isNowOpen set to true (i.e. when the item is being
  32700. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  32701. refresh its sub-item list.
  32702. When this is called with isNowOpen set to false, the subclass might want
  32703. to use clearSubItems() to save on space, or it might choose to leave them,
  32704. depending on the nature of the tree.
  32705. You could also use this callback as a trigger to start a background process
  32706. which asynchronously creates sub-items and adds them, if that's more
  32707. appropriate for the task in hand.
  32708. @see mightContainSubItems
  32709. */
  32710. virtual void itemOpennessChanged (bool isNowOpen);
  32711. /** Must return the width required by this item.
  32712. If your item needs to have a particular width in pixels, return that value; if
  32713. you'd rather have it just fill whatever space is available in the treeview,
  32714. return -1.
  32715. If all your items return -1, no horizontal scrollbar will be shown, but if any
  32716. items have fixed widths and extend beyond the width of the treeview, a
  32717. scrollbar will appear.
  32718. Each item can be a different width, but if they change width, you should call
  32719. treeHasChanged() to update the tree.
  32720. */
  32721. virtual int getItemWidth() const { return -1; }
  32722. /** Must return the height required by this item.
  32723. This is the height in pixels that the item will take up. Items in the tree
  32724. can be different heights, but if they change height, you should call
  32725. treeHasChanged() to update the tree.
  32726. */
  32727. virtual int getItemHeight() const { return 20; }
  32728. /** You can override this method to return false if you don't want to allow the
  32729. user to select this item.
  32730. */
  32731. virtual bool canBeSelected() const { return true; }
  32732. /** Creates a component that will be used to represent this item.
  32733. You don't have to implement this method - if it returns 0 then no component
  32734. will be used for the item, and you can just draw it using the paintItem()
  32735. callback. But if you do return a component, it will be positioned in the
  32736. treeview so that it can be used to represent this item.
  32737. The component returned will be managed by the treeview, so always return
  32738. a new component, and don't keep a reference to it, as the treeview will
  32739. delete it later when it goes off the screen or is no longer needed. Also
  32740. bear in mind that if the component keeps a reference to the item that
  32741. created it, that item could be deleted before the component. Its position
  32742. and size will be completely managed by the tree, so don't attempt to move it
  32743. around.
  32744. Something you may want to do with your component is to give it a pointer to
  32745. the TreeView that created it. This is perfectly safe, and there's no danger
  32746. of it becoming a dangling pointer because the TreeView will always delete
  32747. the component before it is itself deleted.
  32748. As long as you stick to these rules you can return whatever kind of
  32749. component you like. It's most useful if you're doing things like drag-and-drop
  32750. of items, or want to use a Label component to edit item names, etc.
  32751. */
  32752. virtual Component* createItemComponent() { return 0; }
  32753. /** Draws the item's contents.
  32754. You can choose to either implement this method and draw each item, or you
  32755. can use createItemComponent() to create a component that will represent the
  32756. item.
  32757. If all you need in your tree is to be able to draw the items and detect when
  32758. the user selects or double-clicks one of them, it's probably enough to
  32759. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  32760. complicated interactions, you may need to use createItemComponent() instead.
  32761. @param g the graphics context to draw into
  32762. @param width the width of the area available for drawing
  32763. @param height the height of the area available for drawing
  32764. */
  32765. virtual void paintItem (Graphics& g, int width, int height);
  32766. /** Draws the item's open/close button.
  32767. If you don't implement this method, the default behaviour is to
  32768. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  32769. it for custom effects.
  32770. */
  32771. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  32772. /** Called when the user clicks on this item.
  32773. If you're using createItemComponent() to create a custom component for the
  32774. item, the mouse-clicks might not make it through to the treeview, but this
  32775. is how you find out about clicks when just drawing each item individually.
  32776. The associated mouse-event details are passed in, so you can find out about
  32777. which button, where it was, etc.
  32778. @see itemDoubleClicked
  32779. */
  32780. virtual void itemClicked (const MouseEvent& e);
  32781. /** Called when the user double-clicks on this item.
  32782. If you're using createItemComponent() to create a custom component for the
  32783. item, the mouse-clicks might not make it through to the treeview, but this
  32784. is how you find out about clicks when just drawing each item individually.
  32785. The associated mouse-event details are passed in, so you can find out about
  32786. which button, where it was, etc.
  32787. If not overridden, the base class method here will open or close the item as
  32788. if the 'plus' button had been clicked.
  32789. @see itemClicked
  32790. */
  32791. virtual void itemDoubleClicked (const MouseEvent& e);
  32792. /** Called when the item is selected or deselected.
  32793. Use this if you want to do something special when the item's selectedness
  32794. changes. By default it'll get repainted when this happens.
  32795. */
  32796. virtual void itemSelectionChanged (bool isNowSelected);
  32797. /** The item can return a tool tip string here if it wants to.
  32798. @see TooltipClient
  32799. */
  32800. virtual const String getTooltip();
  32801. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  32802. If this returns a non-empty name then when the user drags an item, the treeview will
  32803. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32804. a drag-and-drop operation, using this string as the source description, with the treeview
  32805. itself as the source component.
  32806. If you need more complex drag-and-drop behaviour, you can use custom components for
  32807. the items, and use those to trigger the drag.
  32808. @see DragAndDropContainer::startDragging
  32809. */
  32810. virtual const String getDragSourceDescription();
  32811. /** Sets a flag to indicate that the item wants to be allowed
  32812. to draw all the way across to the left edge of the treeview.
  32813. By default this is false, which means that when the paintItem()
  32814. method is called, its graphics context is clipped to only allow
  32815. drawing within the item's rectangle. If this flag is set to true,
  32816. then the graphics context isn't clipped on its left side, so it
  32817. can draw all the way across to the left margin. Note that the
  32818. context will still have its origin in the same place though, so
  32819. the coordinates of anything to its left will be negative. It's
  32820. mostly useful if you want to draw a wider bar behind the
  32821. highlighted item.
  32822. */
  32823. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  32824. juce_UseDebuggingNewOperator
  32825. private:
  32826. TreeView* ownerView;
  32827. TreeViewItem* parentItem;
  32828. OwnedArray <TreeViewItem> subItems;
  32829. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  32830. int uid;
  32831. bool selected : 1;
  32832. bool redrawNeeded : 1;
  32833. bool drawLinesInside : 1;
  32834. bool drawsInLeftMargin : 1;
  32835. unsigned int openness : 2;
  32836. friend class TreeView;
  32837. friend class TreeViewContentComponent;
  32838. void updatePositions (int newY);
  32839. int getIndentX() const throw();
  32840. void setOwnerView (TreeView* const newOwner) throw();
  32841. void paintRecursively (Graphics& g, int width);
  32842. TreeViewItem* findItemRecursively (int y) throw();
  32843. TreeViewItem* getDeepestOpenParentItem() throw();
  32844. void restoreFromXml (const XmlElement& e);
  32845. XmlElement* createXmlOpenness() const;
  32846. bool isLastOfSiblings() const throw();
  32847. TreeViewItem* getTopLevelItem() throw();
  32848. int getNumRows() const throw();
  32849. TreeViewItem* getItemOnRow (int index) throw();
  32850. void deselectAllRecursively();
  32851. int countSelectedItemsRecursively() const throw();
  32852. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  32853. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  32854. TreeViewItem (const TreeViewItem&);
  32855. const TreeViewItem& operator= (const TreeViewItem&);
  32856. };
  32857. /**
  32858. A tree-view component.
  32859. Use one of these to hold and display a structure of TreeViewItem objects.
  32860. */
  32861. class JUCE_API TreeView : public Component,
  32862. public SettableTooltipClient,
  32863. private AsyncUpdater
  32864. {
  32865. public:
  32866. /** Creates an empty treeview.
  32867. Once you've got a treeview component, you'll need to give it something to
  32868. display, using the setRootItem() method.
  32869. */
  32870. TreeView (const String& componentName = String::empty);
  32871. /** Destructor. */
  32872. ~TreeView();
  32873. /** Sets the item that is displayed in the treeview.
  32874. A tree has a single root item which contains as many sub-items as it needs. If
  32875. you want the tree to contain a number of root items, you should still use a single
  32876. root item above these, but hide it using setRootItemVisible().
  32877. You can pass in 0 to this method to clear the tree and remove its current root item.
  32878. The object passed in will not be deleted by the treeview, it's up to the caller
  32879. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32880. this item until you've removed it from the tree, either by calling setRootItem (0),
  32881. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  32882. to delete it.
  32883. */
  32884. void setRootItem (TreeViewItem* const newRootItem);
  32885. /** Returns the tree's root item.
  32886. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32887. */
  32888. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32889. /** This will remove and delete the current root item.
  32890. It's a convenient way of deleting the item and calling setRootItem (0).
  32891. */
  32892. void deleteRootItem();
  32893. /** Changes whether the tree's root item is shown or not.
  32894. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32895. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32896. will also make sure the root item is open (otherwise the treeview would look empty).
  32897. */
  32898. void setRootItemVisible (const bool shouldBeVisible);
  32899. /** Returns true if the root item is visible.
  32900. @see setRootItemVisible
  32901. */
  32902. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32903. /** Sets whether items are open or closed by default.
  32904. Normally, items are closed until the user opens them, but you can use this
  32905. to make them default to being open until explicitly closed.
  32906. @see areItemsOpenByDefault
  32907. */
  32908. void setDefaultOpenness (const bool isOpenByDefault);
  32909. /** Returns true if the tree's items default to being open.
  32910. @see setDefaultOpenness
  32911. */
  32912. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32913. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32914. You can always select multiple items internally by calling the
  32915. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32916. is allowed to multi-select by clicking on the tree.
  32917. By default it is disabled.
  32918. @see isMultiSelectEnabled
  32919. */
  32920. void setMultiSelectEnabled (const bool canMultiSelect);
  32921. /** Returns whether multi-select has been enabled for the tree.
  32922. @see setMultiSelectEnabled
  32923. */
  32924. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32925. /** Sets a flag to indicate whether to hide the open/close buttons.
  32926. @see areOpenCloseButtonsVisible
  32927. */
  32928. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  32929. /** Returns whether open/close buttons are shown.
  32930. @see setOpenCloseButtonsVisible
  32931. */
  32932. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  32933. /** Deselects any items that are currently selected. */
  32934. void clearSelectedItems();
  32935. /** Returns the number of items that are currently selected.
  32936. @see getSelectedItem, clearSelectedItems
  32937. */
  32938. int getNumSelectedItems() const throw();
  32939. /** Returns one of the selected items in the tree.
  32940. @param index the index, 0 to (getNumSelectedItems() - 1)
  32941. */
  32942. TreeViewItem* getSelectedItem (const int index) const throw();
  32943. /** Returns the number of rows the tree is using.
  32944. This will depend on which items are open.
  32945. @see TreeViewItem::getRowNumberInTree()
  32946. */
  32947. int getNumRowsInTree() const;
  32948. /** Returns the item on a particular row of the tree.
  32949. If the index is out of range, this will return 0.
  32950. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  32951. */
  32952. TreeViewItem* getItemOnRow (int index) const;
  32953. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  32954. void scrollToKeepItemVisible (TreeViewItem* item);
  32955. /** Returns the treeview's Viewport object. */
  32956. Viewport* getViewport() const throw() { return viewport; }
  32957. /** Returns the number of pixels by which each nested level of the tree is indented.
  32958. @see setIndentSize
  32959. */
  32960. int getIndentSize() const throw() { return indentSize; }
  32961. /** Changes the distance by which each nested level of the tree is indented.
  32962. @see getIndentSize
  32963. */
  32964. void setIndentSize (const int newIndentSize);
  32965. /** Saves the current state of open/closed nodes so it can be restored later.
  32966. This takes a snapshot of which nodes have been explicitly opened or closed,
  32967. and records it as XML. To identify node objects it uses the
  32968. TreeViewItem::getUniqueName() method to create named paths. This
  32969. means that the same state of open/closed nodes can be restored to a
  32970. completely different instance of the tree, as long as it contains nodes
  32971. whose unique names are the same.
  32972. The caller is responsible for deleting the object that is returned.
  32973. @param alsoIncludeScrollPosition if this is true, the state will also
  32974. include information about where the
  32975. tree has been scrolled to vertically,
  32976. so this can also be restored
  32977. @see restoreOpennessState
  32978. */
  32979. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32980. /** Restores a previously saved arrangement of open/closed nodes.
  32981. This will try to restore a snapshot of the tree's state that was created by
  32982. the getOpennessState() method. If any of the nodes named in the original
  32983. XML aren't present in this tree, they will be ignored.
  32984. @see getOpennessState
  32985. */
  32986. void restoreOpennessState (const XmlElement& newState);
  32987. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32988. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32989. methods.
  32990. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32991. */
  32992. enum ColourIds
  32993. {
  32994. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32995. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32996. };
  32997. /** @internal */
  32998. void paint (Graphics& g);
  32999. /** @internal */
  33000. void resized();
  33001. /** @internal */
  33002. bool keyPressed (const KeyPress& key);
  33003. /** @internal */
  33004. void colourChanged();
  33005. /** @internal */
  33006. void enablementChanged();
  33007. juce_UseDebuggingNewOperator
  33008. private:
  33009. friend class TreeViewItem;
  33010. friend class TreeViewContentComponent;
  33011. Viewport* viewport;
  33012. CriticalSection nodeAlterationLock;
  33013. TreeViewItem* rootItem;
  33014. int indentSize;
  33015. bool defaultOpenness : 1;
  33016. bool needsRecalculating : 1;
  33017. bool rootItemVisible : 1;
  33018. bool multiSelectEnabled : 1;
  33019. bool openCloseButtonsVisible : 1;
  33020. void itemsChanged() throw();
  33021. void handleAsyncUpdate();
  33022. void moveSelectedRow (int delta);
  33023. void updateButtonUnderMouse (const MouseEvent& e);
  33024. TreeView (const TreeView&);
  33025. const TreeView& operator= (const TreeView&);
  33026. };
  33027. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  33028. /********* End of inlined file: juce_TreeView.h *********/
  33029. /**
  33030. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  33031. object.
  33032. @see KeyPressMappingSet
  33033. */
  33034. class JUCE_API KeyMappingEditorComponent : public Component,
  33035. public TreeViewItem,
  33036. public ChangeListener,
  33037. private ButtonListener
  33038. {
  33039. public:
  33040. /** Creates a KeyMappingEditorComponent.
  33041. @param mappingSet this is the set of mappings to display and
  33042. edit. Make sure the mappings object is not
  33043. deleted before this component!
  33044. @param showResetToDefaultButton if true, then at the bottom of the
  33045. list, the component will include a 'reset to
  33046. defaults' button.
  33047. */
  33048. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  33049. const bool showResetToDefaultButton);
  33050. /** Destructor. */
  33051. virtual ~KeyMappingEditorComponent();
  33052. /** Sets up the colours to use for parts of the component.
  33053. @param mainBackground colour to use for most of the background
  33054. @param textColour colour to use for the text
  33055. */
  33056. void setColours (const Colour& mainBackground,
  33057. const Colour& textColour);
  33058. /** Returns the KeyPressMappingSet that this component is acting upon.
  33059. */
  33060. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  33061. /** Can be overridden if some commands need to be excluded from the list.
  33062. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  33063. method to decide what to return, but you can override it to handle special cases.
  33064. */
  33065. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  33066. /** Can be overridden to indicate that some commands are shown as read-only.
  33067. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  33068. method to decide what to return, but you can override it to handle special cases.
  33069. */
  33070. virtual bool isCommandReadOnly (const CommandID commandID);
  33071. /** This can be overridden to let you change the format of the string used
  33072. to describe a keypress.
  33073. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  33074. keys that are triggered by something else externally. If you override the
  33075. method, be sure to let the base class's method handle keys you're not
  33076. interested in.
  33077. */
  33078. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  33079. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  33080. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33081. methods.
  33082. To change the colours of the menu that pops up
  33083. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33084. */
  33085. enum ColourIds
  33086. {
  33087. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  33088. textColourId = 0x100ad01, /**< The colour for the text. */
  33089. };
  33090. /** @internal */
  33091. void parentHierarchyChanged();
  33092. /** @internal */
  33093. void resized();
  33094. /** @internal */
  33095. void changeListenerCallback (void*);
  33096. /** @internal */
  33097. bool mightContainSubItems();
  33098. /** @internal */
  33099. const String getUniqueName() const;
  33100. /** @internal */
  33101. void buttonClicked (Button* button);
  33102. juce_UseDebuggingNewOperator
  33103. private:
  33104. KeyPressMappingSet* mappings;
  33105. TreeView* tree;
  33106. friend class KeyMappingTreeViewItem;
  33107. friend class KeyCategoryTreeViewItem;
  33108. friend class KeyMappingItemComponent;
  33109. friend class KeyMappingChangeButton;
  33110. TextButton* resetButton;
  33111. void assignNewKey (const CommandID commandID, int index);
  33112. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  33113. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  33114. };
  33115. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  33116. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  33117. #endif
  33118. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  33119. #endif
  33120. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  33121. #endif
  33122. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  33123. #endif
  33124. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  33125. #endif
  33126. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33127. /********* Start of inlined file: juce_CodeEditorComponent.h *********/
  33128. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33129. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33130. /********* Start of inlined file: juce_CodeDocument.h *********/
  33131. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33132. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33133. class CodeDocumentLine;
  33134. /**
  33135. A class for storing and manipulating a source code file.
  33136. When using a CodeEditorComponent, it takes one of these as its source object.
  33137. The CodeDocument stores its content as an array of lines, which makes it
  33138. quick to insert and delete.
  33139. @see CodeEditorComponent
  33140. */
  33141. class JUCE_API CodeDocument
  33142. {
  33143. public:
  33144. /** Creates a new, empty document.
  33145. */
  33146. CodeDocument();
  33147. /** Destructor. */
  33148. ~CodeDocument();
  33149. /** A position in a code document.
  33150. Using this class you can find a position in a code document and quickly get its
  33151. character position, line, and index. By calling setPositionMaintained (true), the
  33152. position is automatically updated when text is inserted or deleted in the document,
  33153. so that it maintains its original place in the text.
  33154. */
  33155. class JUCE_API Position
  33156. {
  33157. public:
  33158. /** Creates an uninitialised postion.
  33159. Don't attempt to call any methods on this until you've given it an owner document
  33160. to refer to!
  33161. */
  33162. Position() throw();
  33163. /** Creates a position based on a line and index in a document.
  33164. Note that this index is NOT the column number, it's the number of characters from the
  33165. start of the line. The "column" number isn't quite the same, because if the line
  33166. contains any tab characters, the relationship of the index to its visual column depends on
  33167. the number of spaces per tab being used!
  33168. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33169. they will be adjusted to keep them within its limits.
  33170. */
  33171. Position (const CodeDocument* const ownerDocument,
  33172. const int line, const int indexInLine) throw();
  33173. /** Creates a position based on a character index in a document.
  33174. This position is placed at the specified number of characters from the start of the
  33175. document. The line and column are auto-calculated.
  33176. If the position is beyond the range of the document, it'll be adjusted to keep it
  33177. inside.
  33178. */
  33179. Position (const CodeDocument* const ownerDocument,
  33180. const int charactersFromStartOfDocument) throw();
  33181. /** Creates a copy of another position.
  33182. This will copy the position, but the new object will not be set to maintain its position,
  33183. even if the source object was set to do so.
  33184. */
  33185. Position (const Position& other) throw();
  33186. /** Destructor. */
  33187. ~Position() throw();
  33188. const Position& operator= (const Position& other) throw();
  33189. bool operator== (const Position& other) const throw();
  33190. bool operator!= (const Position& other) const throw();
  33191. /** Points this object at a new position within the document.
  33192. If the position is beyond the range of the document, it'll be adjusted to keep it
  33193. inside.
  33194. @see getPosition, setLineAndIndex
  33195. */
  33196. void setPosition (const int charactersFromStartOfDocument) throw();
  33197. /** Returns the position as the number of characters from the start of the document.
  33198. @see setPosition, getLineNumber, getIndexInLine
  33199. */
  33200. int getPosition() const throw() { return characterPos; }
  33201. /** Moves the position to a new line and index within the line.
  33202. Note that the index is NOT the column at which the position appears in an editor.
  33203. If the line contains any tab characters, the relationship of the index to its
  33204. visual position depends on the number of spaces per tab being used!
  33205. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33206. they will be adjusted to keep them within its limits.
  33207. */
  33208. void setLineAndIndex (const int newLine, const int newIndexInLine) throw();
  33209. /** Returns the line number of this position.
  33210. The first line in the document is numbered zero, not one!
  33211. */
  33212. int getLineNumber() const throw() { return line; }
  33213. /** Returns the number of characters from the start of the line.
  33214. Note that this value is NOT the column at which the position appears in an editor.
  33215. If the line contains any tab characters, the relationship of the index to its
  33216. visual position depends on the number of spaces per tab being used!
  33217. */
  33218. int getIndexInLine() const throw() { return indexInLine; }
  33219. /** Allows the position to be automatically updated when the document changes.
  33220. If this is set to true, the positon will register with its document so that
  33221. when the document has text inserted or deleted, this position will be automatically
  33222. moved to keep it at the same position in the text.
  33223. */
  33224. void setPositionMaintained (const bool isMaintained) throw();
  33225. /** Moves the position forwards or backwards by the specified number of characters.
  33226. @see movedBy
  33227. */
  33228. void moveBy (int characterDelta) throw();
  33229. /** Returns a position which is the same as this one, moved by the specified number of
  33230. characters.
  33231. @see moveBy
  33232. */
  33233. const Position movedBy (const int characterDelta) const throw();
  33234. /** Returns a position which is the same as this one, moved up or down by the specified
  33235. number of lines.
  33236. @see movedBy
  33237. */
  33238. const Position movedByLines (const int deltaLines) const throw();
  33239. /** Returns the character in the document at this position.
  33240. @see getLineText
  33241. */
  33242. const tchar getCharacter() const throw();
  33243. /** Returns the line from the document that this position is within.
  33244. @see getCharacter, getLineNumber
  33245. */
  33246. const String getLineText() const throw();
  33247. private:
  33248. CodeDocument* owner;
  33249. int characterPos, line, indexInLine;
  33250. bool positionMaintained;
  33251. };
  33252. /** Returns the full text of the document. */
  33253. const String getAllContent() const throw();
  33254. /** Returns a section of the document's text. */
  33255. const String getTextBetween (const Position& start, const Position& end) const throw();
  33256. /** Returns a line from the document. */
  33257. const String getLine (const int lineIndex) const throw();
  33258. /** Returns the number of characters in the document. */
  33259. int getNumCharacters() const throw();
  33260. /** Returns the number of lines in the document. */
  33261. int getNumLines() const throw() { return lines.size(); }
  33262. /** Returns the number of characters in the longest line of the document. */
  33263. int getMaximumLineLength() throw();
  33264. /** Deletes a section of the text.
  33265. This operation is undoable.
  33266. */
  33267. void deleteSection (const Position& startPosition, const Position& endPosition);
  33268. /** Inserts some text into the document at a given position.
  33269. This operation is undoable.
  33270. */
  33271. void insertText (const Position& position, const String& text);
  33272. /** Clears the document and replaces it with some new text.
  33273. This operation is undoable - if you're trying to completely reset the document, you
  33274. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33275. */
  33276. void replaceAllContent (const String& newContent);
  33277. /** Returns the preferred new-line characters for the document.
  33278. This will be either "\n", "\r\n", or (rarely) "\r".
  33279. @see setNewLineCharacters
  33280. */
  33281. const String getNewLineCharacters() const throw() { return newLineChars; }
  33282. /** Sets the new-line characters that the document should use.
  33283. The string must be either "\n", "\r\n", or (rarely) "\r".
  33284. @see getNewLineCharacters
  33285. */
  33286. void setNewLineCharacters (const String& newLine) throw();
  33287. /** Begins a new undo transaction.
  33288. The document itself will not call this internally, so relies on whatever is using the
  33289. document to periodically call this to break up the undo sequence into sensible chunks.
  33290. @see UndoManager::beginNewTransaction
  33291. */
  33292. void newTransaction();
  33293. /** Undo the last operation.
  33294. @see UndoManager::undo
  33295. */
  33296. void undo();
  33297. /** Redo the last operation.
  33298. @see UndoManager::redo
  33299. */
  33300. void redo();
  33301. /** Clears the undo history.
  33302. @see UndoManager::clearUndoHistory
  33303. */
  33304. void clearUndoHistory();
  33305. /** Returns the document's UndoManager */
  33306. UndoManager& getUndoManager() throw() { return undoManager; }
  33307. /** Makes a note that the document's current state matches the one that is saved.
  33308. After this has been called, hasChangedSinceSavePoint() will return false until
  33309. the document has been altered, and then it'll start returning true. If the document is
  33310. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33311. will again return false.
  33312. @see hasChangedSinceSavePoint
  33313. */
  33314. void setSavePoint() throw();
  33315. /** Returns true if the state of the document differs from the state it was in when
  33316. setSavePoint() was last called.
  33317. @see setSavePoint
  33318. */
  33319. bool hasChangedSinceSavePoint() const throw();
  33320. /** Searches for a word-break. */
  33321. const Position findWordBreakAfter (const Position& position) const throw();
  33322. /** Searches for a word-break. */
  33323. const Position findWordBreakBefore (const Position& position) const throw();
  33324. /** An object that receives callbacks from the CodeDocument when its text changes.
  33325. @see CodeDocument::addListener, CodeDocument::removeListener
  33326. */
  33327. class JUCE_API Listener
  33328. {
  33329. public:
  33330. Listener() {}
  33331. virtual ~Listener() {}
  33332. /** Called by a CodeDocument when it is altered.
  33333. */
  33334. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33335. const Position& affectedTextEnd) = 0;
  33336. };
  33337. /** Registers a listener object to receive callbacks when the document changes.
  33338. If the listener is already registered, this method has no effect.
  33339. @see removeListener
  33340. */
  33341. void addListener (Listener* const listener) throw();
  33342. /** Deregisters a listener.
  33343. @see addListener
  33344. */
  33345. void removeListener (Listener* const listener) throw();
  33346. /** Iterates the text in a CodeDocument.
  33347. This class lets you read characters from a CodeDocument. It's designed to be used
  33348. by a SyntaxAnalyser object.
  33349. @see CodeDocument, SyntaxAnalyser
  33350. */
  33351. class Iterator
  33352. {
  33353. public:
  33354. Iterator (CodeDocument* const document) throw();
  33355. Iterator (const Iterator& other);
  33356. const Iterator& operator= (const Iterator& other) throw();
  33357. ~Iterator() throw();
  33358. /** Reads the next character and returns it.
  33359. @see peekNextChar
  33360. */
  33361. juce_wchar nextChar() throw();
  33362. /** Reads the next character without advancing the current position. */
  33363. juce_wchar peekNextChar() const throw();
  33364. /** Advances the position by one character. */
  33365. void skip() throw();
  33366. /** Returns the position of the next character as its position within the
  33367. whole document.
  33368. */
  33369. int getPosition() const throw() { return position; }
  33370. /** Skips over any whitespace characters until the next character is non-whitespace. */
  33371. void skipWhitespace();
  33372. /** Skips forward until the next character will be the first character on the next line */
  33373. void skipToEndOfLine();
  33374. /** Returns the line number of the next character. */
  33375. int getLine() const throw() { return line; }
  33376. /** Returns true if the iterator has reached the end of the document. */
  33377. bool isEOF() const throw();
  33378. private:
  33379. CodeDocument* document;
  33380. int line, position;
  33381. };
  33382. juce_UseDebuggingNewOperator
  33383. private:
  33384. friend class CodeDocumentInsertAction;
  33385. friend class CodeDocumentDeleteAction;
  33386. friend class Iterator;
  33387. friend class Position;
  33388. OwnedArray <CodeDocumentLine> lines;
  33389. Array <Position*> positionsToMaintain;
  33390. UndoManager undoManager;
  33391. int currentActionIndex, indexOfSavedState;
  33392. int maximumLineLength;
  33393. VoidArray listeners;
  33394. String newLineChars;
  33395. void sendListenerChangeMessage (const int startLine, const int endLine);
  33396. void insert (const String& text, const int insertPos, const bool undoable);
  33397. void remove (const int startPos, const int endPos, const bool undoable);
  33398. CodeDocument (const CodeDocument&);
  33399. const CodeDocument& operator= (const CodeDocument&);
  33400. };
  33401. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  33402. /********* End of inlined file: juce_CodeDocument.h *********/
  33403. /********* Start of inlined file: juce_CodeTokeniser.h *********/
  33404. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33405. #define __JUCE_CODETOKENISER_JUCEHEADER__
  33406. /**
  33407. A base class for tokenising code so that the syntax can be displayed in a
  33408. code editor.
  33409. @see CodeDocument, CodeEditorComponent
  33410. */
  33411. class JUCE_API CodeTokeniser
  33412. {
  33413. public:
  33414. CodeTokeniser() {}
  33415. virtual ~CodeTokeniser() {}
  33416. /** Reads the next token from the source and returns its token type.
  33417. This must leave the source pointing to the first character in the
  33418. next token.
  33419. */
  33420. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  33421. /** Returns a list of the names of the token types this analyser uses.
  33422. The index in this list must match the token type numbers that are
  33423. returned by readNextToken().
  33424. */
  33425. virtual const StringArray getTokenTypes() = 0;
  33426. /** Returns a suggested syntax highlighting colour for a specified
  33427. token type.
  33428. */
  33429. virtual const Colour getDefaultColour (const int tokenType) = 0;
  33430. juce_UseDebuggingNewOperator
  33431. };
  33432. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  33433. /********* End of inlined file: juce_CodeTokeniser.h *********/
  33434. class CodeEditorLine;
  33435. /**
  33436. A text editor component designed specifically for source code.
  33437. This is designed to handle syntax highlighting and fast editing of very large
  33438. files.
  33439. */
  33440. class JUCE_API CodeEditorComponent : public Component,
  33441. public Timer,
  33442. public ScrollBarListener,
  33443. public CodeDocument::Listener,
  33444. public AsyncUpdater
  33445. {
  33446. public:
  33447. /** Creates an editor for a document.
  33448. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  33449. The object that you pass in is not owned or deleted by the editor - you must
  33450. make sure that it doesn't get deleted while this component is still using it.
  33451. @see CodeDocument
  33452. */
  33453. CodeEditorComponent (CodeDocument& document,
  33454. CodeTokeniser* const codeTokeniser);
  33455. /** Destructor. */
  33456. ~CodeEditorComponent();
  33457. /** Returns the code document that this component is editing. */
  33458. CodeDocument& getDocument() const throw() { return document; }
  33459. /** Loads the given content into the document.
  33460. This will completely reset the CodeDocument object, clear its undo history,
  33461. and fill it with this text.
  33462. */
  33463. void loadContent (const String& newContent);
  33464. /** Returns the standard character width. */
  33465. float getCharWidth() const throw() { return charWidth; }
  33466. /** Returns the height of a line of text, in pixels. */
  33467. int getLineHeight() const throw() { return lineHeight; }
  33468. /** Returns the number of whole lines visible on the screen,
  33469. This doesn't include a cut-off line that might be visible at the bottom if the
  33470. component's height isn't an exact multiple of the line-height.
  33471. */
  33472. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  33473. /** Returns the number of whole columns visible on the screen.
  33474. This doesn't include any cut-off columns at the right-hand edge.
  33475. */
  33476. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  33477. /** Returns the current caret position. */
  33478. const CodeDocument::Position getCaretPos() const { return caretPos; }
  33479. /** Moves the caret.
  33480. If selecting is true, the section of the document between the current
  33481. caret position and the new one will become selected. If false, any currently
  33482. selected region will be deselected.
  33483. */
  33484. void moveCaretTo (const CodeDocument::Position& newPos, const bool selecting);
  33485. /** Returns the on-screen position of a character in the document.
  33486. The rectangle returned is relative to this component's top-left origin.
  33487. */
  33488. const Rectangle getCharacterBounds (const CodeDocument::Position& pos) const throw();
  33489. /** Finds the character at a given on-screen position.
  33490. The co-ordinates are relative to this component's top-left origin.
  33491. */
  33492. const CodeDocument::Position getPositionAt (int x, int y);
  33493. void cursorLeft (const bool moveInWholeWordSteps, const bool selecting);
  33494. void cursorRight (const bool moveInWholeWordSteps, const bool selecting);
  33495. void cursorDown (const bool selecting);
  33496. void cursorUp (const bool selecting);
  33497. void pageDown (const bool selecting);
  33498. void pageUp (const bool selecting);
  33499. void scrollDown();
  33500. void scrollUp();
  33501. void scrollToLine (int newFirstLineOnScreen);
  33502. void scrollBy (int deltaLines);
  33503. void scrollToColumn (int newFirstColumnOnScreen);
  33504. void scrollToKeepCaretOnScreen();
  33505. void goToStartOfDocument (const bool selecting);
  33506. void goToStartOfLine (const bool selecting);
  33507. void goToEndOfDocument (const bool selecting);
  33508. void goToEndOfLine (const bool selecting);
  33509. void deselectAll();
  33510. void selectAll();
  33511. void insertTextAtCaret (const String& textToInsert);
  33512. void insertTabAtCaret();
  33513. void cut();
  33514. void copy();
  33515. void copyThenCut();
  33516. void paste();
  33517. void backspace (const bool moveInWholeWordSteps);
  33518. void deleteForward (const bool moveInWholeWordSteps);
  33519. void undo();
  33520. void redo();
  33521. /** Changes the current tab settings.
  33522. This lets you change the tab size and whether pressing the tab key inserts a
  33523. tab character, or its equivalent number of spaces.
  33524. */
  33525. void setTabSize (const int numSpacesPerTab,
  33526. const bool insertSpacesInsteadOfTabCharacters) throw();
  33527. /** Returns the current number of spaces per tab.
  33528. @see setTabSize
  33529. */
  33530. int getTabSize() const throw() { return spacesPerTab; }
  33531. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  33532. @see setTabSize
  33533. */
  33534. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  33535. /** Changes the font.
  33536. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  33537. */
  33538. void setFont (const Font& newFont);
  33539. /** Resets the syntax highlighting colours to the default ones provided by the
  33540. code tokeniser.
  33541. @see CodeTokeniser::getDefaultColour
  33542. */
  33543. void resetToDefaultColours();
  33544. /** Changes one of the syntax highlighting colours.
  33545. The token type values are dependent on the tokeniser being used - use
  33546. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33547. @see getColourForTokenType
  33548. */
  33549. void setColourForTokenType (const int tokenType, const Colour& colour);
  33550. /** Returns one of the syntax highlighting colours.
  33551. The token type values are dependent on the tokeniser being used - use
  33552. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33553. @see setColourForTokenType
  33554. */
  33555. const Colour getColourForTokenType (const int tokenType) const throw();
  33556. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  33557. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33558. methods.
  33559. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33560. */
  33561. enum ColourIds
  33562. {
  33563. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  33564. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  33565. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  33566. selected text. */
  33567. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  33568. enabled. */
  33569. };
  33570. /** Changes the size of the scrollbars. */
  33571. void setScrollbarThickness (const int thickness) throw();
  33572. /** @internal */
  33573. void resized();
  33574. /** @internal */
  33575. void paint (Graphics& g);
  33576. /** @internal */
  33577. bool keyPressed (const KeyPress& key);
  33578. /** @internal */
  33579. void mouseDown (const MouseEvent& e);
  33580. /** @internal */
  33581. void mouseDrag (const MouseEvent& e);
  33582. /** @internal */
  33583. void mouseUp (const MouseEvent& e);
  33584. /** @internal */
  33585. void mouseDoubleClick (const MouseEvent& e);
  33586. /** @internal */
  33587. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33588. /** @internal */
  33589. void timerCallback();
  33590. /** @internal */
  33591. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  33592. /** @internal */
  33593. void handleAsyncUpdate();
  33594. /** @internal */
  33595. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  33596. const CodeDocument::Position& affectedTextEnd);
  33597. juce_UseDebuggingNewOperator
  33598. private:
  33599. CodeDocument& document;
  33600. Font font;
  33601. int firstLineOnScreen, gutter, spacesPerTab;
  33602. float charWidth;
  33603. int lineHeight, linesOnScreen, columnsOnScreen;
  33604. int scrollbarThickness;
  33605. bool useSpacesForTabs;
  33606. double xOffset;
  33607. CodeDocument::Position caretPos;
  33608. CodeDocument::Position selectionStart, selectionEnd;
  33609. Component* caret;
  33610. ScrollBar* verticalScrollBar;
  33611. ScrollBar* horizontalScrollBar;
  33612. enum DragType
  33613. {
  33614. notDragging,
  33615. draggingSelectionStart,
  33616. draggingSelectionEnd
  33617. };
  33618. DragType dragType;
  33619. CodeTokeniser* codeTokeniser;
  33620. Array <Colour> coloursForTokenCategories;
  33621. OwnedArray <CodeEditorLine> lines;
  33622. void rebuildLineTokens();
  33623. OwnedArray <CodeDocument::Iterator> cachedIterators;
  33624. void clearCachedIterators (const int firstLineToBeInvalid) throw();
  33625. void updateCachedIterators (int maxLineNum);
  33626. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  33627. void updateScrollBars();
  33628. void scrollToLineInternal (int line);
  33629. void scrollToColumnInternal (double column);
  33630. void newTransaction();
  33631. int indexToColumn (int line, int index) const throw();
  33632. int columnToIndex (int line, int column) const throw();
  33633. CodeEditorComponent (const CodeEditorComponent&);
  33634. const CodeEditorComponent& operator= (const CodeEditorComponent&);
  33635. };
  33636. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33637. /********* End of inlined file: juce_CodeEditorComponent.h *********/
  33638. #endif
  33639. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33640. /********* Start of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  33641. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33642. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33643. /**
  33644. A simple lexical analyser for syntax colouring of C++ code.
  33645. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  33646. */
  33647. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  33648. {
  33649. public:
  33650. CPlusPlusCodeTokeniser();
  33651. ~CPlusPlusCodeTokeniser();
  33652. enum TokenType
  33653. {
  33654. tokenType_error = 0,
  33655. tokenType_comment,
  33656. tokenType_builtInKeyword,
  33657. tokenType_identifier,
  33658. tokenType_integerLiteral,
  33659. tokenType_floatLiteral,
  33660. tokenType_stringLiteral,
  33661. tokenType_operator,
  33662. tokenType_bracket,
  33663. tokenType_punctuation,
  33664. tokenType_preprocessor
  33665. };
  33666. int readNextToken (CodeDocument::Iterator& source);
  33667. const StringArray getTokenTypes();
  33668. const Colour getDefaultColour (const int tokenType);
  33669. juce_UseDebuggingNewOperator
  33670. };
  33671. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33672. /********* End of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  33673. #endif
  33674. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33675. #endif
  33676. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33677. #endif
  33678. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33679. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  33680. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33681. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33682. /********* Start of inlined file: juce_MenuBarModel.h *********/
  33683. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  33684. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  33685. class MenuBarModel;
  33686. /**
  33687. A class to receive callbacks when a MenuBarModel changes.
  33688. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  33689. */
  33690. class JUCE_API MenuBarModelListener
  33691. {
  33692. public:
  33693. /** Destructor. */
  33694. virtual ~MenuBarModelListener() {}
  33695. /** This callback is made when items are changed in the menu bar model.
  33696. */
  33697. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  33698. /** This callback is made when an application command is invoked that
  33699. is represented by one of the items in the menu bar model.
  33700. */
  33701. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  33702. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  33703. };
  33704. /**
  33705. A class for controlling MenuBar components.
  33706. This class is used to tell a MenuBar what menus to show, and to respond
  33707. to a menu being selected.
  33708. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  33709. */
  33710. class JUCE_API MenuBarModel : private AsyncUpdater,
  33711. private ApplicationCommandManagerListener
  33712. {
  33713. public:
  33714. MenuBarModel() throw();
  33715. /** Destructor. */
  33716. virtual ~MenuBarModel();
  33717. /** Call this when some of your menu items have changed.
  33718. This method will cause a callback to any MenuBarListener objects that
  33719. are registered with this model.
  33720. If this model is displaying items from an ApplicationCommandManager, you
  33721. can use the setApplicationCommandManagerToWatch() method to cause
  33722. change messages to be sent automatically when the ApplicationCommandManager
  33723. is changed.
  33724. @see addListener, removeListener, MenuBarListener
  33725. */
  33726. void menuItemsChanged();
  33727. /** Tells the menu bar to listen to the specified command manager, and to update
  33728. itself when the commands change.
  33729. This will also allow it to flash a menu name when a command from that menu
  33730. is invoked using a keystroke.
  33731. */
  33732. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  33733. /** Registers a listener for callbacks when the menu items in this model change.
  33734. The listener object will get callbacks when this object's menuItemsChanged()
  33735. method is called.
  33736. @see removeListener
  33737. */
  33738. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  33739. /** Removes a listener.
  33740. @see addListener
  33741. */
  33742. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  33743. /** This method must return a list of the names of the menus. */
  33744. virtual const StringArray getMenuBarNames() = 0;
  33745. /** This should return the popup menu to display for a given top-level menu.
  33746. @param topLevelMenuIndex the index of the top-level menu to show
  33747. @param menuName the name of the top-level menu item to show
  33748. */
  33749. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  33750. const String& menuName) = 0;
  33751. /** This is called when a menu item has been clicked on.
  33752. @param menuItemID the item ID of the PopupMenu item that was selected
  33753. @param topLevelMenuIndex the index of the top-level menu from which the item was
  33754. chosen (just in case you've used duplicate ID numbers
  33755. on more than one of the popup menus)
  33756. */
  33757. virtual void menuItemSelected (int menuItemID,
  33758. int topLevelMenuIndex) = 0;
  33759. #if JUCE_MAC || DOXYGEN
  33760. /** MAC ONLY - Sets the model that is currently being shown as the main
  33761. menu bar at the top of the screen on the Mac.
  33762. You can pass 0 to stop the current model being displayed. Be careful
  33763. not to delete a model while it is being used.
  33764. An optional extra menu can be specified, containing items to add to the top of
  33765. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  33766. an apple, it's the one next to it, with your application's name at the top
  33767. and the services menu etc on it). When one of these items is selected, the
  33768. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  33769. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  33770. object then newMenuBarModel must be non-null.
  33771. */
  33772. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  33773. const PopupMenu* extraAppleMenuItems = 0) throw();
  33774. /** MAC ONLY - Returns the menu model that is currently being shown as
  33775. the main menu bar.
  33776. */
  33777. static MenuBarModel* getMacMainMenu() throw();
  33778. #endif
  33779. /** @internal */
  33780. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  33781. /** @internal */
  33782. void applicationCommandListChanged();
  33783. /** @internal */
  33784. void handleAsyncUpdate();
  33785. juce_UseDebuggingNewOperator
  33786. private:
  33787. ApplicationCommandManager* manager;
  33788. SortedSet <void*> listeners;
  33789. MenuBarModel (const MenuBarModel&);
  33790. const MenuBarModel& operator= (const MenuBarModel&);
  33791. };
  33792. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  33793. /********* End of inlined file: juce_MenuBarModel.h *********/
  33794. /**
  33795. A menu bar component.
  33796. @see MenuBarModel
  33797. */
  33798. class JUCE_API MenuBarComponent : public Component,
  33799. private MenuBarModelListener,
  33800. private Timer
  33801. {
  33802. public:
  33803. /** Creates a menu bar.
  33804. @param model the model object to use to control this bar. You can
  33805. pass 0 into this if you like, and set the model later
  33806. using the setModel() method
  33807. */
  33808. MenuBarComponent (MenuBarModel* const model);
  33809. /** Destructor. */
  33810. ~MenuBarComponent();
  33811. /** Changes the model object to use to control the bar.
  33812. This can be 0, in which case the bar will be empty. Don't delete the object
  33813. that is passed-in while it's still being used by this MenuBar.
  33814. */
  33815. void setModel (MenuBarModel* const newModel);
  33816. /** Pops up one of the menu items.
  33817. This lets you manually open one of the menus - it could be triggered by a
  33818. key shortcut, for example.
  33819. */
  33820. void showMenu (const int menuIndex);
  33821. /** @internal */
  33822. void paint (Graphics& g);
  33823. /** @internal */
  33824. void resized();
  33825. /** @internal */
  33826. void mouseEnter (const MouseEvent& e);
  33827. /** @internal */
  33828. void mouseExit (const MouseEvent& e);
  33829. /** @internal */
  33830. void mouseDown (const MouseEvent& e);
  33831. /** @internal */
  33832. void mouseDrag (const MouseEvent& e);
  33833. /** @internal */
  33834. void mouseUp (const MouseEvent& e);
  33835. /** @internal */
  33836. void mouseMove (const MouseEvent& e);
  33837. /** @internal */
  33838. void inputAttemptWhenModal();
  33839. /** @internal */
  33840. void handleCommandMessage (int commandId);
  33841. /** @internal */
  33842. bool keyPressed (const KeyPress& key);
  33843. /** @internal */
  33844. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  33845. /** @internal */
  33846. void menuCommandInvoked (MenuBarModel* menuBarModel,
  33847. const ApplicationCommandTarget::InvocationInfo& info);
  33848. juce_UseDebuggingNewOperator
  33849. private:
  33850. MenuBarModel* model;
  33851. StringArray menuNames;
  33852. Array <int> xPositions;
  33853. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  33854. int lastMouseX, lastMouseY;
  33855. bool inModalState;
  33856. Component* currentPopup;
  33857. int getItemAt (int x, int y);
  33858. void updateItemUnderMouse (const int x, const int y);
  33859. void hideCurrentMenu();
  33860. void timerCallback();
  33861. void repaintMenuItem (int index);
  33862. MenuBarComponent (const MenuBarComponent&);
  33863. const MenuBarComponent& operator= (const MenuBarComponent&);
  33864. };
  33865. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33866. /********* End of inlined file: juce_MenuBarComponent.h *********/
  33867. #endif
  33868. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  33869. #endif
  33870. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  33871. #endif
  33872. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  33873. #endif
  33874. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33875. /********* Start of inlined file: juce_ComponentDragger.h *********/
  33876. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33877. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33878. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33879. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33880. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33881. /**
  33882. A class that imposes restrictions on a Component's size or position.
  33883. This is used by classes such as ResizableCornerComponent,
  33884. ResizableBorderComponent and ResizableWindow.
  33885. The base class can impose some basic size and position limits, but you can
  33886. also subclass this for custom uses.
  33887. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  33888. */
  33889. class JUCE_API ComponentBoundsConstrainer
  33890. {
  33891. public:
  33892. /** When first created, the object will not impose any restrictions on the components. */
  33893. ComponentBoundsConstrainer() throw();
  33894. /** Destructor. */
  33895. virtual ~ComponentBoundsConstrainer();
  33896. /** Imposes a minimum width limit. */
  33897. void setMinimumWidth (const int minimumWidth) throw();
  33898. /** Returns the current minimum width. */
  33899. int getMinimumWidth() const throw() { return minW; }
  33900. /** Imposes a maximum width limit. */
  33901. void setMaximumWidth (const int maximumWidth) throw();
  33902. /** Returns the current maximum width. */
  33903. int getMaximumWidth() const throw() { return maxW; }
  33904. /** Imposes a minimum height limit. */
  33905. void setMinimumHeight (const int minimumHeight) throw();
  33906. /** Returns the current minimum height. */
  33907. int getMinimumHeight() const throw() { return minH; }
  33908. /** Imposes a maximum height limit. */
  33909. void setMaximumHeight (const int maximumHeight) throw();
  33910. /** Returns the current maximum height. */
  33911. int getMaximumHeight() const throw() { return maxH; }
  33912. /** Imposes a minimum width and height limit. */
  33913. void setMinimumSize (const int minimumWidth,
  33914. const int minimumHeight) throw();
  33915. /** Imposes a maximum width and height limit. */
  33916. void setMaximumSize (const int maximumWidth,
  33917. const int maximumHeight) throw();
  33918. /** Set all the maximum and minimum dimensions. */
  33919. void setSizeLimits (const int minimumWidth,
  33920. const int minimumHeight,
  33921. const int maximumWidth,
  33922. const int maximumHeight) throw();
  33923. /** Sets the amount by which the component is allowed to go off-screen.
  33924. The values indicate how many pixels must remain on-screen when dragged off
  33925. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  33926. when the component goes off the top of the screen, its y-position will be
  33927. clipped so that there are always at least 10 pixels on-screen. In other words,
  33928. the lowest y-position it can take would be (10 - the component's height).
  33929. If you pass 0 or less for one of these amounts, the component is allowed
  33930. to move beyond that edge completely, with no restrictions at all.
  33931. If you pass a very large number (i.e. larger that the dimensions of the
  33932. component itself), then the component won't be allowed to overlap that
  33933. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  33934. the component will bump into the left side of the screen and go no further.
  33935. */
  33936. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  33937. const int minimumWhenOffTheLeft,
  33938. const int minimumWhenOffTheBottom,
  33939. const int minimumWhenOffTheRight) throw();
  33940. /** Specifies a width-to-height ratio that the resizer should always maintain.
  33941. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  33942. will always be maintained as this multiple of the height.
  33943. @see setResizeLimits
  33944. */
  33945. void setFixedAspectRatio (const double widthOverHeight) throw();
  33946. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  33947. If no aspect ratio is being enforced, this will return 0.
  33948. */
  33949. double getFixedAspectRatio() const throw();
  33950. /** This callback changes the given co-ordinates to impose whatever the current
  33951. constraints are set to be.
  33952. @param x the x position that should be examined and adjusted
  33953. @param y the y position that should be examined and adjusted
  33954. @param w the width that should be examined and adjusted
  33955. @param h the height that should be examined and adjusted
  33956. @param previousBounds the component's current size
  33957. @param limits the region in which the component can be positioned
  33958. @param isStretchingTop whether the top edge of the component is being resized
  33959. @param isStretchingLeft whether the left edge of the component is being resized
  33960. @param isStretchingBottom whether the bottom edge of the component is being resized
  33961. @param isStretchingRight whether the right edge of the component is being resized
  33962. */
  33963. virtual void checkBounds (int& x, int& y, int& w, int& h,
  33964. const Rectangle& previousBounds,
  33965. const Rectangle& limits,
  33966. const bool isStretchingTop,
  33967. const bool isStretchingLeft,
  33968. const bool isStretchingBottom,
  33969. const bool isStretchingRight);
  33970. /** This callback happens when the resizer is about to start dragging. */
  33971. virtual void resizeStart();
  33972. /** This callback happens when the resizer has finished dragging. */
  33973. virtual void resizeEnd();
  33974. /** Checks the given bounds, and then sets the component to the corrected size. */
  33975. void setBoundsForComponent (Component* const component,
  33976. int x, int y, int w, int h,
  33977. const bool isStretchingTop,
  33978. const bool isStretchingLeft,
  33979. const bool isStretchingBottom,
  33980. const bool isStretchingRight);
  33981. /** Performs a check on the current size of a component, and moves or resizes
  33982. it if it fails the constraints.
  33983. */
  33984. void checkComponentBounds (Component* component);
  33985. /** Called by setBoundsForComponent() to apply a new constrained size to a
  33986. component.
  33987. By default this just calls setBounds(), but it virtual in case it's needed for
  33988. extremely cunning purposes.
  33989. */
  33990. virtual void applyBoundsToComponent (Component* component,
  33991. int x, int y, int w, int h);
  33992. juce_UseDebuggingNewOperator
  33993. private:
  33994. int minW, maxW, minH, maxH;
  33995. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  33996. double aspectRatio;
  33997. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  33998. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  33999. };
  34000. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34001. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  34002. /**
  34003. An object to take care of the logic for dragging components around with the mouse.
  34004. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  34005. then in your mouseDrag() callback, call dragComponent().
  34006. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  34007. to limit the component's position and keep it on-screen.
  34008. e.g. @code
  34009. class MyDraggableComp
  34010. {
  34011. ComponentDragger myDragger;
  34012. void mouseDown (const MouseEvent& e)
  34013. {
  34014. myDragger.startDraggingComponent (this, 0);
  34015. }
  34016. void mouseDrag (const MouseEvent& e)
  34017. {
  34018. myDragger.dragComponent (this, e);
  34019. }
  34020. };
  34021. @endcode
  34022. */
  34023. class JUCE_API ComponentDragger
  34024. {
  34025. public:
  34026. /** Creates a ComponentDragger. */
  34027. ComponentDragger();
  34028. /** Destructor. */
  34029. virtual ~ComponentDragger();
  34030. /** Call this from your component's mouseDown() method, to prepare for dragging.
  34031. @param componentToDrag the component that you want to drag
  34032. @param constrainer a constrainer object to use to keep the component
  34033. from going offscreen
  34034. @see dragComponent
  34035. */
  34036. void startDraggingComponent (Component* const componentToDrag,
  34037. ComponentBoundsConstrainer* constrainer);
  34038. /** Call this from your mouseDrag() callback to move the component.
  34039. This will move the component, but will first check the validity of the
  34040. component's new position using the checkPosition() method, which you
  34041. can override if you need to enforce special positioning limits on the
  34042. component.
  34043. @param componentToDrag the component that you want to drag
  34044. @param e the current mouse-drag event
  34045. @see dragComponent
  34046. */
  34047. void dragComponent (Component* const componentToDrag,
  34048. const MouseEvent& e);
  34049. juce_UseDebuggingNewOperator
  34050. private:
  34051. ComponentBoundsConstrainer* constrainer;
  34052. int originalX, originalY;
  34053. };
  34054. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34055. /********* End of inlined file: juce_ComponentDragger.h *********/
  34056. #endif
  34057. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  34058. #endif
  34059. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  34060. #endif
  34061. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34062. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  34063. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34064. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34065. /**
  34066. Components derived from this class can have files dropped onto them by an external application.
  34067. @see DragAndDropContainer
  34068. */
  34069. class JUCE_API FileDragAndDropTarget
  34070. {
  34071. public:
  34072. /** Destructor. */
  34073. virtual ~FileDragAndDropTarget() {}
  34074. /** Callback to check whether this target is interested in the set of files being offered.
  34075. Note that this will be called repeatedly when the user is dragging the mouse around over your
  34076. component, so don't do anything time-consuming in here, like opening the files to have a look
  34077. inside them!
  34078. @param files the set of (absolute) pathnames of the files that the user is dragging
  34079. @returns true if this component wants to receive the other callbacks regarging this
  34080. type of object; if it returns false, no other callbacks will be made.
  34081. */
  34082. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  34083. /** Callback to indicate that some files are being dragged over this component.
  34084. This gets called when the user moves the mouse into this component while dragging.
  34085. Use this callback as a trigger to make your component repaint itself to give the
  34086. user feedback about whether the files can be dropped here or not.
  34087. @param files the set of (absolute) pathnames of the files that the user is dragging
  34088. @param x the mouse x position, relative to this component
  34089. @param y the mouse y position, relative to this component
  34090. */
  34091. virtual void fileDragEnter (const StringArray& files, int x, int y);
  34092. /** Callback to indicate that the user is dragging some files over this component.
  34093. This gets called when the user moves the mouse over this component while dragging.
  34094. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  34095. this lets you know what happens in-between.
  34096. @param files the set of (absolute) pathnames of the files that the user is dragging
  34097. @param x the mouse x position, relative to this component
  34098. @param y the mouse y position, relative to this component
  34099. */
  34100. virtual void fileDragMove (const StringArray& files, int x, int y);
  34101. /** Callback to indicate that the mouse has moved away from this component.
  34102. This gets called when the user moves the mouse out of this component while dragging
  34103. the files.
  34104. If you've used fileDragEnter() to repaint your component and give feedback, use this
  34105. as a signal to repaint it in its normal state.
  34106. @param files the set of (absolute) pathnames of the files that the user is dragging
  34107. */
  34108. virtual void fileDragExit (const StringArray& files);
  34109. /** Callback to indicate that the user has dropped the files onto this component.
  34110. When the user drops the files, this get called, and you can use the files in whatever
  34111. way is appropriate.
  34112. Note that after this is called, the fileDragExit method may not be called, so you should
  34113. clean up in here if there's anything you need to do when the drag finishes.
  34114. @param files the set of (absolute) pathnames of the files that the user is dragging
  34115. @param x the mouse x position, relative to this component
  34116. @param y the mouse y position, relative to this component
  34117. */
  34118. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  34119. };
  34120. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34121. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  34122. #endif
  34123. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34124. /********* Start of inlined file: juce_LassoComponent.h *********/
  34125. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34126. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34127. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  34128. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  34129. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  34130. /** Manages a list of selectable items.
  34131. Use one of these to keep a track of things that the user has highlighted, like
  34132. icons or things in a list.
  34133. The class is templated so that you can use it to hold either a set of pointers
  34134. to objects, or a set of ID numbers or handles, for cases where each item may
  34135. not always have a corresponding object.
  34136. To be informed when items are selected/deselected, register a ChangeListener with
  34137. this object.
  34138. @see SelectableObject
  34139. */
  34140. template <class SelectableItemType>
  34141. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  34142. {
  34143. public:
  34144. /** Creates an empty set. */
  34145. SelectedItemSet()
  34146. {
  34147. }
  34148. /** Creates a set based on an array of items. */
  34149. SelectedItemSet (const Array <SelectableItemType>& items)
  34150. : selectedItems (items)
  34151. {
  34152. }
  34153. /** Creates a copy of another set. */
  34154. SelectedItemSet (const SelectedItemSet& other)
  34155. : selectedItems (other.selectedItems)
  34156. {
  34157. }
  34158. /** Creates a copy of another set. */
  34159. const SelectedItemSet& operator= (const SelectedItemSet& other)
  34160. {
  34161. if (selectedItems != other.selectedItems)
  34162. {
  34163. selectedItems = other.selectedItems;
  34164. changed();
  34165. }
  34166. return *this;
  34167. }
  34168. /** Destructor. */
  34169. ~SelectedItemSet()
  34170. {
  34171. }
  34172. /** Clears any other currently selected items, and selects this item.
  34173. If this item is already the only thing selected, no change notification
  34174. will be sent out.
  34175. @see addToSelection, addToSelectionBasedOnModifiers
  34176. */
  34177. void selectOnly (SelectableItemType item)
  34178. {
  34179. if (isSelected (item))
  34180. {
  34181. for (int i = selectedItems.size(); --i >= 0;)
  34182. {
  34183. if (selectedItems.getUnchecked(i) != item)
  34184. {
  34185. deselect (selectedItems.getUnchecked(i));
  34186. i = jmin (i, selectedItems.size());
  34187. }
  34188. }
  34189. }
  34190. else
  34191. {
  34192. deselectAll();
  34193. changed();
  34194. selectedItems.add (item);
  34195. itemSelected (item);
  34196. }
  34197. }
  34198. /** Selects an item.
  34199. If the item is already selected, no change notification will be sent out.
  34200. @see selectOnly, addToSelectionBasedOnModifiers
  34201. */
  34202. void addToSelection (SelectableItemType item)
  34203. {
  34204. if (! isSelected (item))
  34205. {
  34206. changed();
  34207. selectedItems.add (item);
  34208. itemSelected (item);
  34209. }
  34210. }
  34211. /** Selects or deselects an item.
  34212. This will use the modifier keys to decide whether to deselect other items
  34213. first.
  34214. So if the shift key is held down, the item will be added without deselecting
  34215. anything (same as calling addToSelection() )
  34216. If no modifiers are down, the current selection will be cleared first (same
  34217. as calling selectOnly() )
  34218. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  34219. so it'll be added to the set unless it's already there, in which case it'll be
  34220. deselected.
  34221. If the items that you're selecting can also be dragged, you may need to use the
  34222. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  34223. subtleties of this kind of usage.
  34224. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  34225. */
  34226. void addToSelectionBasedOnModifiers (SelectableItemType item,
  34227. const ModifierKeys& modifiers)
  34228. {
  34229. if (modifiers.isShiftDown())
  34230. {
  34231. addToSelection (item);
  34232. }
  34233. else if (modifiers.isCommandDown())
  34234. {
  34235. if (isSelected (item))
  34236. deselect (item);
  34237. else
  34238. addToSelection (item);
  34239. }
  34240. else
  34241. {
  34242. selectOnly (item);
  34243. }
  34244. }
  34245. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  34246. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  34247. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  34248. makes it easy to handle multiple-selection of sets of objects that can also
  34249. be dragged.
  34250. For example, if you have several items already selected, and you click on
  34251. one of them (without dragging), then you'd expect this to deselect the other, and
  34252. just select the item you clicked on. But if you had clicked on this item and
  34253. dragged it, you'd have expected them all to stay selected.
  34254. When you call this method, you'll need to store the boolean result, because the
  34255. addToSelectionOnMouseUp() method will need to be know this value.
  34256. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  34257. */
  34258. bool addToSelectionOnMouseDown (SelectableItemType item,
  34259. const ModifierKeys& modifiers)
  34260. {
  34261. if (isSelected (item))
  34262. {
  34263. return ! modifiers.isPopupMenu();
  34264. }
  34265. else
  34266. {
  34267. addToSelectionBasedOnModifiers (item, modifiers);
  34268. return false;
  34269. }
  34270. }
  34271. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  34272. Call this during a mouseUp callback, when you have previously called the
  34273. addToSelectionOnMouseDown() method during your mouseDown event.
  34274. See addToSelectionOnMouseDown() for more info
  34275. @param item the item to select (or deselect)
  34276. @param modifiers the modifiers from the mouse-up event
  34277. @param wasItemDragged true if your item was dragged during the mouse click
  34278. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  34279. back from the addToSelectionOnMouseDown() call that you
  34280. should have made during the matching mouseDown event
  34281. */
  34282. void addToSelectionOnMouseUp (SelectableItemType item,
  34283. const ModifierKeys& modifiers,
  34284. const bool wasItemDragged,
  34285. const bool resultOfMouseDownSelectMethod)
  34286. {
  34287. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  34288. addToSelectionBasedOnModifiers (item, modifiers);
  34289. }
  34290. /** Deselects an item. */
  34291. void deselect (SelectableItemType item)
  34292. {
  34293. const int i = selectedItems.indexOf (item);
  34294. if (i >= 0)
  34295. {
  34296. changed();
  34297. itemDeselected (selectedItems.remove (i));
  34298. }
  34299. }
  34300. /** Deselects all items. */
  34301. void deselectAll()
  34302. {
  34303. if (selectedItems.size() > 0)
  34304. {
  34305. changed();
  34306. for (int i = selectedItems.size(); --i >= 0;)
  34307. {
  34308. itemDeselected (selectedItems.remove (i));
  34309. i = jmin (i, selectedItems.size());
  34310. }
  34311. }
  34312. }
  34313. /** Returns the number of currently selected items.
  34314. @see getSelectedItem
  34315. */
  34316. int getNumSelected() const throw()
  34317. {
  34318. return selectedItems.size();
  34319. }
  34320. /** Returns one of the currently selected items.
  34321. Returns 0 if the index is out-of-range.
  34322. @see getNumSelected
  34323. */
  34324. SelectableItemType getSelectedItem (const int index) const throw()
  34325. {
  34326. return selectedItems [index];
  34327. }
  34328. /** True if this item is currently selected. */
  34329. bool isSelected (const SelectableItemType item) const throw()
  34330. {
  34331. return selectedItems.contains (item);
  34332. }
  34333. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  34334. /** Can be overridden to do special handling when an item is selected.
  34335. For example, if the item is an object, you might want to call it and tell
  34336. it that it's being selected.
  34337. */
  34338. virtual void itemSelected (SelectableItemType item) {}
  34339. /** Can be overridden to do special handling when an item is deselected.
  34340. For example, if the item is an object, you might want to call it and tell
  34341. it that it's being deselected.
  34342. */
  34343. virtual void itemDeselected (SelectableItemType item) {}
  34344. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  34345. */
  34346. void changed (const bool synchronous = false)
  34347. {
  34348. if (synchronous)
  34349. sendSynchronousChangeMessage (this);
  34350. else
  34351. sendChangeMessage (this);
  34352. }
  34353. juce_UseDebuggingNewOperator
  34354. private:
  34355. Array <SelectableItemType> selectedItems;
  34356. };
  34357. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  34358. /********* End of inlined file: juce_SelectedItemSet.h *********/
  34359. /**
  34360. A class used by the LassoComponent to manage the things that it selects.
  34361. This allows the LassoComponent to find out which items are within the lasso,
  34362. and to change the list of selected items.
  34363. @see LassoComponent, SelectedItemSet
  34364. */
  34365. template <class SelectableItemType>
  34366. class LassoSource
  34367. {
  34368. public:
  34369. /** Destructor. */
  34370. virtual ~LassoSource() {}
  34371. /** Returns the set of items that lie within a given lassoable region.
  34372. Your implementation of this method must find all the relevent items that lie
  34373. within the given rectangle. and add them to the itemsFound array.
  34374. The co-ordinates are relative to the top-left of the lasso component's parent
  34375. component. (i.e. they are the same as the size and position of the lasso
  34376. component itself).
  34377. */
  34378. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  34379. int x, int y, int width, int height) = 0;
  34380. /** Returns the SelectedItemSet that the lasso should update.
  34381. This set will be continuously updated by the LassoComponent as it gets
  34382. dragged around, so make sure that you've got a ChangeListener attached to
  34383. the set so that your UI objects will know when the selection changes and
  34384. be able to update themselves appropriately.
  34385. */
  34386. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  34387. };
  34388. /**
  34389. A component that acts as a rectangular selection region, which you drag with
  34390. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  34391. To use one of these:
  34392. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  34393. component, and call its beginLasso() method, giving it a
  34394. suitable LassoSource object that it can use to find out which items are in
  34395. the active area.
  34396. - Each time your parent component gets a mouseDrag event, call dragLasso()
  34397. to update the lasso's position - it will use its LassoSource to calculate and
  34398. update the current selection.
  34399. - After the drag has finished and you get a mouseUp callback, you should call
  34400. endLasso() to clean up. This will make the lasso component invisible, and you
  34401. can remove it from the parent component, or delete it.
  34402. The class takes into account the modifier keys that are being held down while
  34403. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  34404. be added to the original selection; if ctrl or command is pressed, they will be
  34405. xor'ed with any previously selected items.
  34406. @see LassoSource, SelectedItemSet
  34407. */
  34408. template <class SelectableItemType>
  34409. class LassoComponent : public Component
  34410. {
  34411. public:
  34412. /** Creates a Lasso component.
  34413. The fill colour is used to fill the lasso'ed rectangle, and the outline
  34414. colour is used to draw a line around its edge.
  34415. */
  34416. LassoComponent (const int outlineThickness_ = 1)
  34417. : source (0),
  34418. outlineThickness (outlineThickness_)
  34419. {
  34420. }
  34421. /** Destructor. */
  34422. ~LassoComponent()
  34423. {
  34424. }
  34425. /** Call this in your mouseDown event, to initialise a drag.
  34426. Pass in a suitable LassoSource object which the lasso will use to find
  34427. the items and change the selection.
  34428. After using this method to initialise the lasso, repeatedly call dragLasso()
  34429. in your component's mouseDrag callback.
  34430. @see dragLasso, endLasso, LassoSource
  34431. */
  34432. void beginLasso (const MouseEvent& e,
  34433. LassoSource <SelectableItemType>* const lassoSource)
  34434. {
  34435. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  34436. jassert (lassoSource != 0); // the source can't be null!
  34437. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  34438. source = lassoSource;
  34439. if (lassoSource != 0)
  34440. originalSelection = lassoSource->getLassoSelection().getItemArray();
  34441. setSize (0, 0);
  34442. }
  34443. /** Call this in your mouseDrag event, to update the lasso's position.
  34444. This must be repeatedly calling when the mouse is dragged, after you've
  34445. first initialised the lasso with beginLasso().
  34446. This method takes into account the modifier keys that are being held down, so
  34447. if shift is pressed, then the lassoed items will be added to any that were
  34448. previously selected; if ctrl or command is pressed, then they will be xor'ed
  34449. with previously selected items.
  34450. @see beginLasso, endLasso
  34451. */
  34452. void dragLasso (const MouseEvent& e)
  34453. {
  34454. if (source != 0)
  34455. {
  34456. const int x1 = e.getMouseDownX();
  34457. const int y1 = e.getMouseDownY();
  34458. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  34459. setVisible (true);
  34460. Array <SelectableItemType> itemsInLasso;
  34461. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  34462. if (e.mods.isShiftDown())
  34463. {
  34464. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  34465. itemsInLasso.addArray (originalSelection);
  34466. }
  34467. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  34468. {
  34469. Array <SelectableItemType> originalMinusNew (originalSelection);
  34470. originalMinusNew.removeValuesIn (itemsInLasso);
  34471. itemsInLasso.removeValuesIn (originalSelection);
  34472. itemsInLasso.addArray (originalMinusNew);
  34473. }
  34474. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  34475. }
  34476. }
  34477. /** Call this in your mouseUp event, after the lasso has been dragged.
  34478. @see beginLasso, dragLasso
  34479. */
  34480. void endLasso()
  34481. {
  34482. source = 0;
  34483. originalSelection.clear();
  34484. setVisible (false);
  34485. }
  34486. /** A set of colour IDs to use to change the colour of various aspects of the label.
  34487. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34488. methods.
  34489. Note that you can also use the constants from TextEditor::ColourIds to change the
  34490. colour of the text editor that is opened when a label is editable.
  34491. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34492. */
  34493. enum ColourIds
  34494. {
  34495. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  34496. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  34497. };
  34498. /** @internal */
  34499. void paint (Graphics& g)
  34500. {
  34501. g.fillAll (findColour (lassoFillColourId));
  34502. g.setColour (findColour (lassoOutlineColourId));
  34503. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  34504. // this suggests that you've left a lasso comp lying around after the
  34505. // mouse drag has finished.. Be careful to call endLasso() when you get a
  34506. // mouse-up event.
  34507. jassert (isMouseButtonDownAnywhere());
  34508. }
  34509. /** @internal */
  34510. bool hitTest (int x, int y) { return false; }
  34511. juce_UseDebuggingNewOperator
  34512. private:
  34513. Array <SelectableItemType> originalSelection;
  34514. LassoSource <SelectableItemType>* source;
  34515. int outlineThickness;
  34516. };
  34517. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34518. /********* End of inlined file: juce_LassoComponent.h *********/
  34519. #endif
  34520. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  34521. #endif
  34522. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  34523. #endif
  34524. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34525. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  34526. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34527. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34528. /**
  34529. Monitors a component for mouse activity, and triggers a callback
  34530. when the mouse hovers in one place for a specified length of time.
  34531. To use a hover-detector, just create one and call its setHoverComponent()
  34532. method to start it watching a component. You can call setHoverComponent (0)
  34533. to make it inactive.
  34534. (Be careful not to delete a component that's being monitored without first
  34535. stopping or deleting the hover detector).
  34536. */
  34537. class JUCE_API MouseHoverDetector
  34538. {
  34539. public:
  34540. /** Creates a hover detector.
  34541. Initially the object is inactive, and you need to tell it which component
  34542. to monitor, using the setHoverComponent() method.
  34543. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  34544. needs to stay still before the mouseHovered() method
  34545. is invoked. You can change this setting later with
  34546. the setHoverTimeMillisecs() method
  34547. */
  34548. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  34549. /** Destructor. */
  34550. virtual ~MouseHoverDetector();
  34551. /** Changes the time for which the mouse has to stay still before it's considered
  34552. to be hovering.
  34553. */
  34554. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  34555. /** Changes the component that's being monitored for hovering.
  34556. Be careful not to delete a component that's being monitored without first
  34557. stopping or deleting the hover detector.
  34558. */
  34559. void setHoverComponent (Component* const newSourceComponent);
  34560. protected:
  34561. /** Called back when the mouse hovers.
  34562. After the mouse has stayed still over the component for the length of time
  34563. specified by setHoverTimeMillisecs(), this method will be invoked.
  34564. When the mouse is first moved after this callback has occurred, the
  34565. mouseMovedAfterHover() method will be called.
  34566. @param mouseX the mouse's X position relative to the component being monitored
  34567. @param mouseY the mouse's Y position relative to the component being monitored
  34568. */
  34569. virtual void mouseHovered (int mouseX,
  34570. int mouseY) = 0;
  34571. /** Called when the mouse is moved away after just having hovered. */
  34572. virtual void mouseMovedAfterHover() = 0;
  34573. private:
  34574. class JUCE_API HoverDetectorInternal : public MouseListener,
  34575. public Timer
  34576. {
  34577. public:
  34578. MouseHoverDetector* owner;
  34579. int lastX, lastY;
  34580. void timerCallback();
  34581. void mouseEnter (const MouseEvent&);
  34582. void mouseExit (const MouseEvent&);
  34583. void mouseDown (const MouseEvent&);
  34584. void mouseUp (const MouseEvent&);
  34585. void mouseMove (const MouseEvent&);
  34586. void mouseWheelMove (const MouseEvent&, float, float);
  34587. } internalTimer;
  34588. friend class HoverDetectorInternal;
  34589. Component* source;
  34590. int hoverTimeMillisecs;
  34591. bool hasJustHovered;
  34592. void hoverTimerCallback();
  34593. void checkJustHoveredCallback();
  34594. };
  34595. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34596. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  34597. #endif
  34598. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  34599. #endif
  34600. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  34601. #endif
  34602. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34603. #endif
  34604. #ifndef __JUCE_LABEL_JUCEHEADER__
  34605. #endif
  34606. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34607. #endif
  34608. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34609. /********* Start of inlined file: juce_ProgressBar.h *********/
  34610. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34611. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34612. /**
  34613. A progress bar component.
  34614. To use this, just create one and make it visible. It'll run its own timer
  34615. to keep an eye on a variable that you give it, and will automatically
  34616. redraw itself when the variable changes.
  34617. For an easy way of running a background task with a dialog box showing its
  34618. progress, see the ThreadWithProgressWindow class.
  34619. @see ThreadWithProgressWindow
  34620. */
  34621. class JUCE_API ProgressBar : public Component,
  34622. public SettableTooltipClient,
  34623. private Timer
  34624. {
  34625. public:
  34626. /** Creates a ProgressBar.
  34627. @param progress pass in a reference to a double that you're going to
  34628. update with your task's progress. The ProgressBar will
  34629. monitor the value of this variable and will redraw itself
  34630. when the value changes. The range is from 0 to 1.0. Obviously
  34631. you'd better be careful not to delete this variable while the
  34632. ProgressBar still exists!
  34633. */
  34634. ProgressBar (double& progress);
  34635. /** Destructor. */
  34636. ~ProgressBar();
  34637. /** Turns the percentage display on or off.
  34638. By default this is on, and the progress bar will display a text string showing
  34639. its current percentage.
  34640. */
  34641. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34642. /** Gives the progress bar a string to display inside it.
  34643. If you call this, it will turn off the percentage display.
  34644. @see setPercentageDisplay
  34645. */
  34646. void setTextToDisplay (const String& text);
  34647. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34648. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34649. methods.
  34650. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34651. */
  34652. enum ColourIds
  34653. {
  34654. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34655. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34656. classes will probably use variations on this colour. */
  34657. };
  34658. juce_UseDebuggingNewOperator
  34659. protected:
  34660. /** @internal */
  34661. void paint (Graphics& g);
  34662. /** @internal */
  34663. void lookAndFeelChanged();
  34664. /** @internal */
  34665. void visibilityChanged();
  34666. /** @internal */
  34667. void colourChanged();
  34668. private:
  34669. double& progress;
  34670. double currentValue;
  34671. bool displayPercentage;
  34672. String displayedMessage, currentMessage;
  34673. uint32 lastCallbackTime;
  34674. void timerCallback();
  34675. ProgressBar (const ProgressBar&);
  34676. const ProgressBar& operator= (const ProgressBar&);
  34677. };
  34678. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34679. /********* End of inlined file: juce_ProgressBar.h *********/
  34680. #endif
  34681. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34682. /********* Start of inlined file: juce_Slider.h *********/
  34683. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34684. #define __JUCE_SLIDER_JUCEHEADER__
  34685. /********* Start of inlined file: juce_SliderListener.h *********/
  34686. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34687. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34688. class Slider;
  34689. /**
  34690. A class for receiving callbacks from a Slider.
  34691. To be told when a slider's value changes, you can register a SliderListener
  34692. object using Slider::addListener().
  34693. @see Slider::addListener, Slider::removeListener
  34694. */
  34695. class JUCE_API SliderListener
  34696. {
  34697. public:
  34698. /** Destructor. */
  34699. virtual ~SliderListener() {}
  34700. /** Called when the slider's value is changed.
  34701. This may be caused by dragging it, or by typing in its text entry box,
  34702. or by a call to Slider::setValue().
  34703. You can find out the new value using Slider::getValue().
  34704. @see Slider::valueChanged
  34705. */
  34706. virtual void sliderValueChanged (Slider* slider) = 0;
  34707. /** Called when the slider is about to be dragged.
  34708. This is called when a drag begins, then it's followed by multiple calls
  34709. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34710. user lets go.
  34711. @see sliderDragEnded, Slider::startedDragging
  34712. */
  34713. virtual void sliderDragStarted (Slider* slider);
  34714. /** Called after a drag operation has finished.
  34715. @see sliderDragStarted, Slider::stoppedDragging
  34716. */
  34717. virtual void sliderDragEnded (Slider* slider);
  34718. };
  34719. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34720. /********* End of inlined file: juce_SliderListener.h *********/
  34721. /**
  34722. A slider control for changing a value.
  34723. The slider can be horizontal, vertical, or rotary, and can optionally have
  34724. a text-box inside it to show an editable display of the current value.
  34725. To use it, create a Slider object and use the setSliderStyle() method
  34726. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34727. To define the values that it can be set to, see the setRange() and setValue() methods.
  34728. There are also lots of custom tweaks you can do by subclassing and overriding
  34729. some of the virtual methods, such as changing the scaling, changing the format of
  34730. the text display, custom ways of limiting the values, etc.
  34731. You can register SliderListeners with a slider, which will be informed when the value
  34732. changes, or a subclass can override valueChanged() to be informed synchronously.
  34733. @see SliderListener
  34734. */
  34735. class JUCE_API Slider : public Component,
  34736. public SettableTooltipClient,
  34737. private AsyncUpdater,
  34738. private ButtonListener,
  34739. private LabelListener
  34740. {
  34741. public:
  34742. /** Creates a slider.
  34743. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34744. setRange(), etc.
  34745. */
  34746. Slider (const String& componentName);
  34747. /** Destructor. */
  34748. ~Slider();
  34749. /** The types of slider available.
  34750. @see setSliderStyle, setRotaryParameters
  34751. */
  34752. enum SliderStyle
  34753. {
  34754. LinearHorizontal, /**< A traditional horizontal slider. */
  34755. LinearVertical, /**< A traditional vertical slider. */
  34756. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34757. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34758. @see setRotaryParameters */
  34759. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34760. @see setRotaryParameters */
  34761. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34762. @see setRotaryParameters */
  34763. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34764. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34765. @see setMinValue, setMaxValue */
  34766. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34767. @see setMinValue, setMaxValue */
  34768. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34769. value, with the current value being somewhere between them.
  34770. @see setMinValue, setMaxValue */
  34771. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34772. value, with the current value being somewhere between them.
  34773. @see setMinValue, setMaxValue */
  34774. };
  34775. /** Changes the type of slider interface being used.
  34776. @param newStyle the type of interface
  34777. @see setRotaryParameters, setVelocityBasedMode,
  34778. */
  34779. void setSliderStyle (const SliderStyle newStyle);
  34780. /** Returns the slider's current style.
  34781. @see setSliderStyle
  34782. */
  34783. SliderStyle getSliderStyle() const throw() { return style; }
  34784. /** Changes the properties of a rotary slider.
  34785. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34786. the slider's minimum value is represented
  34787. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34788. the slider's maximum value is represented. This must be
  34789. greater than startAngleRadians
  34790. @param stopAtEnd if true, then when the slider is dragged around past the
  34791. minimum or maximum, it'll stop there; if false, it'll wrap
  34792. back to the opposite value
  34793. */
  34794. void setRotaryParameters (const float startAngleRadians,
  34795. const float endAngleRadians,
  34796. const bool stopAtEnd);
  34797. /** Sets the distance the mouse has to move to drag the slider across
  34798. the full extent of its range.
  34799. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34800. relative mouse movements to adjust the slider.
  34801. */
  34802. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  34803. /** Changes the way the the mouse is used when dragging the slider.
  34804. If true, this will turn on velocity-sensitive dragging, so that
  34805. the faster the mouse moves, the bigger the movement to the slider. This
  34806. helps when making accurate adjustments if the slider's range is quite large.
  34807. If false, the slider will just try to snap to wherever the mouse is.
  34808. */
  34809. void setVelocityBasedMode (const bool isVelocityBased) throw();
  34810. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34811. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34812. or if you're holding down ctrl.
  34813. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34814. @param threshold the minimum number of pixels that the mouse needs to move for it
  34815. to be treated as a movement
  34816. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34817. the threshold is reached
  34818. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34819. key to toggle velocity-sensitive mode
  34820. */
  34821. void setVelocityModeParameters (const double sensitivity = 1.0,
  34822. const int threshold = 1,
  34823. const double offset = 0.0,
  34824. const bool userCanPressKeyToSwapMode = true) throw();
  34825. /** Sets up a skew factor to alter the way values are distributed.
  34826. You may want to use a range of values on the slider where more accuracy
  34827. is required towards one end of the range, so this will logarithmically
  34828. spread the values across the length of the slider.
  34829. If the factor is < 1.0, the lower end of the range will fill more of the
  34830. slider's length; if the factor is > 1.0, the upper end of the range
  34831. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34832. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34833. method instead.
  34834. @see getSkewFactor, setSkewFactorFromMidPoint
  34835. */
  34836. void setSkewFactor (const double factor) throw();
  34837. /** Sets up a skew factor to alter the way values are distributed.
  34838. This allows you to specify the slider value that should appear in the
  34839. centre of the slider's visible range.
  34840. @see setSkewFactor, getSkewFactor
  34841. */
  34842. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  34843. /** Returns the current skew factor.
  34844. See setSkewFactor for more info.
  34845. @see setSkewFactor, setSkewFactorFromMidPoint
  34846. */
  34847. double getSkewFactor() const throw() { return skewFactor; }
  34848. /** Used by setIncDecButtonsMode().
  34849. */
  34850. enum IncDecButtonMode
  34851. {
  34852. incDecButtonsNotDraggable,
  34853. incDecButtonsDraggable_AutoDirection,
  34854. incDecButtonsDraggable_Horizontal,
  34855. incDecButtonsDraggable_Vertical
  34856. };
  34857. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34858. can be dragged on the buttons to drag the values.
  34859. By default this is turned off. When enabled, clicking on the buttons still works
  34860. them as normal, but by holding down the mouse on a button and dragging it a little
  34861. distance, it flips into a mode where the value can be dragged. The drag direction can
  34862. either be set explicitly to be vertical or horizontal, or can be set to
  34863. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34864. are side-by-side or above each other.
  34865. */
  34866. void setIncDecButtonsMode (const IncDecButtonMode mode);
  34867. /** The position of the slider's text-entry box.
  34868. @see setTextBoxStyle
  34869. */
  34870. enum TextEntryBoxPosition
  34871. {
  34872. NoTextBox, /**< Doesn't display a text box. */
  34873. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34874. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34875. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34876. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34877. };
  34878. /** Changes the location and properties of the text-entry box.
  34879. @param newPosition where it should go (or NoTextBox to not have one at all)
  34880. @param isReadOnly if true, it's a read-only display
  34881. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34882. room for the slider as well!
  34883. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34884. room for the slider as well!
  34885. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34886. */
  34887. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34888. const bool isReadOnly,
  34889. const int textEntryBoxWidth,
  34890. const int textEntryBoxHeight);
  34891. /** Returns the status of the text-box.
  34892. @see setTextBoxStyle
  34893. */
  34894. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  34895. /** Returns the width used for the text-box.
  34896. @see setTextBoxStyle
  34897. */
  34898. int getTextBoxWidth() const throw() { return textBoxWidth; }
  34899. /** Returns the height used for the text-box.
  34900. @see setTextBoxStyle
  34901. */
  34902. int getTextBoxHeight() const throw() { return textBoxHeight; }
  34903. /** Makes the text-box editable.
  34904. By default this is true, and the user can enter values into the textbox,
  34905. but it can be turned off if that's not suitable.
  34906. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34907. */
  34908. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  34909. /** Returns true if the text-box is read-only.
  34910. @see setTextBoxStyle
  34911. */
  34912. bool isTextBoxEditable() const throw() { return editableText; }
  34913. /** If the text-box is editable, this will give it the focus so that the user can
  34914. type directly into it.
  34915. This is basically the effect as the user clicking on it.
  34916. */
  34917. void showTextBox();
  34918. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34919. focus away from it.
  34920. @param discardCurrentEditorContents if true, the slider's value will be left
  34921. unchanged; if false, the current contents of the
  34922. text editor will be used to set the slider position
  34923. before it is hidden.
  34924. */
  34925. void hideTextBox (const bool discardCurrentEditorContents);
  34926. /** Changes the slider's current value.
  34927. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34928. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34929. want to handle it.
  34930. @param newValue the new value to set - this will be restricted by the
  34931. minimum and maximum range, and will be snapped to the
  34932. nearest interval if one has been set
  34933. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34934. any SliderListeners or the valueChanged() method
  34935. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34936. synchronously; if false, it will be asynchronous
  34937. */
  34938. void setValue (double newValue,
  34939. const bool sendUpdateMessage = true,
  34940. const bool sendMessageSynchronously = false);
  34941. /** Returns the slider's current value. */
  34942. double getValue() const throw();
  34943. /** Sets the limits that the slider's value can take.
  34944. @param newMinimum the lowest value allowed
  34945. @param newMaximum the highest value allowed
  34946. @param newInterval the steps in which the value is allowed to increase - if this
  34947. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34948. */
  34949. void setRange (const double newMinimum,
  34950. const double newMaximum,
  34951. const double newInterval = 0);
  34952. /** Returns the current maximum value.
  34953. @see setRange
  34954. */
  34955. double getMaximum() const throw() { return maximum; }
  34956. /** Returns the current minimum value.
  34957. @see setRange
  34958. */
  34959. double getMinimum() const throw() { return minimum; }
  34960. /** Returns the current step-size for values.
  34961. @see setRange
  34962. */
  34963. double getInterval() const throw() { return interval; }
  34964. /** For a slider with two or three thumbs, this returns the lower of its values.
  34965. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34966. A slider with three values also uses the normal getValue() and setValue() methods to
  34967. control the middle value.
  34968. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34969. */
  34970. double getMinValue() const throw();
  34971. /** For a slider with two or three thumbs, this sets the lower of its values.
  34972. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34973. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34974. want to handle it.
  34975. @param newValue the new value to set - this will be restricted by the
  34976. minimum and maximum range, and will be snapped to the nearest
  34977. interval if one has been set.
  34978. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34979. any SliderListeners or the valueChanged() method
  34980. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34981. synchronously; if false, it will be asynchronous
  34982. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34983. max value (in a two-value slider) or the mid value (in a three-value
  34984. slider). If false, then if this value goes beyond those values,
  34985. it will push them along with it.
  34986. @see getMinValue, setMaxValue, setValue
  34987. */
  34988. void setMinValue (double newValue,
  34989. const bool sendUpdateMessage = true,
  34990. const bool sendMessageSynchronously = false,
  34991. const bool allowNudgingOfOtherValues = false);
  34992. /** For a slider with two or three thumbs, this returns the higher of its values.
  34993. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34994. A slider with three values also uses the normal getValue() and setValue() methods to
  34995. control the middle value.
  34996. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34997. */
  34998. double getMaxValue() const throw();
  34999. /** For a slider with two or three thumbs, this sets the lower of its values.
  35000. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  35001. that are registered, and will synchronously call the valueChanged() method in case subclasses
  35002. want to handle it.
  35003. @param newValue the new value to set - this will be restricted by the
  35004. minimum and maximum range, and will be snapped to the nearest
  35005. interval if one has been set.
  35006. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  35007. any SliderListeners or the valueChanged() method
  35008. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  35009. synchronously; if false, it will be asynchronous
  35010. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  35011. min value (in a two-value slider) or the mid value (in a three-value
  35012. slider). If false, then if this value goes beyond those values,
  35013. it will push them along with it.
  35014. @see getMaxValue, setMinValue, setValue
  35015. */
  35016. void setMaxValue (double newValue,
  35017. const bool sendUpdateMessage = true,
  35018. const bool sendMessageSynchronously = false,
  35019. const bool allowNudgingOfOtherValues = false);
  35020. /** Adds a listener to be called when this slider's value changes. */
  35021. void addListener (SliderListener* const listener) throw();
  35022. /** Removes a previously-registered listener. */
  35023. void removeListener (SliderListener* const listener) throw();
  35024. /** This lets you choose whether double-clicking moves the slider to a given position.
  35025. By default this is turned off, but it's handy if you want a double-click to act
  35026. as a quick way of resetting a slider. Just pass in the value you want it to
  35027. go to when double-clicked.
  35028. @see getDoubleClickReturnValue
  35029. */
  35030. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  35031. const double valueToSetOnDoubleClick) throw();
  35032. /** Returns the values last set by setDoubleClickReturnValue() method.
  35033. Sets isEnabled to true if double-click is enabled, and returns the value
  35034. that was set.
  35035. @see setDoubleClickReturnValue
  35036. */
  35037. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  35038. /** Tells the slider whether to keep sending change messages while the user
  35039. is dragging the slider.
  35040. If set to true, a change message will only be sent when the user has
  35041. dragged the slider and let go. If set to false (the default), then messages
  35042. will be continuously sent as they drag it while the mouse button is still
  35043. held down.
  35044. */
  35045. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  35046. /** This lets you change whether the slider thumb jumps to the mouse position
  35047. when you click.
  35048. By default, this is true. If it's false, then the slider moves with relative
  35049. motion when you drag it.
  35050. This only applies to linear bars, and won't affect two- or three- value
  35051. sliders.
  35052. */
  35053. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  35054. /** If enabled, this gives the slider a pop-up bubble which appears while the
  35055. slider is being dragged.
  35056. This can be handy if your slider doesn't have a text-box, so that users can
  35057. see the value just when they're changing it.
  35058. If you pass a component as the parentComponentToUse parameter, the pop-up
  35059. bubble will be added as a child of that component when it's needed. If you
  35060. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  35061. transparent window, so if you're using an OS that can't do transparent windows
  35062. you'll have to add it to a parent component instead).
  35063. */
  35064. void setPopupDisplayEnabled (const bool isEnabled,
  35065. Component* const parentComponentToUse) throw();
  35066. /** If this is set to true, then right-clicking on the slider will pop-up
  35067. a menu to let the user change the way it works.
  35068. By default this is turned off, but when turned on, the menu will include
  35069. things like velocity sensitivity, and for rotary sliders, whether they
  35070. use a linear or rotary mouse-drag to move them.
  35071. */
  35072. void setPopupMenuEnabled (const bool menuEnabled) throw();
  35073. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  35074. By default it's enabled.
  35075. */
  35076. void setScrollWheelEnabled (const bool enabled) throw();
  35077. /** Returns a number to indicate which thumb is currently being dragged by the
  35078. mouse.
  35079. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  35080. the maximum-value thumb, or -1 if none is currently down.
  35081. */
  35082. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  35083. /** Callback to indicate that the user is about to start dragging the slider.
  35084. @see SliderListener::sliderDragStarted
  35085. */
  35086. virtual void startedDragging();
  35087. /** Callback to indicate that the user has just stopped dragging the slider.
  35088. @see SliderListener::sliderDragEnded
  35089. */
  35090. virtual void stoppedDragging();
  35091. /** Callback to indicate that the user has just moved the slider.
  35092. @see SliderListener::sliderValueChanged
  35093. */
  35094. virtual void valueChanged();
  35095. /** Callback to indicate that the user has just moved the slider.
  35096. Note - the valueChanged() method has changed its format and now no longer has
  35097. any parameters. Update your code to use the new version.
  35098. This version has been left here with an int as its return value to cause
  35099. a syntax error if you've got existing code that uses the old version.
  35100. */
  35101. virtual int valueChanged (double) { jassertfalse; return 0; }
  35102. /** Subclasses can override this to convert a text string to a value.
  35103. When the user enters something into the text-entry box, this method is
  35104. called to convert it to a value.
  35105. The default routine just tries to convert it to a double.
  35106. @see getTextFromValue
  35107. */
  35108. virtual double getValueFromText (const String& text);
  35109. /** Turns the slider's current value into a text string.
  35110. Subclasses can override this to customise the formatting of the text-entry box.
  35111. The default implementation just turns the value into a string, using
  35112. a number of decimal places based on the range interval. If a suffix string
  35113. has been set using setTextValueSuffix(), this will be appended to the text.
  35114. @see getValueFromText
  35115. */
  35116. virtual const String getTextFromValue (double value);
  35117. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  35118. a string.
  35119. This is used by the default implementation of getTextFromValue(), and is just
  35120. appended to the numeric value. For more advanced formatting, you can override
  35121. getTextFromValue() and do something else.
  35122. */
  35123. void setTextValueSuffix (const String& suffix);
  35124. /** Allows a user-defined mapping of distance along the slider to its value.
  35125. The default implementation for this performs the skewing operation that
  35126. can be set up in the setSkewFactor() method. Override it if you need
  35127. some kind of custom mapping instead, but make sure you also implement the
  35128. inverse function in valueToProportionOfLength().
  35129. @param proportion a value 0 to 1.0, indicating a distance along the slider
  35130. @returns the slider value that is represented by this position
  35131. @see valueToProportionOfLength
  35132. */
  35133. virtual double proportionOfLengthToValue (double proportion);
  35134. /** Allows a user-defined mapping of value to the position of the slider along its length.
  35135. The default implementation for this performs the skewing operation that
  35136. can be set up in the setSkewFactor() method. Override it if you need
  35137. some kind of custom mapping instead, but make sure you also implement the
  35138. inverse function in proportionOfLengthToValue().
  35139. @param value a valid slider value, between the range of values specified in
  35140. setRange()
  35141. @returns a value 0 to 1.0 indicating the distance along the slider that
  35142. represents this value
  35143. @see proportionOfLengthToValue
  35144. */
  35145. virtual double valueToProportionOfLength (double value);
  35146. /** Returns the X or Y coordinate of a value along the slider's length.
  35147. If the slider is horizontal, this will be the X coordinate of the given
  35148. value, relative to the left of the slider. If it's vertical, then this will
  35149. be the Y coordinate, relative to the top of the slider.
  35150. If the slider is rotary, this will throw an assertion and return 0. If the
  35151. value is out-of-range, it will be constrained to the length of the slider.
  35152. */
  35153. float getPositionOfValue (const double value);
  35154. /** This can be overridden to allow the slider to snap to user-definable values.
  35155. If overridden, it will be called when the user tries to move the slider to
  35156. a given position, and allows a subclass to sanity-check this value, possibly
  35157. returning a different value to use instead.
  35158. @param attemptedValue the value the user is trying to enter
  35159. @param userIsDragging true if the user is dragging with the mouse; false if
  35160. they are entering the value using the text box
  35161. @returns the value to use instead
  35162. */
  35163. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  35164. /** This can be called to force the text box to update its contents.
  35165. (Not normally needed, as this is done automatically).
  35166. */
  35167. void updateText();
  35168. /** True if the slider moves horizontally. */
  35169. bool isHorizontal() const throw();
  35170. /** True if the slider moves vertically. */
  35171. bool isVertical() const throw();
  35172. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  35173. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35174. methods.
  35175. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35176. */
  35177. enum ColourIds
  35178. {
  35179. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  35180. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  35181. and feel class how this is used. */
  35182. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  35183. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  35184. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  35185. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  35186. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  35187. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  35188. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  35189. };
  35190. juce_UseDebuggingNewOperator
  35191. protected:
  35192. /** @internal */
  35193. void labelTextChanged (Label*);
  35194. /** @internal */
  35195. void paint (Graphics& g);
  35196. /** @internal */
  35197. void resized();
  35198. /** @internal */
  35199. void mouseDown (const MouseEvent& e);
  35200. /** @internal */
  35201. void mouseUp (const MouseEvent& e);
  35202. /** @internal */
  35203. void mouseDrag (const MouseEvent& e);
  35204. /** @internal */
  35205. void mouseDoubleClick (const MouseEvent& e);
  35206. /** @internal */
  35207. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35208. /** @internal */
  35209. void modifierKeysChanged (const ModifierKeys& modifiers);
  35210. /** @internal */
  35211. void buttonClicked (Button* button);
  35212. /** @internal */
  35213. void lookAndFeelChanged();
  35214. /** @internal */
  35215. void enablementChanged();
  35216. /** @internal */
  35217. void focusOfChildComponentChanged (FocusChangeType cause);
  35218. /** @internal */
  35219. void handleAsyncUpdate();
  35220. /** @internal */
  35221. void colourChanged();
  35222. private:
  35223. SortedSet <void*> listeners;
  35224. double currentValue, valueMin, valueMax;
  35225. double minimum, maximum, interval, doubleClickReturnValue;
  35226. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  35227. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  35228. int velocityModeThreshold;
  35229. float rotaryStart, rotaryEnd;
  35230. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  35231. int mouseDragStartX, mouseDragStartY;
  35232. int sliderRegionStart, sliderRegionSize;
  35233. int sliderBeingDragged;
  35234. int pixelsForFullDragExtent;
  35235. Rectangle sliderRect;
  35236. String textSuffix;
  35237. SliderStyle style;
  35238. TextEntryBoxPosition textBoxPos;
  35239. int textBoxWidth, textBoxHeight;
  35240. IncDecButtonMode incDecButtonMode;
  35241. bool editableText : 1, doubleClickToValue : 1;
  35242. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  35243. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  35244. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  35245. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  35246. Font font;
  35247. Label* valueBox;
  35248. Button* incButton;
  35249. Button* decButton;
  35250. Component* popupDisplay;
  35251. Component* parentForPopupDisplay;
  35252. float getLinearSliderPos (const double value);
  35253. void restoreMouseIfHidden();
  35254. void sendDragStart();
  35255. void sendDragEnd();
  35256. double constrainedValue (double value) const throw();
  35257. void triggerChangeMessage (const bool synchronous);
  35258. bool incDecDragDirectionIsHorizontal() const throw();
  35259. Slider (const Slider&);
  35260. const Slider& operator= (const Slider&);
  35261. };
  35262. #endif // __JUCE_SLIDER_JUCEHEADER__
  35263. /********* End of inlined file: juce_Slider.h *********/
  35264. #endif
  35265. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  35266. #endif
  35267. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35268. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  35269. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35270. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35271. class TableHeaderComponent;
  35272. /**
  35273. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  35274. You can register one of these objects for table events using TableHeaderComponent::addListener()
  35275. and TableHeaderComponent::removeListener().
  35276. @see TableHeaderComponent
  35277. */
  35278. class JUCE_API TableHeaderListener
  35279. {
  35280. public:
  35281. TableHeaderListener() {}
  35282. /** Destructor. */
  35283. virtual ~TableHeaderListener() {}
  35284. /** This is called when some of the table's columns are added, removed, hidden,
  35285. or rearranged.
  35286. */
  35287. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  35288. /** This is called when one or more of the table's columns are resized.
  35289. */
  35290. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  35291. /** This is called when the column by which the table should be sorted is changed.
  35292. */
  35293. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  35294. /** This is called when the user begins or ends dragging one of the columns around.
  35295. When the user starts dragging a column, this is called with the ID of that
  35296. column. When they finish dragging, it is called again with 0 as the ID.
  35297. */
  35298. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  35299. int columnIdNowBeingDragged);
  35300. };
  35301. /**
  35302. A component that displays a strip of column headings for a table, and allows these
  35303. to be resized, dragged around, etc.
  35304. This is just the component that goes at the top of a table. You can use it
  35305. directly for custom components, or to create a simple table, use the
  35306. TableListBox class.
  35307. To use one of these, create it and use addColumn() to add all the columns that you need.
  35308. Each column must be given a unique ID number that's used to refer to it.
  35309. @see TableListBox, TableHeaderListener
  35310. */
  35311. class JUCE_API TableHeaderComponent : public Component,
  35312. private AsyncUpdater
  35313. {
  35314. public:
  35315. /** Creates an empty table header.
  35316. */
  35317. TableHeaderComponent();
  35318. /** Destructor. */
  35319. ~TableHeaderComponent();
  35320. /** A combination of these flags are passed into the addColumn() method to specify
  35321. the properties of a column.
  35322. */
  35323. enum ColumnPropertyFlags
  35324. {
  35325. 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. */
  35326. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  35327. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  35328. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  35329. 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. */
  35330. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  35331. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  35332. /** This set of default flags is used as the default parameter value in addColumn(). */
  35333. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  35334. /** A quick way of combining flags for a column that's not resizable. */
  35335. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  35336. /** A quick way of combining flags for a column that's not resizable or sortable. */
  35337. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  35338. /** A quick way of combining flags for a column that's not sortable. */
  35339. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  35340. };
  35341. /** Adds a column to the table.
  35342. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  35343. registered listeners.
  35344. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  35345. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  35346. a unique ID. This is used to identify the column later on, after the user may have
  35347. changed the order that they appear in
  35348. @param width the initial width of the column, in pixels
  35349. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  35350. if the 'resizable' flag is specified for this column
  35351. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  35352. if the 'resizable' flag is specified for this column
  35353. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  35354. properties of this column
  35355. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  35356. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  35357. all columns, not just the index amongst those that are currently visible
  35358. */
  35359. void addColumn (const String& columnName,
  35360. const int columnId,
  35361. const int width,
  35362. const int minimumWidth = 30,
  35363. const int maximumWidth = -1,
  35364. const int propertyFlags = defaultFlags,
  35365. const int insertIndex = -1);
  35366. /** Removes a column with the given ID.
  35367. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  35368. registered listeners.
  35369. */
  35370. void removeColumn (const int columnIdToRemove);
  35371. /** Deletes all columns from the table.
  35372. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  35373. registered listeners.
  35374. */
  35375. void removeAllColumns();
  35376. /** Returns the number of columns in the table.
  35377. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  35378. return the total number of columns, including hidden ones.
  35379. @see isColumnVisible
  35380. */
  35381. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  35382. /** Returns the name for a column.
  35383. @see setColumnName
  35384. */
  35385. const String getColumnName (const int columnId) const throw();
  35386. /** Changes the name of a column. */
  35387. void setColumnName (const int columnId, const String& newName);
  35388. /** Moves a column to a different index in the table.
  35389. @param columnId the column to move
  35390. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  35391. */
  35392. void moveColumn (const int columnId, int newVisibleIndex);
  35393. /** Returns the width of one of the columns.
  35394. */
  35395. int getColumnWidth (const int columnId) const throw();
  35396. /** Changes the width of a column.
  35397. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  35398. */
  35399. void setColumnWidth (const int columnId, const int newWidth);
  35400. /** Shows or hides a column.
  35401. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  35402. @see isColumnVisible
  35403. */
  35404. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  35405. /** Returns true if this column is currently visible.
  35406. @see setColumnVisible
  35407. */
  35408. bool isColumnVisible (const int columnId) const;
  35409. /** Changes the column which is the sort column.
  35410. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  35411. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  35412. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  35413. @see getSortColumnId, isSortedForwards, reSortTable
  35414. */
  35415. void setSortColumnId (const int columnId, const bool sortForwards);
  35416. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  35417. @see setSortColumnId, isSortedForwards
  35418. */
  35419. int getSortColumnId() const throw();
  35420. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  35421. @see setSortColumnId
  35422. */
  35423. bool isSortedForwards() const throw();
  35424. /** Triggers a re-sort of the table according to the current sort-column.
  35425. If you modifiy the table's contents, you can call this to signal that the table needs
  35426. to be re-sorted.
  35427. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  35428. tableSortOrderChanged() method of any listeners).
  35429. */
  35430. void reSortTable();
  35431. /** Returns the total width of all the visible columns in the table.
  35432. */
  35433. int getTotalWidth() const throw();
  35434. /** Returns the index of a given column.
  35435. If there's no such column ID, this will return -1.
  35436. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  35437. otherwise it'll return the index amongst all the columns, including any hidden ones.
  35438. */
  35439. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  35440. /** Returns the ID of the column at a given index.
  35441. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  35442. otherwise it'll count it amongst all the columns, including any hidden ones.
  35443. If the index is out-of-range, it'll return 0.
  35444. */
  35445. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  35446. /** Returns the rectangle containing of one of the columns.
  35447. The index is an index from 0 to the number of columns that are currently visible (hidden
  35448. ones are not counted). It returns a rectangle showing the position of the column relative
  35449. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  35450. */
  35451. const Rectangle getColumnPosition (const int index) const throw();
  35452. /** Finds the column ID at a given x-position in the component.
  35453. If there is a column at this point this returns its ID, or if not, it will return 0.
  35454. */
  35455. int getColumnIdAtX (const int xToFind) const throw();
  35456. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  35457. entire width of the component.
  35458. By default this is disabled. Turning it on also means that when resizing a column, those
  35459. on the right will be squashed to fit.
  35460. */
  35461. void setStretchToFitActive (const bool shouldStretchToFit);
  35462. /** Returns true if stretch-to-fit has been enabled.
  35463. @see setStretchToFitActive
  35464. */
  35465. bool isStretchToFitActive() const throw();
  35466. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  35467. specified width, keeping their relative proportions the same.
  35468. If the minimum widths of the columns are too wide to fit into this space, it may
  35469. actually end up wider.
  35470. */
  35471. void resizeAllColumnsToFit (int targetTotalWidth);
  35472. /** Enables or disables the pop-up menu.
  35473. The default menu allows the user to show or hide columns. You can add custom
  35474. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  35475. By default the menu is enabled.
  35476. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  35477. */
  35478. void setPopupMenuActive (const bool hasMenu);
  35479. /** Returns true if the pop-up menu is enabled.
  35480. @see setPopupMenuActive
  35481. */
  35482. bool isPopupMenuActive() const throw();
  35483. /** Returns a string that encapsulates the table's current layout.
  35484. This can be restored later using restoreFromString(). It saves the order of
  35485. the columns, the currently-sorted column, and the widths.
  35486. @see restoreFromString
  35487. */
  35488. const String toString() const;
  35489. /** Restores the state of the table, based on a string previously created with
  35490. toString().
  35491. @see toString
  35492. */
  35493. void restoreFromString (const String& storedVersion);
  35494. /** Adds a listener to be informed about things that happen to the header. */
  35495. void addListener (TableHeaderListener* const newListener) throw();
  35496. /** Removes a previously-registered listener. */
  35497. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  35498. /** This can be overridden to handle a mouse-click on one of the column headers.
  35499. The default implementation will use this click to call getSortColumnId() and
  35500. change the sort order.
  35501. */
  35502. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  35503. /** This can be overridden to add custom items to the pop-up menu.
  35504. If you override this, you should call the superclass's method to add its
  35505. column show/hide items, if you want them on the menu as well.
  35506. Then to handle the result, override reactToMenuItem().
  35507. @see reactToMenuItem
  35508. */
  35509. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  35510. /** Override this to handle any custom items that you have added to the
  35511. pop-up menu with an addMenuItems() override.
  35512. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35513. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35514. handle the items that it had added.
  35515. @see addMenuItems
  35516. */
  35517. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  35518. /** @internal */
  35519. void paint (Graphics& g);
  35520. /** @internal */
  35521. void resized();
  35522. /** @internal */
  35523. void mouseMove (const MouseEvent&);
  35524. /** @internal */
  35525. void mouseEnter (const MouseEvent&);
  35526. /** @internal */
  35527. void mouseExit (const MouseEvent&);
  35528. /** @internal */
  35529. void mouseDown (const MouseEvent&);
  35530. /** @internal */
  35531. void mouseDrag (const MouseEvent&);
  35532. /** @internal */
  35533. void mouseUp (const MouseEvent&);
  35534. /** @internal */
  35535. const MouseCursor getMouseCursor();
  35536. /** Can be overridden for more control over the pop-up menu behaviour. */
  35537. virtual void showColumnChooserMenu (const int columnIdClicked);
  35538. juce_UseDebuggingNewOperator
  35539. private:
  35540. struct ColumnInfo
  35541. {
  35542. String name;
  35543. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35544. double lastDeliberateWidth;
  35545. bool isVisible() const throw();
  35546. };
  35547. OwnedArray <ColumnInfo> columns;
  35548. Array <TableHeaderListener*> listeners;
  35549. Component* dragOverlayComp;
  35550. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35551. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35552. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35553. ColumnInfo* getInfoForId (const int columnId) const throw();
  35554. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  35555. void sendColumnsChanged();
  35556. void handleAsyncUpdate();
  35557. void beginDrag (const MouseEvent&);
  35558. void endDrag (const int finalIndex);
  35559. int getResizeDraggerAt (const int mouseX) const throw();
  35560. void updateColumnUnderMouse (int x, int y);
  35561. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35562. TableHeaderComponent (const TableHeaderComponent&);
  35563. const TableHeaderComponent operator= (const TableHeaderComponent&);
  35564. };
  35565. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35566. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  35567. #endif
  35568. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35569. /********* Start of inlined file: juce_TableListBox.h *********/
  35570. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35571. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35572. /**
  35573. One of these is used by a TableListBox as the data model for the table's contents.
  35574. The virtual methods that you override in this class take care of drawing the
  35575. table cells, and reacting to events.
  35576. @see TableListBox
  35577. */
  35578. class JUCE_API TableListBoxModel
  35579. {
  35580. public:
  35581. TableListBoxModel() {}
  35582. /** Destructor. */
  35583. virtual ~TableListBoxModel() {}
  35584. /** This must return the number of rows currently in the table.
  35585. If the number of rows changes, you must call TableListBox::updateContent() to
  35586. cause it to refresh the list.
  35587. */
  35588. virtual int getNumRows() = 0;
  35589. /** This must draw the background behind one of the rows in the table.
  35590. The graphics context has its origin at the row's top-left, and your method
  35591. should fill the area specified by the width and height parameters.
  35592. */
  35593. virtual void paintRowBackground (Graphics& g,
  35594. int rowNumber,
  35595. int width, int height,
  35596. bool rowIsSelected) = 0;
  35597. /** This must draw one of the cells.
  35598. The graphics context's origin will already be set to the top-left of the cell,
  35599. whose size is specified by (width, height).
  35600. */
  35601. virtual void paintCell (Graphics& g,
  35602. int rowNumber,
  35603. int columnId,
  35604. int width, int height,
  35605. bool rowIsSelected) = 0;
  35606. /** This is used to create or update a custom component to go in a cell.
  35607. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35608. and handle mouse clicks with cellClicked().
  35609. This method will be called whenever a custom component might need to be updated - e.g.
  35610. when the table is changed, or TableListBox::updateContent() is called.
  35611. If you don't need a custom component for the specified cell, then return 0.
  35612. If you do want a custom component, and the existingComponentToUpdate is null, then
  35613. this method must create a new component suitable for the cell, and return it.
  35614. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35615. by this method. In this case, the method must either update it to make sure it's correctly representing
  35616. the given cell (which may be different from the one that the component was created for), or it can
  35617. delete this component and return a new one.
  35618. */
  35619. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35620. Component* existingComponentToUpdate);
  35621. /** This callback is made when the user clicks on one of the cells in the table.
  35622. The mouse event's coordinates will be relative to the entire table row.
  35623. @see cellDoubleClicked, backgroundClicked
  35624. */
  35625. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35626. /** This callback is made when the user clicks on one of the cells in the table.
  35627. The mouse event's coordinates will be relative to the entire table row.
  35628. @see cellClicked, backgroundClicked
  35629. */
  35630. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35631. /** This can be overridden to react to the user double-clicking on a part of the list where
  35632. there are no rows.
  35633. @see cellClicked
  35634. */
  35635. virtual void backgroundClicked();
  35636. /** This callback is made when the table's sort order is changed.
  35637. This could be because the user has clicked a column header, or because the
  35638. TableHeaderComponent::setSortColumnId() method was called.
  35639. If you implement this, your method should re-sort the table using the given
  35640. column as the key.
  35641. */
  35642. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  35643. /** Returns the best width for one of the columns.
  35644. If you implement this method, you should measure the width of all the items
  35645. in this column, and return the best size.
  35646. Returning 0 means that the column shouldn't be changed.
  35647. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35648. */
  35649. virtual int getColumnAutoSizeWidth (int columnId);
  35650. /** Returns a tooltip for a particular cell in the table.
  35651. */
  35652. virtual const String getCellTooltip (int rowNumber, int columnId);
  35653. /** Override this to be informed when rows are selected or deselected.
  35654. @see ListBox::selectedRowsChanged()
  35655. */
  35656. virtual void selectedRowsChanged (int lastRowSelected);
  35657. /** Override this to be informed when the delete key is pressed.
  35658. @see ListBox::deleteKeyPressed()
  35659. */
  35660. virtual void deleteKeyPressed (int lastRowSelected);
  35661. /** Override this to be informed when the return key is pressed.
  35662. @see ListBox::returnKeyPressed()
  35663. */
  35664. virtual void returnKeyPressed (int lastRowSelected);
  35665. /** Override this to be informed when the list is scrolled.
  35666. This might be caused by the user moving the scrollbar, or by programmatic changes
  35667. to the list position.
  35668. */
  35669. virtual void listWasScrolled();
  35670. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35671. If this returns a non-empty name then when the user drags a row, the table will try to
  35672. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35673. drag-and-drop operation, using this string as the source description, and the listbox
  35674. itself as the source component.
  35675. @see DragAndDropContainer::startDragging
  35676. */
  35677. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35678. };
  35679. /**
  35680. A table of cells, using a TableHeaderComponent as its header.
  35681. This component makes it easy to create a table by providing a TableListBoxModel as
  35682. the data source.
  35683. @see TableListBoxModel, TableHeaderComponent
  35684. */
  35685. class JUCE_API TableListBox : public ListBox,
  35686. private ListBoxModel,
  35687. private TableHeaderListener
  35688. {
  35689. public:
  35690. /** Creates a TableListBox.
  35691. The model pointer passed-in can be null, in which case you can set it later
  35692. with setModel().
  35693. */
  35694. TableListBox (const String& componentName,
  35695. TableListBoxModel* const model);
  35696. /** Destructor. */
  35697. ~TableListBox();
  35698. /** Changes the TableListBoxModel that is being used for this table.
  35699. */
  35700. void setModel (TableListBoxModel* const newModel);
  35701. /** Returns the model currently in use. */
  35702. TableListBoxModel* getModel() const throw() { return model; }
  35703. /** Returns the header component being used in this table. */
  35704. TableHeaderComponent* getHeader() const throw() { return header; }
  35705. /** Changes the height of the table header component.
  35706. @see getHeaderHeight
  35707. */
  35708. void setHeaderHeight (const int newHeight);
  35709. /** Returns the height of the table header.
  35710. @see setHeaderHeight
  35711. */
  35712. int getHeaderHeight() const throw();
  35713. /** Resizes a column to fit its contents.
  35714. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35715. and applies that to the column.
  35716. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35717. */
  35718. void autoSizeColumn (const int columnId);
  35719. /** Calls autoSizeColumn() for all columns in the table. */
  35720. void autoSizeAllColumns();
  35721. /** Enables or disables the auto size options on the popup menu.
  35722. By default, these are enabled.
  35723. */
  35724. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  35725. /** True if the auto-size options should be shown on the menu.
  35726. @see setAutoSizeMenuOptionsShown
  35727. */
  35728. bool isAutoSizeMenuOptionShown() const throw();
  35729. /** Returns the position of one of the cells in the table.
  35730. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35731. the table component's top-left. The row number isn't checked to see if it's
  35732. in-range, but the column ID must exist or this will return an empty rectangle.
  35733. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35734. top-left of the table's top-left cell.
  35735. */
  35736. const Rectangle getCellPosition (const int columnId,
  35737. const int rowNumber,
  35738. const bool relativeToComponentTopLeft) const;
  35739. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35740. @see ListBox::scrollToEnsureRowIsOnscreen
  35741. */
  35742. void scrollToEnsureColumnIsOnscreen (const int columnId);
  35743. /** @internal */
  35744. int getNumRows();
  35745. /** @internal */
  35746. void paintListBoxItem (int, Graphics&, int, int, bool);
  35747. /** @internal */
  35748. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35749. /** @internal */
  35750. void selectedRowsChanged (int lastRowSelected);
  35751. /** @internal */
  35752. void deleteKeyPressed (int currentSelectedRow);
  35753. /** @internal */
  35754. void returnKeyPressed (int currentSelectedRow);
  35755. /** @internal */
  35756. void backgroundClicked();
  35757. /** @internal */
  35758. void listWasScrolled();
  35759. /** @internal */
  35760. void tableColumnsChanged (TableHeaderComponent*);
  35761. /** @internal */
  35762. void tableColumnsResized (TableHeaderComponent*);
  35763. /** @internal */
  35764. void tableSortOrderChanged (TableHeaderComponent*);
  35765. /** @internal */
  35766. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35767. /** @internal */
  35768. void resized();
  35769. juce_UseDebuggingNewOperator
  35770. private:
  35771. TableHeaderComponent* header;
  35772. TableListBoxModel* model;
  35773. int columnIdNowBeingDragged;
  35774. bool autoSizeOptionsShown;
  35775. void updateColumnComponents() const;
  35776. TableListBox (const TableListBox&);
  35777. const TableListBox& operator= (const TableListBox&);
  35778. };
  35779. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35780. /********* End of inlined file: juce_TableListBox.h *********/
  35781. #endif
  35782. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35783. #endif
  35784. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35785. #endif
  35786. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35787. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  35788. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35789. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35790. /**
  35791. A factory object which can create ToolbarItemComponent objects.
  35792. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35793. that it can create.
  35794. Each type of item is identified by a unique ID, and multiple instances of an
  35795. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35796. bars).
  35797. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35798. */
  35799. class JUCE_API ToolbarItemFactory
  35800. {
  35801. public:
  35802. ToolbarItemFactory();
  35803. /** Destructor. */
  35804. virtual ~ToolbarItemFactory();
  35805. /** A set of reserved item ID values, used for the built-in item types.
  35806. */
  35807. enum SpecialItemIds
  35808. {
  35809. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35810. can be placed between sets of items to break them into groups. */
  35811. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35812. items.*/
  35813. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35814. either side of it, filling any available space. */
  35815. };
  35816. /** Must return a list of the IDs for all the item types that this factory can create.
  35817. The ids should be added to the array that is passed-in.
  35818. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35819. and the predefined IDs in the SpecialItemIds enum.
  35820. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35821. to this list if you want your toolbar to be able to contain those items.
  35822. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35823. of available items, and their order on the palette will reflect the order in which
  35824. they appear on this list.
  35825. @see ToolbarItemPalette
  35826. */
  35827. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35828. /** Must return the set of items that should be added to a toolbar as its default set.
  35829. This method is used by Toolbar::addDefaultItems() to determine which items to
  35830. create.
  35831. The items that your method adds to the array that is passed-in will be added to the
  35832. toolbar in the same order. Items can appear in the list more than once.
  35833. */
  35834. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35835. /** Must create an instance of one of the items that the factory lists in its
  35836. getAllToolbarItemIds() method.
  35837. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35838. method, except for the built-in item types from the SpecialItemIds enum, which
  35839. are created internally by the toolbar code.
  35840. Try not to keep a pointer to the object that is returned, as it will be deleted
  35841. automatically by the toolbar, and remember that multiple instances of the same
  35842. item type are likely to exist at the same time.
  35843. */
  35844. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  35845. };
  35846. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35847. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  35848. #endif
  35849. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35850. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  35851. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35852. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35853. /**
  35854. A component containing a list of toolbar items, which the user can drag onto
  35855. a toolbar to add them.
  35856. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35857. which automatically shows one of these in a dialog box with lots of extra controls.
  35858. @see Toolbar
  35859. */
  35860. class JUCE_API ToolbarItemPalette : public Component,
  35861. public DragAndDropContainer
  35862. {
  35863. public:
  35864. /** Creates a palette of items for a given factory, with the aim of adding them
  35865. to the specified toolbar.
  35866. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35867. set of items that are shown in this palette.
  35868. The toolbar and factory must not be deleted while this object exists.
  35869. */
  35870. ToolbarItemPalette (ToolbarItemFactory& factory,
  35871. Toolbar* const toolbar);
  35872. /** Destructor. */
  35873. ~ToolbarItemPalette();
  35874. /** @internal */
  35875. void resized();
  35876. juce_UseDebuggingNewOperator
  35877. private:
  35878. ToolbarItemFactory& factory;
  35879. Toolbar* toolbar;
  35880. Viewport* viewport;
  35881. friend class Toolbar;
  35882. void replaceComponent (ToolbarItemComponent* const comp);
  35883. ToolbarItemPalette (const ToolbarItemPalette&);
  35884. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35885. };
  35886. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35887. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  35888. #endif
  35889. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35890. #endif
  35891. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35892. #endif
  35893. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35894. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  35895. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35896. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35897. /**
  35898. A PropertyComponent that contains an on/off toggle button.
  35899. This type of property component can be used if you have a boolean value to
  35900. toggle on/off.
  35901. @see PropertyComponent
  35902. */
  35903. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  35904. private ButtonListener
  35905. {
  35906. public:
  35907. /** Creates a button component.
  35908. @param propertyName the property name to be passed to the PropertyComponent
  35909. @param buttonTextWhenTrue the text shown in the button when the value is true
  35910. @param buttonTextWhenFalse the text shown in the button when the value is false
  35911. */
  35912. BooleanPropertyComponent (const String& propertyName,
  35913. const String& buttonTextWhenTrue,
  35914. const String& buttonTextWhenFalse);
  35915. /** Destructor. */
  35916. ~BooleanPropertyComponent();
  35917. /** Called to change the state of the boolean value. */
  35918. virtual void setState (const bool newState) = 0;
  35919. /** Must return the current value of the property. */
  35920. virtual bool getState() const = 0;
  35921. /** @internal */
  35922. void paint (Graphics& g);
  35923. /** @internal */
  35924. void refresh();
  35925. /** @internal */
  35926. void buttonClicked (Button*);
  35927. juce_UseDebuggingNewOperator
  35928. private:
  35929. ToggleButton* button;
  35930. String onText, offText;
  35931. };
  35932. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35933. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  35934. #endif
  35935. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35936. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  35937. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35938. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35939. /**
  35940. A PropertyComponent that contains a button.
  35941. This type of property component can be used if you need a button to trigger some
  35942. kind of action.
  35943. @see PropertyComponent
  35944. */
  35945. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  35946. private ButtonListener
  35947. {
  35948. public:
  35949. /** Creates a button component.
  35950. @param propertyName the property name to be passed to the PropertyComponent
  35951. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  35952. */
  35953. ButtonPropertyComponent (const String& propertyName,
  35954. const bool triggerOnMouseDown);
  35955. /** Destructor. */
  35956. ~ButtonPropertyComponent();
  35957. /** Called when the user clicks the button.
  35958. */
  35959. virtual void buttonClicked() = 0;
  35960. /** Returns the string that should be displayed in the button.
  35961. If you need to change this string, call refresh() to update the component.
  35962. */
  35963. virtual const String getButtonText() const = 0;
  35964. /** @internal */
  35965. void refresh();
  35966. /** @internal */
  35967. void buttonClicked (Button*);
  35968. juce_UseDebuggingNewOperator
  35969. private:
  35970. TextButton* button;
  35971. };
  35972. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35973. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  35974. #endif
  35975. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35976. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  35977. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35978. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35979. /**
  35980. A PropertyComponent that shows its value as a combo box.
  35981. This type of property component contains a list of options and has a
  35982. combo box to choose one.
  35983. Your subclass's constructor must add some strings to the choices StringArray
  35984. and these are shown in the list.
  35985. The getIndex() method will be called to find out which option is the currently
  35986. selected one. If you call refresh() it will call getIndex() to check whether
  35987. the value has changed, and will update the combo box if needed.
  35988. If the user selects a different item from the list, setIndex() will be
  35989. called to let your class process this.
  35990. @see PropertyComponent, PropertyPanel
  35991. */
  35992. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  35993. private ComboBoxListener
  35994. {
  35995. public:
  35996. /** Creates the component.
  35997. Your subclass's constructor must add a list of options to the choices
  35998. member variable.
  35999. */
  36000. ChoicePropertyComponent (const String& propertyName);
  36001. /** Destructor. */
  36002. ~ChoicePropertyComponent();
  36003. /** Called when the user selects an item from the combo box.
  36004. Your subclass must use this callback to update the value that this component
  36005. represents. The index is the index of the chosen item in the choices
  36006. StringArray.
  36007. */
  36008. virtual void setIndex (const int newIndex) = 0;
  36009. /** Returns the index of the item that should currently be shown.
  36010. This is the index of the item in the choices StringArray that will be
  36011. shown.
  36012. */
  36013. virtual int getIndex() const = 0;
  36014. /** Returns the list of options. */
  36015. const StringArray& getChoices() const throw();
  36016. /** @internal */
  36017. void refresh();
  36018. /** @internal */
  36019. void comboBoxChanged (ComboBox*);
  36020. juce_UseDebuggingNewOperator
  36021. protected:
  36022. /** The list of options that will be shown in the combo box.
  36023. Your subclass must populate this array in its constructor. If any empty
  36024. strings are added, these will be replaced with horizontal separators (see
  36025. ComboBox::addSeparator() for more info).
  36026. */
  36027. StringArray choices;
  36028. private:
  36029. ComboBox* comboBox;
  36030. };
  36031. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  36032. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  36033. #endif
  36034. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  36035. #endif
  36036. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36037. #endif
  36038. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36039. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  36040. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36041. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36042. /**
  36043. A PropertyComponent that shows its value as a slider.
  36044. @see PropertyComponent, Slider
  36045. */
  36046. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  36047. private SliderListener
  36048. {
  36049. public:
  36050. /** Creates the property component.
  36051. The ranges, interval and skew factor are passed to the Slider component.
  36052. If you need to customise the slider in other ways, your constructor can
  36053. access the slider member variable and change it directly.
  36054. */
  36055. SliderPropertyComponent (const String& propertyName,
  36056. const double rangeMin,
  36057. const double rangeMax,
  36058. const double interval,
  36059. const double skewFactor = 1.0);
  36060. /** Destructor. */
  36061. ~SliderPropertyComponent();
  36062. /** Called when the user moves the slider to change its value.
  36063. Your subclass must use this method to update whatever item this property
  36064. represents.
  36065. */
  36066. virtual void setValue (const double newValue) = 0;
  36067. /** Returns the value that the slider should show. */
  36068. virtual const double getValue() const = 0;
  36069. /** @internal */
  36070. void refresh();
  36071. /** @internal */
  36072. void changeListenerCallback (void*);
  36073. /** @internal */
  36074. void sliderValueChanged (Slider*);
  36075. juce_UseDebuggingNewOperator
  36076. protected:
  36077. /** The slider component being used in this component.
  36078. Your subclass has access to this in case it needs to customise it in some way.
  36079. */
  36080. Slider* slider;
  36081. };
  36082. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36083. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  36084. #endif
  36085. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36086. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  36087. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36088. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36089. /**
  36090. A PropertyComponent that shows its value as editable text.
  36091. @see PropertyComponent
  36092. */
  36093. class JUCE_API TextPropertyComponent : public PropertyComponent
  36094. {
  36095. public:
  36096. /** Creates a text property component.
  36097. The maxNumChars is used to set the length of string allowable, and isMultiLine
  36098. sets whether the text editor allows carriage returns.
  36099. @see TextEditor
  36100. */
  36101. TextPropertyComponent (const String& propertyName,
  36102. const int maxNumChars,
  36103. const bool isMultiLine);
  36104. /** Destructor. */
  36105. ~TextPropertyComponent();
  36106. /** Called when the user edits the text.
  36107. Your subclass must use this callback to change the value of whatever item
  36108. this property component represents.
  36109. */
  36110. virtual void setText (const String& newText) = 0;
  36111. /** Returns the text that should be shown in the text editor.
  36112. */
  36113. virtual const String getText() const = 0;
  36114. /** @internal */
  36115. void refresh();
  36116. /** @internal */
  36117. void textWasEdited();
  36118. juce_UseDebuggingNewOperator
  36119. private:
  36120. Label* textEditor;
  36121. };
  36122. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36123. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  36124. #endif
  36125. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  36126. #endif
  36127. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36128. #endif
  36129. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36130. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  36131. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36132. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36133. /** An object that watches for any movement of a component or any of its parent components.
  36134. This makes it easy to check when a component is moved relative to its top-level
  36135. peer window. The normal Component::moved() method is only called when a component
  36136. moves relative to its immediate parent, and sometimes you want to know if any of
  36137. components higher up the tree have moved (which of course will affect the overall
  36138. position of all their sub-components).
  36139. It also includes a callback that lets you know when the top-level peer is changed.
  36140. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  36141. because they need to keep their custom windows in the right place and respond to
  36142. changes in the peer.
  36143. */
  36144. class JUCE_API ComponentMovementWatcher : public ComponentListener
  36145. {
  36146. public:
  36147. /** Creates a ComponentMovementWatcher to watch a given target component. */
  36148. ComponentMovementWatcher (Component* const component);
  36149. /** Destructor. */
  36150. ~ComponentMovementWatcher();
  36151. /** This callback happens when the component that is being watched is moved
  36152. relative to its top-level peer window, or when it is resized.
  36153. */
  36154. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  36155. /** This callback happens when the component's top-level peer is changed.
  36156. */
  36157. virtual void componentPeerChanged() = 0;
  36158. juce_UseDebuggingNewOperator
  36159. /** @internal */
  36160. void componentParentHierarchyChanged (Component& component);
  36161. /** @internal */
  36162. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36163. private:
  36164. Component* const component;
  36165. ComponentPeer* lastPeer;
  36166. VoidArray registeredParentComps;
  36167. bool reentrant;
  36168. int lastX, lastY, lastWidth, lastHeight;
  36169. #ifdef JUCE_DEBUG
  36170. ComponentDeletionWatcher* deletionWatcher;
  36171. #endif
  36172. void unregister() throw();
  36173. void registerWithParentComps() throw();
  36174. ComponentMovementWatcher (const ComponentMovementWatcher&);
  36175. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  36176. };
  36177. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36178. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  36179. #endif
  36180. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36181. /********* Start of inlined file: juce_GroupComponent.h *********/
  36182. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36183. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36184. /**
  36185. A component that draws an outline around itself and has an optional title at
  36186. the top, for drawing an outline around a group of controls.
  36187. */
  36188. class JUCE_API GroupComponent : public Component
  36189. {
  36190. public:
  36191. /** Creates a GroupComponent.
  36192. @param componentName the name to give the component
  36193. @param labelText the text to show at the top of the outline
  36194. */
  36195. GroupComponent (const String& componentName,
  36196. const String& labelText);
  36197. /** Destructor. */
  36198. ~GroupComponent();
  36199. /** Changes the text that's shown at the top of the component. */
  36200. void setText (const String& newText) throw();
  36201. /** Returns the currently displayed text label. */
  36202. const String getText() const throw();
  36203. /** Sets the positioning of the text label.
  36204. (The default is Justification::left)
  36205. @see getTextLabelPosition
  36206. */
  36207. void setTextLabelPosition (const Justification& justification);
  36208. /** Returns the current text label position.
  36209. @see setTextLabelPosition
  36210. */
  36211. const Justification getTextLabelPosition() const throw() { return justification; }
  36212. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36213. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36214. methods.
  36215. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36216. */
  36217. enum ColourIds
  36218. {
  36219. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  36220. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  36221. };
  36222. /** @internal */
  36223. void paint (Graphics& g);
  36224. /** @internal */
  36225. void enablementChanged();
  36226. /** @internal */
  36227. void colourChanged();
  36228. private:
  36229. String text;
  36230. Justification justification;
  36231. GroupComponent (const GroupComponent&);
  36232. const GroupComponent& operator= (const GroupComponent&);
  36233. };
  36234. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36235. /********* End of inlined file: juce_GroupComponent.h *********/
  36236. #endif
  36237. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36238. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  36239. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36240. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36241. /********* Start of inlined file: juce_TabbedComponent.h *********/
  36242. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36243. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36244. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  36245. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36246. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36247. class TabbedButtonBar;
  36248. /** In a TabbedButtonBar, this component is used for each of the buttons.
  36249. If you want to create a TabbedButtonBar with custom tab components, derive
  36250. your component from this class, and override the TabbedButtonBar::createTabButton()
  36251. method to create it instead of the default one.
  36252. @see TabbedButtonBar
  36253. */
  36254. class JUCE_API TabBarButton : public Button
  36255. {
  36256. public:
  36257. /** Creates the tab button. */
  36258. TabBarButton (const String& name,
  36259. TabbedButtonBar* const ownerBar,
  36260. const int tabIndex);
  36261. /** Destructor. */
  36262. ~TabBarButton();
  36263. /** Chooses the best length for the tab, given the specified depth.
  36264. If the tab is horizontal, this should return its width, and the depth
  36265. specifies its height. If it's vertical, it should return the height, and
  36266. the depth is actually its width.
  36267. */
  36268. virtual int getBestTabLength (const int depth);
  36269. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  36270. void clicked (const ModifierKeys& mods);
  36271. bool hitTest (int x, int y);
  36272. juce_UseDebuggingNewOperator
  36273. protected:
  36274. friend class TabbedButtonBar;
  36275. TabbedButtonBar* const owner;
  36276. int tabIndex, overlapPixels;
  36277. DropShadowEffect shadow;
  36278. /** Returns an area of the component that's safe to draw in.
  36279. This deals with the orientation of the tabs, which affects which side is
  36280. touching the tabbed box's content component.
  36281. */
  36282. void getActiveArea (int& x, int& y, int& w, int& h);
  36283. private:
  36284. TabBarButton (const TabBarButton&);
  36285. const TabBarButton& operator= (const TabBarButton&);
  36286. };
  36287. /**
  36288. A vertical or horizontal bar containing tabs that you can select.
  36289. You can use one of these to generate things like a dialog box that has
  36290. tabbed pages you can flip between. Attach a ChangeListener to the
  36291. button bar to be told when the user changes the page.
  36292. An easier method than doing this is to use a TabbedComponent, which
  36293. contains its own TabbedButtonBar and which takes care of the layout
  36294. and other housekeeping.
  36295. @see TabbedComponent
  36296. */
  36297. class JUCE_API TabbedButtonBar : public Component,
  36298. public ChangeBroadcaster,
  36299. public ButtonListener
  36300. {
  36301. public:
  36302. /** The placement of the tab-bar
  36303. @see setOrientation, getOrientation
  36304. */
  36305. enum Orientation
  36306. {
  36307. TabsAtTop,
  36308. TabsAtBottom,
  36309. TabsAtLeft,
  36310. TabsAtRight
  36311. };
  36312. /** Creates a TabbedButtonBar with a given placement.
  36313. You can change the orientation later if you need to.
  36314. */
  36315. TabbedButtonBar (const Orientation orientation);
  36316. /** Destructor. */
  36317. ~TabbedButtonBar();
  36318. /** Changes the bar's orientation.
  36319. This won't change the bar's actual size - you'll need to do that yourself,
  36320. but this determines which direction the tabs go in, and which side they're
  36321. stuck to.
  36322. */
  36323. void setOrientation (const Orientation orientation);
  36324. /** Returns the current orientation.
  36325. @see setOrientation
  36326. */
  36327. Orientation getOrientation() const throw() { return orientation; }
  36328. /** Deletes all the tabs from the bar.
  36329. @see addTab
  36330. */
  36331. void clearTabs();
  36332. /** Adds a tab to the bar.
  36333. Tabs are added in left-to-right reading order.
  36334. If this is the first tab added, it'll also be automatically selected.
  36335. */
  36336. void addTab (const String& tabName,
  36337. const Colour& tabBackgroundColour,
  36338. int insertIndex = -1);
  36339. /** Changes the name of one of the tabs. */
  36340. void setTabName (const int tabIndex,
  36341. const String& newName);
  36342. /** Gets rid of one of the tabs. */
  36343. void removeTab (const int tabIndex);
  36344. /** Moves a tab to a new index in the list.
  36345. Pass -1 as the index to move it to the end of the list.
  36346. */
  36347. void moveTab (const int currentIndex,
  36348. const int newIndex);
  36349. /** Returns the number of tabs in the bar. */
  36350. int getNumTabs() const;
  36351. /** Returns a list of all the tab names in the bar. */
  36352. const StringArray getTabNames() const;
  36353. /** Changes the currently selected tab.
  36354. This will send a change message and cause a synchronous callback to
  36355. the currentTabChanged() method. (But if the given tab is already selected,
  36356. nothing will be done).
  36357. To deselect all the tabs, use an index of -1.
  36358. */
  36359. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  36360. /** Returns the name of the currently selected tab.
  36361. This could be an empty string if none are selected.
  36362. */
  36363. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  36364. /** Returns the index of the currently selected tab.
  36365. This could return -1 if none are selected.
  36366. */
  36367. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  36368. /** Returns the button for a specific tab.
  36369. The button that is returned may be deleted later by this component, so don't hang
  36370. on to the pointer that is returned. A null pointer may be returned if the index is
  36371. out of range.
  36372. */
  36373. TabBarButton* getTabButton (const int index) const;
  36374. /** Callback method to indicate the selected tab has been changed.
  36375. @see setCurrentTabIndex
  36376. */
  36377. virtual void currentTabChanged (const int newCurrentTabIndex,
  36378. const String& newCurrentTabName);
  36379. /** Callback method to indicate that the user has right-clicked on a tab.
  36380. (Or ctrl-clicked on the Mac)
  36381. */
  36382. virtual void popupMenuClickOnTab (const int tabIndex,
  36383. const String& tabName);
  36384. /** Returns the colour of a tab.
  36385. This is the colour that was specified in addTab().
  36386. */
  36387. const Colour getTabBackgroundColour (const int tabIndex);
  36388. /** Changes the background colour of a tab.
  36389. @see addTab, getTabBackgroundColour
  36390. */
  36391. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36392. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36393. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36394. methods.
  36395. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36396. */
  36397. enum ColourIds
  36398. {
  36399. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  36400. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  36401. the look and feel will choose an appropriate colour. */
  36402. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  36403. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  36404. this isn't specified, the look and feel will choose an appropriate
  36405. colour. */
  36406. };
  36407. /** @internal */
  36408. void resized();
  36409. /** @internal */
  36410. void buttonClicked (Button* button);
  36411. /** @internal */
  36412. void lookAndFeelChanged();
  36413. juce_UseDebuggingNewOperator
  36414. protected:
  36415. /** This creates one of the tabs.
  36416. If you need to use custom tab components, you can override this method and
  36417. return your own class instead of the default.
  36418. */
  36419. virtual TabBarButton* createTabButton (const String& tabName,
  36420. const int tabIndex);
  36421. private:
  36422. Orientation orientation;
  36423. StringArray tabs;
  36424. Array <Colour> tabColours;
  36425. int currentTabIndex;
  36426. Component* behindFrontTab;
  36427. Button* extraTabsButton;
  36428. TabbedButtonBar (const TabbedButtonBar&);
  36429. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  36430. };
  36431. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36432. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  36433. /**
  36434. A component with a TabbedButtonBar along one of its sides.
  36435. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  36436. with addTab(), and this will take care of showing the pages for you when the
  36437. user clicks on a different tab.
  36438. @see TabbedButtonBar
  36439. */
  36440. class JUCE_API TabbedComponent : public Component
  36441. {
  36442. public:
  36443. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  36444. Once created, add some tabs with the addTab() method.
  36445. */
  36446. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  36447. /** Destructor. */
  36448. ~TabbedComponent();
  36449. /** Changes the placement of the tabs.
  36450. This will rearrange the layout to place the tabs along the appropriate
  36451. side of this component, and will shift the content component accordingly.
  36452. @see TabbedButtonBar::setOrientation
  36453. */
  36454. void setOrientation (const TabbedButtonBar::Orientation orientation);
  36455. /** Returns the current tab placement.
  36456. @see setOrientation, TabbedButtonBar::getOrientation
  36457. */
  36458. TabbedButtonBar::Orientation getOrientation() const throw();
  36459. /** Specifies how many pixels wide or high the tab-bar should be.
  36460. If the tabs are placed along the top or bottom, this specified the height
  36461. of the bar; if they're along the left or right edges, it'll be the width
  36462. of the bar.
  36463. */
  36464. void setTabBarDepth (const int newDepth);
  36465. /** Returns the current thickness of the tab bar.
  36466. @see setTabBarDepth
  36467. */
  36468. int getTabBarDepth() const throw() { return tabDepth; }
  36469. /** Specifies the thickness of an outline that should be drawn around the content component.
  36470. If this thickness is > 0, a line will be drawn around the three sides of the content
  36471. component which don't touch the tab-bar, and the content component will be inset by this amount.
  36472. To set the colour of the line, use setColour (outlineColourId, ...).
  36473. */
  36474. void setOutline (const int newThickness);
  36475. /** Specifies a gap to leave around the edge of the content component.
  36476. Each edge of the content component will be indented by the given number of pixels.
  36477. */
  36478. void setIndent (const int indentThickness);
  36479. /** Removes all the tabs from the bar.
  36480. @see TabbedButtonBar::clearTabs
  36481. */
  36482. void clearTabs();
  36483. /** Adds a tab to the tab-bar.
  36484. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  36485. is true, it will be deleted when the tab is removed or when this object is
  36486. deleted.
  36487. @see TabbedButtonBar::addTab
  36488. */
  36489. void addTab (const String& tabName,
  36490. const Colour& tabBackgroundColour,
  36491. Component* const contentComponent,
  36492. const bool deleteComponentWhenNotNeeded,
  36493. const int insertIndex = -1);
  36494. /** Changes the name of one of the tabs. */
  36495. void setTabName (const int tabIndex,
  36496. const String& newName);
  36497. /** Gets rid of one of the tabs. */
  36498. void removeTab (const int tabIndex);
  36499. /** Returns the number of tabs in the bar. */
  36500. int getNumTabs() const;
  36501. /** Returns a list of all the tab names in the bar. */
  36502. const StringArray getTabNames() const;
  36503. /** Returns the content component that was added for the given index.
  36504. Be sure not to use or delete the components that are returned, as this may interfere
  36505. with the TabbedComponent's use of them.
  36506. */
  36507. Component* getTabContentComponent (const int tabIndex) const throw();
  36508. /** Returns the colour of one of the tabs. */
  36509. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  36510. /** Changes the background colour of one of the tabs. */
  36511. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36512. /** Changes the currently-selected tab.
  36513. To deselect all the tabs, pass -1 as the index.
  36514. @see TabbedButtonBar::setCurrentTabIndex
  36515. */
  36516. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  36517. /** Returns the index of the currently selected tab.
  36518. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  36519. */
  36520. int getCurrentTabIndex() const;
  36521. /** Returns the name of the currently selected tab.
  36522. @see addTab, TabbedButtonBar::getCurrentTabName()
  36523. */
  36524. const String& getCurrentTabName() const;
  36525. /** Returns the current component that's filling the panel.
  36526. This will return 0 if there isn't one.
  36527. */
  36528. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  36529. /** Callback method to indicate the selected tab has been changed.
  36530. @see setCurrentTabIndex
  36531. */
  36532. virtual void currentTabChanged (const int newCurrentTabIndex,
  36533. const String& newCurrentTabName);
  36534. /** Callback method to indicate that the user has right-clicked on a tab.
  36535. (Or ctrl-clicked on the Mac)
  36536. */
  36537. virtual void popupMenuClickOnTab (const int tabIndex,
  36538. const String& tabName);
  36539. /** Returns the tab button bar component that is being used.
  36540. */
  36541. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  36542. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36543. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36544. methods.
  36545. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36546. */
  36547. enum ColourIds
  36548. {
  36549. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  36550. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  36551. (See setOutline) */
  36552. };
  36553. /** @internal */
  36554. void paint (Graphics& g);
  36555. /** @internal */
  36556. void resized();
  36557. /** @internal */
  36558. void lookAndFeelChanged();
  36559. juce_UseDebuggingNewOperator
  36560. protected:
  36561. TabbedButtonBar* tabs;
  36562. /** This creates one of the tab buttons.
  36563. If you need to use custom tab components, you can override this method and
  36564. return your own class instead of the default.
  36565. */
  36566. virtual TabBarButton* createTabButton (const String& tabName,
  36567. const int tabIndex);
  36568. private:
  36569. Array <Component*> contentComponents;
  36570. Component* panelComponent;
  36571. int tabDepth;
  36572. int outlineThickness, edgeIndent;
  36573. friend class TabCompButtonBar;
  36574. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  36575. TabbedComponent (const TabbedComponent&);
  36576. const TabbedComponent& operator= (const TabbedComponent&);
  36577. };
  36578. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36579. /********* End of inlined file: juce_TabbedComponent.h *********/
  36580. /********* Start of inlined file: juce_DocumentWindow.h *********/
  36581. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36582. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36583. /********* Start of inlined file: juce_ResizableWindow.h *********/
  36584. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36585. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36586. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  36587. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36588. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36589. /********* Start of inlined file: juce_DropShadower.h *********/
  36590. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36591. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36592. /**
  36593. Adds a drop-shadow to a component.
  36594. This object creates and manages a set of components which sit around a
  36595. component, creating a gaussian shadow around it. The components will track
  36596. the position of the component and if it's brought to the front they'll also
  36597. follow this.
  36598. For desktop windows you don't need to use this class directly - just
  36599. set the Component::windowHasDropShadow flag when calling
  36600. Component::addToDesktop(), and the system will create one of these if it's
  36601. needed (which it obviously isn't on the Mac, for example).
  36602. */
  36603. class JUCE_API DropShadower : public ComponentListener
  36604. {
  36605. public:
  36606. /** Creates a DropShadower.
  36607. @param alpha the opacity of the shadows, from 0 to 1.0
  36608. @param xOffset the horizontal displacement of the shadow, in pixels
  36609. @param yOffset the vertical displacement of the shadow, in pixels
  36610. @param blurRadius the radius of the blur to use for creating the shadow
  36611. */
  36612. DropShadower (const float alpha = 0.5f,
  36613. const int xOffset = 1,
  36614. const int yOffset = 5,
  36615. const float blurRadius = 10.0f);
  36616. /** Destructor. */
  36617. virtual ~DropShadower();
  36618. /** Attaches the DropShadower to the component you want to shadow. */
  36619. void setOwner (Component* componentToFollow);
  36620. /** @internal */
  36621. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36622. /** @internal */
  36623. void componentBroughtToFront (Component& component);
  36624. /** @internal */
  36625. void componentChildrenChanged (Component& component);
  36626. /** @internal */
  36627. void componentParentHierarchyChanged (Component& component);
  36628. /** @internal */
  36629. void componentVisibilityChanged (Component& component);
  36630. juce_UseDebuggingNewOperator
  36631. private:
  36632. Component* owner;
  36633. int numShadows;
  36634. Component* shadowWindows[4];
  36635. Image* shadowImageSections[12];
  36636. const int shadowEdge, xOffset, yOffset;
  36637. const float alpha, blurRadius;
  36638. bool inDestructor, reentrant;
  36639. void updateShadows();
  36640. void setShadowImage (Image* const src,
  36641. const int num,
  36642. const int w, const int h,
  36643. const int sx, const int sy) throw();
  36644. void bringShadowWindowsToFront();
  36645. void deleteShadowWindows();
  36646. DropShadower (const DropShadower&);
  36647. const DropShadower& operator= (const DropShadower&);
  36648. };
  36649. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36650. /********* End of inlined file: juce_DropShadower.h *********/
  36651. /**
  36652. A base class for top-level windows.
  36653. This class is used for components that are considered a major part of your
  36654. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36655. etc. Things like menus that pop up briefly aren't derived from it.
  36656. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36657. could itself be the child of another component.
  36658. The class manages a list of all instances of top-level windows that are in use,
  36659. and each one is also given the concept of being "active". The active window is
  36660. one that is actively being used by the user. This isn't quite the same as the
  36661. component with the keyboard focus, because there may be a popup menu or other
  36662. temporary window which gets keyboard focus while the active top level window is
  36663. unchanged.
  36664. A top-level window also has an optional drop-shadow.
  36665. @see ResizableWindow, DocumentWindow, DialogWindow
  36666. */
  36667. class JUCE_API TopLevelWindow : public Component
  36668. {
  36669. public:
  36670. /** Creates a TopLevelWindow.
  36671. @param name the name to give the component
  36672. @param addToDesktop if true, the window will be automatically added to the
  36673. desktop; if false, you can use it as a child component
  36674. */
  36675. TopLevelWindow (const String& name,
  36676. const bool addToDesktop);
  36677. /** Destructor. */
  36678. ~TopLevelWindow();
  36679. /** True if this is currently the TopLevelWindow that is actively being used.
  36680. This isn't quite the same as having keyboard focus, because the focus may be
  36681. on a child component or a temporary pop-up menu, etc, while this window is
  36682. still considered to be active.
  36683. @see activeWindowStatusChanged
  36684. */
  36685. bool isActiveWindow() const throw() { return windowIsActive_; }
  36686. /** This will set the bounds of the window so that it's centred in front of another
  36687. window.
  36688. If your app has a few windows open and want to pop up a dialog box for one of
  36689. them, you can use this to show it in front of the relevent parent window, which
  36690. is a bit neater than just having it appear in the middle of the screen.
  36691. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36692. be used instead. If no window is focused, it'll just default to the middle of the
  36693. screen.
  36694. */
  36695. void centreAroundComponent (Component* componentToCentreAround,
  36696. const int width, const int height);
  36697. /** Turns the drop-shadow on and off. */
  36698. void setDropShadowEnabled (const bool useShadow);
  36699. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36700. @see isUsingNativeTitleBar
  36701. */
  36702. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  36703. /** Returns true if the window is currently using an OS-native title bar.
  36704. @see setUsingNativeTitleBar
  36705. */
  36706. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36707. /** Returns the number of TopLevelWindow objects currently in use.
  36708. @see getTopLevelWindow
  36709. */
  36710. static int getNumTopLevelWindows() throw();
  36711. /** Returns one of the TopLevelWindow objects currently in use.
  36712. The index is 0 to (getNumTopLevelWindows() - 1).
  36713. */
  36714. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  36715. /** Returns the currently-active top level window.
  36716. There might not be one, of course, so this can return 0.
  36717. */
  36718. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36719. juce_UseDebuggingNewOperator
  36720. /** @internal */
  36721. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36722. protected:
  36723. /** This callback happens when this window becomes active or inactive.
  36724. @see isActiveWindow
  36725. */
  36726. virtual void activeWindowStatusChanged();
  36727. /** @internal */
  36728. void focusOfChildComponentChanged (FocusChangeType cause);
  36729. /** @internal */
  36730. void parentHierarchyChanged();
  36731. /** @internal */
  36732. void visibilityChanged();
  36733. /** @internal */
  36734. virtual int getDesktopWindowStyleFlags() const;
  36735. /** @internal */
  36736. void recreateDesktopWindow();
  36737. private:
  36738. friend class TopLevelWindowManager;
  36739. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  36740. DropShadower* shadower;
  36741. void setWindowActive (const bool isNowActive) throw();
  36742. TopLevelWindow (const TopLevelWindow&);
  36743. const TopLevelWindow& operator= (const TopLevelWindow&);
  36744. };
  36745. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36746. /********* End of inlined file: juce_TopLevelWindow.h *********/
  36747. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  36748. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36749. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36750. /**
  36751. A component that resizes its parent window when dragged.
  36752. This component forms a frame around the edge of a component, allowing it to
  36753. be dragged by the edges or corners to resize it - like the way windows are
  36754. resized in MSWindows or Linux.
  36755. To use it, just add it to your component, making it fill the entire parent component
  36756. (there's a mouse hit-test that only traps mouse-events which land around the
  36757. edge of the component, so it's even ok to put it on top of any other components
  36758. you're using). Make sure you rescale the resizer component to fill the parent
  36759. each time the parent's size changes.
  36760. @see ResizableCornerComponent
  36761. */
  36762. class JUCE_API ResizableBorderComponent : public Component
  36763. {
  36764. public:
  36765. /** Creates a resizer.
  36766. Pass in the target component which you want to be resized when this one is
  36767. dragged.
  36768. The target component will usually be a parent of the resizer component, but this
  36769. isn't mandatory.
  36770. Remember that when the target component is resized, it'll need to move and
  36771. resize this component to keep it in place, as this won't happen automatically.
  36772. If the constrainer parameter is non-zero, then this object will be used to enforce
  36773. limits on the size and position that the component can be stretched to. Make sure
  36774. that the constrainer isn't deleted while still in use by this object.
  36775. @see ComponentBoundsConstrainer
  36776. */
  36777. ResizableBorderComponent (Component* const componentToResize,
  36778. ComponentBoundsConstrainer* const constrainer);
  36779. /** Destructor. */
  36780. ~ResizableBorderComponent();
  36781. /** Specifies how many pixels wide the draggable edges of this component are.
  36782. @see getBorderThickness
  36783. */
  36784. void setBorderThickness (const BorderSize& newBorderSize) throw();
  36785. /** Returns the number of pixels wide that the draggable edges of this component are.
  36786. @see setBorderThickness
  36787. */
  36788. const BorderSize getBorderThickness() const throw();
  36789. juce_UseDebuggingNewOperator
  36790. protected:
  36791. /** @internal */
  36792. void paint (Graphics& g);
  36793. /** @internal */
  36794. void mouseEnter (const MouseEvent& e);
  36795. /** @internal */
  36796. void mouseMove (const MouseEvent& e);
  36797. /** @internal */
  36798. void mouseDown (const MouseEvent& e);
  36799. /** @internal */
  36800. void mouseDrag (const MouseEvent& e);
  36801. /** @internal */
  36802. void mouseUp (const MouseEvent& e);
  36803. /** @internal */
  36804. bool hitTest (int x, int y);
  36805. private:
  36806. Component* const component;
  36807. ComponentBoundsConstrainer* constrainer;
  36808. BorderSize borderSize;
  36809. int originalX, originalY, originalW, originalH;
  36810. int mouseZone;
  36811. void updateMouseZone (const MouseEvent& e) throw();
  36812. ResizableBorderComponent (const ResizableBorderComponent&);
  36813. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  36814. };
  36815. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36816. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  36817. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  36818. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36819. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36820. /** A component that resizes a parent window when dragged.
  36821. This is the small triangular stripey resizer component you get in the bottom-right
  36822. of windows (more commonly on the Mac than Windows). Put one in the corner of
  36823. a larger component and it will automatically resize its parent when it gets dragged
  36824. around.
  36825. @see ResizableFrameComponent
  36826. */
  36827. class JUCE_API ResizableCornerComponent : public Component
  36828. {
  36829. public:
  36830. /** Creates a resizer.
  36831. Pass in the target component which you want to be resized when this one is
  36832. dragged.
  36833. The target component will usually be a parent of the resizer component, but this
  36834. isn't mandatory.
  36835. Remember that when the target component is resized, it'll need to move and
  36836. resize this component to keep it in place, as this won't happen automatically.
  36837. If the constrainer parameter is non-zero, then this object will be used to enforce
  36838. limits on the size and position that the component can be stretched to. Make sure
  36839. that the constrainer isn't deleted while still in use by this object. If you
  36840. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  36841. @see ComponentBoundsConstrainer
  36842. */
  36843. ResizableCornerComponent (Component* const componentToResize,
  36844. ComponentBoundsConstrainer* const constrainer);
  36845. /** Destructor. */
  36846. ~ResizableCornerComponent();
  36847. juce_UseDebuggingNewOperator
  36848. protected:
  36849. /** @internal */
  36850. void paint (Graphics& g);
  36851. /** @internal */
  36852. void mouseDown (const MouseEvent& e);
  36853. /** @internal */
  36854. void mouseDrag (const MouseEvent& e);
  36855. /** @internal */
  36856. void mouseUp (const MouseEvent& e);
  36857. /** @internal */
  36858. bool hitTest (int x, int y);
  36859. private:
  36860. Component* const component;
  36861. ComponentBoundsConstrainer* constrainer;
  36862. int originalX, originalY, originalW, originalH;
  36863. ResizableCornerComponent (const ResizableCornerComponent&);
  36864. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  36865. };
  36866. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36867. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  36868. /**
  36869. A base class for top-level windows that can be dragged around and resized.
  36870. To add content to the window, use its setContentComponent() method to
  36871. give it a component that will remain positioned inside it (leaving a gap around
  36872. the edges for a border).
  36873. It's not advisable to add child components directly to a ResizableWindow: put them
  36874. inside your content component instead. And overriding methods like resized(), moved(), etc
  36875. is also not recommended - instead override these methods for your content component.
  36876. (If for some obscure reason you do need to override these methods, always remember to
  36877. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36878. decorations correctly).
  36879. By default resizing isn't enabled - use the setResizable() method to enable it and
  36880. to choose the style of resizing to use.
  36881. @see TopLevelWindow
  36882. */
  36883. class JUCE_API ResizableWindow : public TopLevelWindow
  36884. {
  36885. public:
  36886. /** Creates a ResizableWindow.
  36887. This constructor doesn't specify a background colour, so the LookAndFeel's default
  36888. background colour will be used.
  36889. @param name the name to give the component
  36890. @param addToDesktop if true, the window will be automatically added to the
  36891. desktop; if false, you can use it as a child component
  36892. */
  36893. ResizableWindow (const String& name,
  36894. const bool addToDesktop);
  36895. /** Creates a ResizableWindow.
  36896. @param name the name to give the component
  36897. @param backgroundColour the colour to use for filling the window's background.
  36898. @param addToDesktop if true, the window will be automatically added to the
  36899. desktop; if false, you can use it as a child component
  36900. */
  36901. ResizableWindow (const String& name,
  36902. const Colour& backgroundColour,
  36903. const bool addToDesktop);
  36904. /** Destructor.
  36905. If a content component has been set with setContentComponent(), it
  36906. will be deleted.
  36907. */
  36908. ~ResizableWindow();
  36909. /** Returns the colour currently being used for the window's background.
  36910. As a convenience the window will fill itself with this colour, but you
  36911. can override the paint() method if you need more customised behaviour.
  36912. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  36913. @see setBackgroundColour
  36914. */
  36915. const Colour getBackgroundColour() const throw();
  36916. /** Changes the colour currently being used for the window's background.
  36917. As a convenience the window will fill itself with this colour, but you
  36918. can override the paint() method if you need more customised behaviour.
  36919. Note that the opaque state of this window is altered by this call to reflect
  36920. the opacity of the colour passed-in. On window systems which can't support
  36921. semi-transparent windows this might cause problems, (though it's unlikely you'll
  36922. be using this class as a base for a semi-transparent component anyway).
  36923. You can also use the ResizableWindow::backgroundColourId colour id to set
  36924. this colour.
  36925. @see getBackgroundColour
  36926. */
  36927. void setBackgroundColour (const Colour& newColour);
  36928. /** Make the window resizable or fixed.
  36929. @param shouldBeResizable whether it's resizable at all
  36930. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  36931. bottom-right; if false, it'll use a ResizableBorderComponent
  36932. around the edge
  36933. @see setResizeLimits, isResizable
  36934. */
  36935. void setResizable (const bool shouldBeResizable,
  36936. const bool useBottomRightCornerResizer);
  36937. /** True if resizing is enabled.
  36938. @see setResizable
  36939. */
  36940. bool isResizable() const throw();
  36941. /** This sets the maximum and minimum sizes for the window.
  36942. If the window's current size is outside these limits, it will be resized to
  36943. make sure it's within them.
  36944. Calling setBounds() on the component will bypass any size checking - it's only when
  36945. the window is being resized by the user that these values are enforced.
  36946. @see setResizable, setFixedAspectRatio
  36947. */
  36948. void setResizeLimits (const int newMinimumWidth,
  36949. const int newMinimumHeight,
  36950. const int newMaximumWidth,
  36951. const int newMaximumHeight) throw();
  36952. /** Returns the bounds constrainer object that this window is using.
  36953. You can access this to change its properties.
  36954. */
  36955. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  36956. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  36957. A pointer to the object you pass in will be kept, but it won't be deleted
  36958. by this object, so it's the caller's responsiblity to manage it.
  36959. If you pass 0, then no contraints will be placed on the positioning of the window.
  36960. */
  36961. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  36962. /** Calls the window's setBounds method, after first checking these bounds
  36963. with the current constrainer.
  36964. @see setConstrainer
  36965. */
  36966. void setBoundsConstrained (int x, int y, int width, int height);
  36967. /** Returns true if the window is currently in full-screen mode.
  36968. @see setFullScreen
  36969. */
  36970. bool isFullScreen() const;
  36971. /** Puts the window into full-screen mode, or restores it to its normal size.
  36972. If true, the window will become full-screen; if false, it will return to the
  36973. last size it was before being made full-screen.
  36974. @see isFullScreen
  36975. */
  36976. void setFullScreen (const bool shouldBeFullScreen);
  36977. /** Returns true if the window is currently minimised.
  36978. @see setMinimised
  36979. */
  36980. bool isMinimised() const;
  36981. /** Minimises the window, or restores it to its previous position and size.
  36982. When being un-minimised, it'll return to the last position and size it
  36983. was in before being minimised.
  36984. @see isMinimised
  36985. */
  36986. void setMinimised (const bool shouldMinimise);
  36987. /** Returns a string which encodes the window's current size and position.
  36988. This string will encapsulate the window's size, position, and whether it's
  36989. in full-screen mode. It's intended for letting your application save and
  36990. restore a window's position.
  36991. Use the restoreWindowStateFromString() to restore from a saved state.
  36992. @see restoreWindowStateFromString
  36993. */
  36994. const String getWindowStateAsString();
  36995. /** Restores the window to a previously-saved size and position.
  36996. This restores the window's size, positon and full-screen status from an
  36997. string that was previously created with the getWindowStateAsString()
  36998. method.
  36999. @returns false if the string wasn't a valid window state
  37000. @see getWindowStateAsString
  37001. */
  37002. bool restoreWindowStateFromString (const String& previousState);
  37003. /** Returns the current content component.
  37004. This will be the component set by setContentComponent(), or 0 if none
  37005. has yet been specified.
  37006. @see setContentComponent
  37007. */
  37008. Component* getContentComponent() const throw() { return contentComponent; }
  37009. /** Changes the current content component.
  37010. This sets a component that will be placed in the centre of the ResizableWindow,
  37011. (leaving a space around the edge for the border).
  37012. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37013. with addChildComponent(). Instead, add them to the content component.
  37014. @param newContentComponent the new component to use (or null to not use one) - this
  37015. component will be deleted either when replaced by another call
  37016. to this method, or when the ResizableWindow is deleted.
  37017. To remove a content component without deleting it, use
  37018. setContentComponent (0, false).
  37019. @param deleteOldOne if true, the previous content component will be deleted; if
  37020. false, the previous component will just be removed without
  37021. deleting it.
  37022. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37023. it always fits around the size of the content component. If false, the
  37024. new content will be resized to fit the current space available.
  37025. */
  37026. void setContentComponent (Component* const newContentComponent,
  37027. const bool deleteOldOne = true,
  37028. const bool resizeToFit = false);
  37029. /** Changes the window so that the content component ends up with the specified size.
  37030. This is basically a setSize call on the window, but which adds on the borders,
  37031. so you can specify the content component's target size.
  37032. */
  37033. void setContentComponentSize (int width, int height);
  37034. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37035. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37036. methods.
  37037. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37038. */
  37039. enum ColourIds
  37040. {
  37041. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37042. };
  37043. juce_UseDebuggingNewOperator
  37044. protected:
  37045. /** @internal */
  37046. void paint (Graphics& g);
  37047. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37048. void moved();
  37049. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37050. void resized();
  37051. /** @internal */
  37052. void mouseDown (const MouseEvent& e);
  37053. /** @internal */
  37054. void mouseDrag (const MouseEvent& e);
  37055. /** @internal */
  37056. void lookAndFeelChanged();
  37057. /** @internal */
  37058. void childBoundsChanged (Component* child);
  37059. /** @internal */
  37060. void parentSizeChanged();
  37061. /** @internal */
  37062. void visibilityChanged();
  37063. /** @internal */
  37064. void activeWindowStatusChanged();
  37065. /** @internal */
  37066. int getDesktopWindowStyleFlags() const;
  37067. /** Returns the width of the border to use around the window.
  37068. @see getContentComponentBorder
  37069. */
  37070. virtual const BorderSize getBorderThickness();
  37071. /** Returns the insets to use when positioning the content component.
  37072. @see getBorderThickness
  37073. */
  37074. virtual const BorderSize getContentComponentBorder();
  37075. #ifdef JUCE_DEBUG
  37076. /** Overridden to warn people about adding components directly to this component
  37077. instead of using setContentComponent().
  37078. If you know what you're doing and are sure you really want to add a component, specify
  37079. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37080. */
  37081. void addChildComponent (Component* const child, int zOrder = -1);
  37082. /** Overridden to warn people about adding components directly to this component
  37083. instead of using setContentComponent().
  37084. If you know what you're doing and are sure you really want to add a component, specify
  37085. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37086. */
  37087. void addAndMakeVisible (Component* const child, int zOrder = -1);
  37088. #endif
  37089. ResizableCornerComponent* resizableCorner;
  37090. ResizableBorderComponent* resizableBorder;
  37091. private:
  37092. Component* contentComponent;
  37093. bool resizeToFitContent, fullscreen;
  37094. ComponentDragger dragger;
  37095. Rectangle lastNonFullScreenPos;
  37096. ComponentBoundsConstrainer defaultConstrainer;
  37097. ComponentBoundsConstrainer* constrainer;
  37098. #ifdef JUCE_DEBUG
  37099. bool hasBeenResized;
  37100. #endif
  37101. void updateLastPos();
  37102. ResizableWindow (const ResizableWindow&);
  37103. const ResizableWindow& operator= (const ResizableWindow&);
  37104. // (xxx remove these eventually)
  37105. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37106. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37107. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37108. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37109. };
  37110. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37111. /********* End of inlined file: juce_ResizableWindow.h *********/
  37112. /**
  37113. A resizable window with a title bar and maximise, minimise and close buttons.
  37114. This subclass of ResizableWindow creates a fairly standard type of window with
  37115. a title bar and various buttons. The name of the component is shown in the
  37116. title bar, and an icon can optionally be specified with setIcon().
  37117. All the methods available to a ResizableWindow are also available to this,
  37118. so it can easily be made resizable, minimised, maximised, etc.
  37119. It's not advisable to add child components directly to a DocumentWindow: put them
  37120. inside your content component instead. And overriding methods like resized(), moved(), etc
  37121. is also not recommended - instead override these methods for your content component.
  37122. (If for some obscure reason you do need to override these methods, always remember to
  37123. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37124. decorations correctly).
  37125. You can also automatically add a menu bar to the window, using the setMenuBar()
  37126. method.
  37127. @see ResizableWindow, DialogWindow
  37128. */
  37129. class JUCE_API DocumentWindow : public ResizableWindow
  37130. {
  37131. public:
  37132. /** The set of available button-types that can be put on the title bar.
  37133. @see setTitleBarButtonsRequired
  37134. */
  37135. enum TitleBarButtons
  37136. {
  37137. minimiseButton = 1,
  37138. maximiseButton = 2,
  37139. closeButton = 4,
  37140. /** A combination of all the buttons above. */
  37141. allButtons = 7
  37142. };
  37143. /** Creates a DocumentWindow.
  37144. @param name the name to give the component - this is also
  37145. the title shown at the top of the window. To change
  37146. this later, use setName()
  37147. @param backgroundColour the colour to use for filling the window's background.
  37148. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  37149. should be shown on the title bar. This value is a bitwise
  37150. combination of values from the TitleBarButtons enum. Note
  37151. that it can be "allButtons" to get them all. You
  37152. can change this later with the setTitleBarButtonsRequired()
  37153. method, which can also specify where they are positioned.
  37154. @param addToDesktop if true, the window will be automatically added to the
  37155. desktop; if false, you can use it as a child component
  37156. @see TitleBarButtons
  37157. */
  37158. DocumentWindow (const String& name,
  37159. const Colour& backgroundColour,
  37160. const int requiredButtons,
  37161. const bool addToDesktop = true);
  37162. /** Destructor.
  37163. If a content component has been set with setContentComponent(), it
  37164. will be deleted.
  37165. */
  37166. ~DocumentWindow();
  37167. /** Changes the component's name.
  37168. (This is overridden from Component::setName() to cause a repaint, as
  37169. the name is what gets drawn across the window's title bar).
  37170. */
  37171. void setName (const String& newName);
  37172. /** Sets an icon to show in the title bar, next to the title.
  37173. A copy is made internally of the image, so the caller can delete the
  37174. image after calling this. If 0 is passed-in, any existing icon will be
  37175. removed.
  37176. */
  37177. void setIcon (const Image* imageToUse);
  37178. /** Changes the height of the title-bar. */
  37179. void setTitleBarHeight (const int newHeight);
  37180. /** Returns the current title bar height. */
  37181. int getTitleBarHeight() const;
  37182. /** Changes the set of title-bar buttons being shown.
  37183. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  37184. should be shown on the title bar. This value is a bitwise
  37185. combination of values from the TitleBarButtons enum. Note
  37186. that it can be "allButtons" to get them all.
  37187. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  37188. left side of the bar; if false, they'll be placed at the right
  37189. */
  37190. void setTitleBarButtonsRequired (const int requiredButtons,
  37191. const bool positionTitleBarButtonsOnLeft);
  37192. /** Sets whether the title should be centred within the window.
  37193. If true, the title text is shown in the middle of the title-bar; if false,
  37194. it'll be shown at the left of the bar.
  37195. */
  37196. void setTitleBarTextCentred (const bool textShouldBeCentred);
  37197. /** Creates a menu inside this window.
  37198. @param menuBarModel this specifies a MenuBarModel that should be used to
  37199. generate the contents of a menu bar that will be placed
  37200. just below the title bar, and just above any content
  37201. component. If this value is zero, any existing menu bar
  37202. will be removed from the component; if non-zero, one will
  37203. be added if it's required.
  37204. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  37205. or less to use the look-and-feel's default size.
  37206. */
  37207. void setMenuBar (MenuBarModel* menuBarModel,
  37208. const int menuBarHeight = 0);
  37209. /** This method is called when the user tries to close the window.
  37210. This is triggered by the user clicking the close button, or using some other
  37211. OS-specific key shortcut or OS menu for getting rid of a window.
  37212. If the window is just a pop-up, you should override this closeButtonPressed()
  37213. method and make it delete the window in whatever way is appropriate for your
  37214. app. E.g. you might just want to call "delete this".
  37215. If your app is centred around this window such that the whole app should quit when
  37216. the window is closed, then you will probably want to use this method as an opportunity
  37217. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  37218. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  37219. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  37220. or closing it via the taskbar icon on Windows).
  37221. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  37222. redirects it to call this method, so any methods of closing the window that are
  37223. caught by userTriedToCloseWindow() will also end up here).
  37224. */
  37225. virtual void closeButtonPressed();
  37226. /** Callback that is triggered when the minimise button is pressed.
  37227. The default implementation of this calls ResizableWindow::setMinimised(), but
  37228. you can override it to do more customised behaviour.
  37229. */
  37230. virtual void minimiseButtonPressed();
  37231. /** Callback that is triggered when the maximise button is pressed, or when the
  37232. title-bar is double-clicked.
  37233. The default implementation of this calls ResizableWindow::setFullScreen(), but
  37234. you can override it to do more customised behaviour.
  37235. */
  37236. virtual void maximiseButtonPressed();
  37237. /** Returns the close button, (or 0 if there isn't one). */
  37238. Button* getCloseButton() const throw();
  37239. /** Returns the minimise button, (or 0 if there isn't one). */
  37240. Button* getMinimiseButton() const throw();
  37241. /** Returns the maximise button, (or 0 if there isn't one). */
  37242. Button* getMaximiseButton() const throw();
  37243. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37244. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37245. methods.
  37246. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37247. */
  37248. enum ColourIds
  37249. {
  37250. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  37251. and feel class how this is used. */
  37252. };
  37253. /** @internal */
  37254. void paint (Graphics& g);
  37255. /** @internal */
  37256. void resized();
  37257. /** @internal */
  37258. void lookAndFeelChanged();
  37259. /** @internal */
  37260. const BorderSize getBorderThickness();
  37261. /** @internal */
  37262. const BorderSize getContentComponentBorder();
  37263. /** @internal */
  37264. void mouseDoubleClick (const MouseEvent& e);
  37265. /** @internal */
  37266. void userTriedToCloseWindow();
  37267. /** @internal */
  37268. void activeWindowStatusChanged();
  37269. /** @internal */
  37270. int getDesktopWindowStyleFlags() const;
  37271. /** @internal */
  37272. void parentHierarchyChanged();
  37273. /** @internal */
  37274. const Rectangle getTitleBarArea();
  37275. juce_UseDebuggingNewOperator
  37276. private:
  37277. int titleBarHeight, menuBarHeight, requiredButtons;
  37278. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  37279. Button* titleBarButtons [3];
  37280. Image* titleBarIcon;
  37281. MenuBarComponent* menuBar;
  37282. MenuBarModel* menuBarModel;
  37283. class ButtonListenerProxy : public ButtonListener
  37284. {
  37285. public:
  37286. ButtonListenerProxy();
  37287. void buttonClicked (Button* button);
  37288. DocumentWindow* owner;
  37289. } buttonListener;
  37290. void repaintTitleBar();
  37291. DocumentWindow (const DocumentWindow&);
  37292. const DocumentWindow& operator= (const DocumentWindow&);
  37293. };
  37294. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37295. /********* End of inlined file: juce_DocumentWindow.h *********/
  37296. class MultiDocumentPanel;
  37297. class MDITabbedComponentInternal;
  37298. /**
  37299. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  37300. component.
  37301. It's like a normal DocumentWindow but has some extra functionality to make sure
  37302. everything works nicely inside a MultiDocumentPanel.
  37303. @see MultiDocumentPanel
  37304. */
  37305. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  37306. {
  37307. public:
  37308. /**
  37309. */
  37310. MultiDocumentPanelWindow (const Colour& backgroundColour);
  37311. /** Destructor. */
  37312. ~MultiDocumentPanelWindow();
  37313. /** @internal */
  37314. void maximiseButtonPressed();
  37315. /** @internal */
  37316. void closeButtonPressed();
  37317. /** @internal */
  37318. void activeWindowStatusChanged();
  37319. /** @internal */
  37320. void broughtToFront();
  37321. juce_UseDebuggingNewOperator
  37322. private:
  37323. void updateOrder();
  37324. MultiDocumentPanel* getOwner() const throw();
  37325. };
  37326. /**
  37327. A component that contains a set of other components either in floating windows
  37328. or tabs.
  37329. This acts as a panel that can be used to hold a set of open document windows, with
  37330. different layout modes.
  37331. Use addDocument() and closeDocument() to add or remove components from the
  37332. panel - never use any of the Component methods to access the panel's child
  37333. components directly, as these are managed internally.
  37334. */
  37335. class JUCE_API MultiDocumentPanel : public Component,
  37336. private ComponentListener
  37337. {
  37338. public:
  37339. /** Creates an empty panel.
  37340. Use addDocument() and closeDocument() to add or remove components from the
  37341. panel - never use any of the Component methods to access the panel's child
  37342. components directly, as these are managed internally.
  37343. */
  37344. MultiDocumentPanel();
  37345. /** Destructor.
  37346. When deleted, this will call closeAllDocuments (false) to make sure all its
  37347. components are deleted. If you need to make sure all documents are saved
  37348. before closing, then you should call closeAllDocuments (true) and check that
  37349. it returns true before deleting the panel.
  37350. */
  37351. ~MultiDocumentPanel();
  37352. /** Tries to close all the documents.
  37353. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37354. be called for each open document, and any of these calls fails, this method
  37355. will stop and return false, leaving some documents still open.
  37356. If checkItsOkToCloseFirst is false, then all documents will be closed
  37357. unconditionally.
  37358. @see closeDocument
  37359. */
  37360. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  37361. /** Adds a document component to the panel.
  37362. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  37363. this will fail and return false. (If it does fail, the component passed-in will not be
  37364. deleted, even if deleteWhenRemoved was set to true).
  37365. The MultiDocumentPanel will deal with creating a window border to go around your component,
  37366. so just pass in the bare content component here, no need to give it a ResizableWindow
  37367. or DocumentWindow.
  37368. @param component the component to add
  37369. @param backgroundColour the background colour to use to fill the component's
  37370. window or tab
  37371. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  37372. or closeAllDocuments(), then it will be deleted. If false, then
  37373. the caller must handle the component's deletion
  37374. */
  37375. bool addDocument (Component* const component,
  37376. const Colour& backgroundColour,
  37377. const bool deleteWhenRemoved);
  37378. /** Closes one of the documents.
  37379. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37380. be called, and if it fails, this method will return false without closing the
  37381. document.
  37382. If checkItsOkToCloseFirst is false, then the documents will be closed
  37383. unconditionally.
  37384. The component will be deleted if the deleteWhenRemoved parameter was set to
  37385. true when it was added with addDocument.
  37386. @see addDocument, closeAllDocuments
  37387. */
  37388. bool closeDocument (Component* component,
  37389. const bool checkItsOkToCloseFirst);
  37390. /** Returns the number of open document windows.
  37391. @see getDocument
  37392. */
  37393. int getNumDocuments() const throw();
  37394. /** Returns one of the open documents.
  37395. The order of the documents in this array may change when they are added, removed
  37396. or moved around.
  37397. @see getNumDocuments
  37398. */
  37399. Component* getDocument (const int index) const throw();
  37400. /** Returns the document component that is currently focused or on top.
  37401. If currently using floating windows, then this will be the component in the currently
  37402. active window, or the top component if none are active.
  37403. If it's currently in tabbed mode, then it'll return the component in the active tab.
  37404. @see setActiveDocument
  37405. */
  37406. Component* getActiveDocument() const throw();
  37407. /** Makes one of the components active and brings it to the top.
  37408. @see getActiveDocument
  37409. */
  37410. void setActiveDocument (Component* component);
  37411. /** Callback which gets invoked when the currently-active document changes. */
  37412. virtual void activeDocumentChanged();
  37413. /** Sets a limit on how many windows can be open at once.
  37414. If this is zero or less there's no limit (the default). addDocument() will fail
  37415. if this number is exceeded.
  37416. */
  37417. void setMaximumNumDocuments (const int maximumNumDocuments);
  37418. /** Sets an option to make the document fullscreen if there's only one document open.
  37419. If set to true, then if there's only one document, it'll fill the whole of this
  37420. component without tabs or a window border. If false, then tabs or a window
  37421. will always be shown, even if there's only one document. If there's more than
  37422. one document open, then this option makes no difference.
  37423. */
  37424. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  37425. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  37426. */
  37427. bool isFullscreenWhenOneDocument() const throw();
  37428. /** The different layout modes available. */
  37429. enum LayoutMode
  37430. {
  37431. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  37432. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  37433. };
  37434. /** Changes the panel's mode.
  37435. @see LayoutMode, getLayoutMode
  37436. */
  37437. void setLayoutMode (const LayoutMode newLayoutMode);
  37438. /** Returns the current layout mode. */
  37439. LayoutMode getLayoutMode() const throw() { return mode; }
  37440. /** Sets the background colour for the whole panel.
  37441. Each document has its own background colour, but this is the one used to fill the areas
  37442. behind them.
  37443. */
  37444. void setBackgroundColour (const Colour& newBackgroundColour);
  37445. /** Returns the current background colour.
  37446. @see setBackgroundColour
  37447. */
  37448. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  37449. /** A subclass must override this to say whether its currently ok for a document
  37450. to be closed.
  37451. This method is called by closeDocument() and closeAllDocuments() to indicate that
  37452. a document should be saved if possible, ready for it to be closed.
  37453. If this method returns true, then it means the document is ok and can be closed.
  37454. If it returns false, then it means that the closeDocument() method should stop
  37455. and not close.
  37456. Normally, you'd use this method to ask the user if they want to save any changes,
  37457. then return true if the save operation went ok. If the user cancelled the save
  37458. operation you could return false here to abort the close operation.
  37459. If your component is based on the FileBasedDocument class, then you'd probably want
  37460. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  37461. FileBasedDocument::savedOk
  37462. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  37463. */
  37464. virtual bool tryToCloseDocument (Component* component) = 0;
  37465. /** Creates a new window to be used for a document.
  37466. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  37467. but you might want to override it to return a custom component.
  37468. */
  37469. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  37470. /** @internal */
  37471. void paint (Graphics& g);
  37472. /** @internal */
  37473. void resized();
  37474. /** @internal */
  37475. void componentNameChanged (Component&);
  37476. juce_UseDebuggingNewOperator
  37477. private:
  37478. LayoutMode mode;
  37479. Array <Component*> components;
  37480. TabbedComponent* tabComponent;
  37481. Colour backgroundColour;
  37482. int maximumNumDocuments, numDocsBeforeTabsUsed;
  37483. friend class MultiDocumentPanelWindow;
  37484. friend class MDITabbedComponentInternal;
  37485. Component* getContainerComp (Component* c) const;
  37486. void updateOrder();
  37487. void addWindow (Component* component);
  37488. };
  37489. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  37490. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  37491. #endif
  37492. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37493. #endif
  37494. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37495. #endif
  37496. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  37497. #endif
  37498. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37499. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  37500. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37501. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37502. /**
  37503. For laying out a set of components, where the components have preferred sizes
  37504. and size limits, but where they are allowed to stretch to fill the available
  37505. space.
  37506. For example, if you have a component containing several other components, and
  37507. each one should be given a share of the total size, you could use one of these
  37508. to resize the child components when the parent component is resized. Then
  37509. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  37510. A StretchableLayoutManager operates only in one dimension, so if you have a set
  37511. of components stacked vertically on top of each other, you'd use one to manage their
  37512. heights. To build up complex arrangements of components, e.g. for applications
  37513. with multiple nested panels, you would use more than one StretchableLayoutManager.
  37514. E.g. by using two (one vertical, one horizontal), you could create a resizable
  37515. spreadsheet-style table.
  37516. E.g.
  37517. @code
  37518. class MyComp : public Component
  37519. {
  37520. StretchableLayoutManager myLayout;
  37521. MyComp()
  37522. {
  37523. myLayout.setItemLayout (0, // for item 0
  37524. 50, 100, // must be between 50 and 100 pixels in size
  37525. -0.6); // and its preferred size is 60% of the total available space
  37526. myLayout.setItemLayout (1, // for item 1
  37527. -0.2, -0.6, // size must be between 20% and 60% of the available space
  37528. 50); // and its preferred size is 50 pixels
  37529. }
  37530. void resized()
  37531. {
  37532. // make a list of two of our child components that we want to reposition
  37533. Component* comps[] = { myComp1, myComp2 };
  37534. // this will position the 2 components, one above the other, to fit
  37535. // vertically into the rectangle provided.
  37536. myLayout.layOutComponents (comps, 2,
  37537. 0, 0, getWidth(), getHeight(),
  37538. true);
  37539. }
  37540. };
  37541. @endcode
  37542. @see StretchableLayoutResizerBar
  37543. */
  37544. class JUCE_API StretchableLayoutManager
  37545. {
  37546. public:
  37547. /** Creates an empty layout.
  37548. You'll need to add some item properties to the layout before it can be used
  37549. to resize things - see setItemLayout().
  37550. */
  37551. StretchableLayoutManager();
  37552. /** Destructor. */
  37553. ~StretchableLayoutManager();
  37554. /** For a numbered item, this sets its size limits and preferred size.
  37555. @param itemIndex the index of the item to change.
  37556. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37557. indicates an absolute size in pixels. A negative number indicates a
  37558. proportion of the available space (e.g -0.5 is 50%)
  37559. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37560. indicates an absolute size in pixels. A negative number indicates a
  37561. proportion of the available space
  37562. @param preferredSize the size that this item would like to be, if there's enough room. A
  37563. positive number indicates an absolute size in pixels. A negative number
  37564. indicates a proportion of the available space
  37565. @see getItemLayout
  37566. */
  37567. void setItemLayout (const int itemIndex,
  37568. const double minimumSize,
  37569. const double maximumSize,
  37570. const double preferredSize);
  37571. /** For a numbered item, this returns its size limits and preferred size.
  37572. @param itemIndex the index of the item.
  37573. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37574. indicates an absolute size in pixels. A negative number indicates a
  37575. proportion of the available space (e.g -0.5 is 50%)
  37576. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37577. indicates an absolute size in pixels. A negative number indicates a
  37578. proportion of the available space
  37579. @param preferredSize the size that this item would like to be, if there's enough room. A
  37580. positive number indicates an absolute size in pixels. A negative number
  37581. indicates a proportion of the available space
  37582. @returns false if the item's properties hadn't been set
  37583. @see setItemLayout
  37584. */
  37585. bool getItemLayout (const int itemIndex,
  37586. double& minimumSize,
  37587. double& maximumSize,
  37588. double& preferredSize) const;
  37589. /** Clears all the properties that have been set with setItemLayout() and resets
  37590. this object to its initial state.
  37591. */
  37592. void clearAllItems();
  37593. /** Takes a set of components that correspond to the layout's items, and positions
  37594. them to fill a space.
  37595. This will try to give each item its preferred size, whether that's a relative size
  37596. or an absolute one.
  37597. @param components an array of components that correspond to each of the
  37598. numbered items that the StretchableLayoutManager object
  37599. has been told about with setItemLayout()
  37600. @param numComponents the number of components in the array that is passed-in. This
  37601. should be the same as the number of items this object has been
  37602. told about.
  37603. @param x the left of the rectangle in which the components should
  37604. be laid out
  37605. @param y the top of the rectangle in which the components should
  37606. be laid out
  37607. @param width the width of the rectangle in which the components should
  37608. be laid out
  37609. @param height the height of the rectangle in which the components should
  37610. be laid out
  37611. @param vertically if true, the components will be positioned in a vertical stack,
  37612. so that they fill the height of the rectangle. If false, they
  37613. will be placed side-by-side in a horizontal line, filling the
  37614. available width
  37615. @param resizeOtherDimension if true, this means that the components will have their
  37616. other dimension resized to fit the space - i.e. if the 'vertically'
  37617. parameter is true, their x-positions and widths are adjusted to fit
  37618. the x and width parameters; if 'vertically' is false, their y-positions
  37619. and heights are adjusted to fit the y and height parameters.
  37620. */
  37621. void layOutComponents (Component** const components,
  37622. int numComponents,
  37623. int x, int y, int width, int height,
  37624. const bool vertically,
  37625. const bool resizeOtherDimension);
  37626. /** Returns the current position of one of the items.
  37627. This is only a valid call after layOutComponents() has been called, as it
  37628. returns the last position that this item was placed at. If the layout was
  37629. vertical, the value returned will be the y position of the top of the item,
  37630. relative to the top of the rectangle in which the items were placed (so for
  37631. example, item 0 will always have position of 0, even in the rectangle passed
  37632. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  37633. the position returned is the item's left-hand position, again relative to the
  37634. x position of the rectangle used.
  37635. @see getItemCurrentSize, setItemPosition
  37636. */
  37637. int getItemCurrentPosition (const int itemIndex) const;
  37638. /** Returns the current size of one of the items.
  37639. This is only meaningful after layOutComponents() has been called, as it
  37640. returns the last size that this item was given. If the layout was done
  37641. vertically, it'll return the item's height in pixels; if it was horizontal,
  37642. it'll return its width.
  37643. @see getItemCurrentRelativeSize
  37644. */
  37645. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  37646. /** Returns the current size of one of the items.
  37647. This is only meaningful after layOutComponents() has been called, as it
  37648. returns the last size that this item was given. If the layout was done
  37649. vertically, it'll return a negative value representing the item's height relative
  37650. to the last size used for laying the components out; if the layout was done
  37651. horizontally it'll be the proportion of its width.
  37652. @see getItemCurrentAbsoluteSize
  37653. */
  37654. double getItemCurrentRelativeSize (const int itemIndex) const;
  37655. /** Moves one of the items, shifting along any other items as necessary in
  37656. order to get it to the desired position.
  37657. Calling this method will also update the preferred sizes of the items it
  37658. shuffles along, so that they reflect their new positions.
  37659. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  37660. about when it's dragged).
  37661. @param itemIndex the item to move
  37662. @param newPosition the absolute position that you'd like this item to move
  37663. to. The item might not be able to always reach exactly this position,
  37664. because other items may have minimum sizes that constrain how
  37665. far it can go
  37666. */
  37667. void setItemPosition (const int itemIndex,
  37668. int newPosition);
  37669. juce_UseDebuggingNewOperator
  37670. private:
  37671. struct ItemLayoutProperties
  37672. {
  37673. int itemIndex;
  37674. int currentSize;
  37675. double minSize, maxSize, preferredSize;
  37676. };
  37677. OwnedArray <ItemLayoutProperties> items;
  37678. int totalSize;
  37679. static int sizeToRealSize (double size, int totalSpace);
  37680. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  37681. void setTotalSize (const int newTotalSize);
  37682. int fitComponentsIntoSpace (const int startIndex,
  37683. const int endIndex,
  37684. const int availableSpace,
  37685. int startPos);
  37686. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  37687. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  37688. void updatePrefSizesToMatchCurrentPositions();
  37689. StretchableLayoutManager (const StretchableLayoutManager&);
  37690. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  37691. };
  37692. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37693. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  37694. #endif
  37695. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37696. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37697. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37698. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37699. /**
  37700. A component that acts as one of the vertical or horizontal bars you see being
  37701. used to resize panels in a window.
  37702. One of these acts with a StretchableLayoutManager to resize the other components.
  37703. @see StretchableLayoutManager
  37704. */
  37705. class JUCE_API StretchableLayoutResizerBar : public Component
  37706. {
  37707. public:
  37708. /** Creates a resizer bar for use on a specified layout.
  37709. @param layoutToUse the layout that will be affected when this bar
  37710. is dragged
  37711. @param itemIndexInLayout the item index in the layout that corresponds to
  37712. this bar component. You'll need to set up the item
  37713. properties in a suitable way for a divider bar, e.g.
  37714. for an 8-pixel wide bar which, you could call
  37715. myLayout->setItemLayout (barIndex, 8, 8, 8)
  37716. @param isBarVertical true if it's an upright bar that you drag left and
  37717. right; false for a horizontal one that you drag up and
  37718. down
  37719. */
  37720. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  37721. const int itemIndexInLayout,
  37722. const bool isBarVertical);
  37723. /** Destructor. */
  37724. ~StretchableLayoutResizerBar();
  37725. /** This is called when the bar is dragged.
  37726. This method must update the positions of any components whose position is
  37727. determined by the StretchableLayoutManager, because they might have just
  37728. moved.
  37729. The default implementation calls the resized() method of this component's
  37730. parent component, because that's often where you're likely to apply the
  37731. layout, but it can be overridden for more specific needs.
  37732. */
  37733. virtual void hasBeenMoved();
  37734. /** @internal */
  37735. void paint (Graphics& g);
  37736. /** @internal */
  37737. void mouseDown (const MouseEvent& e);
  37738. /** @internal */
  37739. void mouseDrag (const MouseEvent& e);
  37740. juce_UseDebuggingNewOperator
  37741. private:
  37742. StretchableLayoutManager* layout;
  37743. int itemIndex, mouseDownPos;
  37744. bool isVertical;
  37745. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  37746. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  37747. };
  37748. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37749. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37750. #endif
  37751. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37752. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  37753. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37754. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37755. /**
  37756. A utility class for fitting a set of objects whose sizes can vary between
  37757. a minimum and maximum size, into a space.
  37758. This is a trickier algorithm than it would first seem, so I've put it in this
  37759. class to allow it to be shared by various bits of code.
  37760. To use it, create one of these objects, call addItem() to add the list of items
  37761. you need, then call resizeToFit(), which will change all their sizes. You can
  37762. then retrieve the new sizes with getItemSize() and getNumItems().
  37763. It's currently used by the TableHeaderComponent for stretching out the table
  37764. headings to fill the table's width.
  37765. */
  37766. class StretchableObjectResizer
  37767. {
  37768. public:
  37769. /** Creates an empty object resizer. */
  37770. StretchableObjectResizer();
  37771. /** Destructor. */
  37772. ~StretchableObjectResizer();
  37773. /** Adds an item to the list.
  37774. The order parameter lets you specify groups of items that are resized first when some
  37775. space needs to be found. Those items with an order of 0 will be the first ones to be
  37776. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  37777. will then try resizing the items with an order of 1, then 2, and so on.
  37778. */
  37779. void addItem (const double currentSize,
  37780. const double minSize,
  37781. const double maxSize,
  37782. const int order = 0);
  37783. /** Resizes all the items to fit this amount of space.
  37784. This will attempt to fit them in without exceeding each item's miniumum and
  37785. maximum sizes. In cases where none of the items can be expanded or enlarged any
  37786. further, the final size may be greater or less than the size passed in.
  37787. After calling this method, you can retrieve the new sizes with the getItemSize()
  37788. method.
  37789. */
  37790. void resizeToFit (const double targetSize);
  37791. /** Returns the number of items that have been added. */
  37792. int getNumItems() const throw() { return items.size(); }
  37793. /** Returns the size of one of the items. */
  37794. double getItemSize (const int index) const throw();
  37795. juce_UseDebuggingNewOperator
  37796. private:
  37797. struct Item
  37798. {
  37799. double size;
  37800. double minSize;
  37801. double maxSize;
  37802. int order;
  37803. };
  37804. OwnedArray <Item> items;
  37805. StretchableObjectResizer (const StretchableObjectResizer&);
  37806. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  37807. };
  37808. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37809. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  37810. #endif
  37811. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  37812. #endif
  37813. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  37814. #endif
  37815. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  37816. #endif
  37817. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37818. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37819. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37820. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37821. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  37822. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37823. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37824. /********* Start of inlined file: juce_FileFilter.h *********/
  37825. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37826. #define __JUCE_FILEFILTER_JUCEHEADER__
  37827. /**
  37828. Interface for deciding which files are suitable for something.
  37829. For example, this is used by DirectoryContentsList to select which files
  37830. go into the list.
  37831. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37832. */
  37833. class JUCE_API FileFilter
  37834. {
  37835. public:
  37836. /** Creates a filter with the given description.
  37837. The description can be returned later with the getDescription() method.
  37838. */
  37839. FileFilter (const String& filterDescription);
  37840. /** Destructor. */
  37841. virtual ~FileFilter();
  37842. /** Returns the description that the filter was created with. */
  37843. const String& getDescription() const throw();
  37844. /** Should return true if this file is suitable for inclusion in whatever context
  37845. the object is being used.
  37846. */
  37847. virtual bool isFileSuitable (const File& file) const = 0;
  37848. /** Should return true if this directory is suitable for inclusion in whatever context
  37849. the object is being used.
  37850. */
  37851. virtual bool isDirectorySuitable (const File& file) const = 0;
  37852. protected:
  37853. String description;
  37854. };
  37855. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  37856. /********* End of inlined file: juce_FileFilter.h *********/
  37857. /**
  37858. A class to asynchronously scan for details about the files in a directory.
  37859. This keeps a list of files and some information about them, using a background
  37860. thread to scan for more files. As files are found, it broadcasts change messages
  37861. to tell any listeners.
  37862. @see FileListComponent, FileBrowserComponent
  37863. */
  37864. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  37865. public TimeSliceClient
  37866. {
  37867. public:
  37868. /** Creates a directory list.
  37869. To set the directory it should point to, use setDirectory(), which will
  37870. also start it scanning for files on the background thread.
  37871. When the background thread finds and adds new files to this list, the
  37872. ChangeBroadcaster class will send a change message, so you can register
  37873. listeners and update them when the list changes.
  37874. @param fileFilter an optional filter to select which files are
  37875. included in the list. If this is 0, then all files
  37876. and directories are included. Make sure that the
  37877. filter doesn't get deleted during the lifetime of this
  37878. object
  37879. @param threadToUse a thread object that this list can use
  37880. to scan for files as a background task. Make sure
  37881. that the thread you give it has been started, or you
  37882. won't get any files!
  37883. */
  37884. DirectoryContentsList (const FileFilter* const fileFilter,
  37885. TimeSliceThread& threadToUse);
  37886. /** Destructor. */
  37887. ~DirectoryContentsList();
  37888. /** Sets the directory to look in for files.
  37889. If the directory that's passed in is different to the current one, this will
  37890. also start the background thread scanning it for files.
  37891. */
  37892. void setDirectory (const File& directory,
  37893. const bool includeDirectories,
  37894. const bool includeFiles);
  37895. /** Returns the directory that's currently being used. */
  37896. const File& getDirectory() const throw();
  37897. /** Clears the list, and stops the thread scanning for files. */
  37898. void clear();
  37899. /** Clears the list and restarts scanning the directory for files. */
  37900. void refresh();
  37901. /** True if the background thread hasn't yet finished scanning for files. */
  37902. bool isStillLoading() const;
  37903. /** Tells the list whether or not to ignore hidden files.
  37904. By default these are ignored.
  37905. */
  37906. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  37907. /** Returns true if hidden files are ignored.
  37908. @see setIgnoresHiddenFiles
  37909. */
  37910. bool ignoresHiddenFiles() const throw() { return ignoreHiddenFiles; }
  37911. /** Contains cached information about one of the files in a DirectoryContentsList.
  37912. */
  37913. struct FileInfo
  37914. {
  37915. /** The filename.
  37916. This isn't a full pathname, it's just the last part of the path, same as you'd
  37917. get from File::getFileName().
  37918. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  37919. */
  37920. String filename;
  37921. /** File size in bytes. */
  37922. int64 fileSize;
  37923. /** File modification time.
  37924. As supplied by File::getLastModificationTime().
  37925. */
  37926. Time modificationTime;
  37927. /** File creation time.
  37928. As supplied by File::getCreationTime().
  37929. */
  37930. Time creationTime;
  37931. /** True if the file is a directory. */
  37932. bool isDirectory;
  37933. /** True if the file is read-only. */
  37934. bool isReadOnly;
  37935. };
  37936. /** Returns the number of files currently available in the list.
  37937. The info about one of these files can be retrieved with getFileInfo() or
  37938. getFile().
  37939. Obviously as the background thread runs and scans the directory for files, this
  37940. number will change.
  37941. @see getFileInfo, getFile
  37942. */
  37943. int getNumFiles() const;
  37944. /** Returns the cached information about one of the files in the list.
  37945. If the index is in-range, this will return true and will copy the file's details
  37946. to the structure that is passed-in.
  37947. If it returns false, then the index wasn't in range, and the structure won't
  37948. be affected.
  37949. @see getNumFiles, getFile
  37950. */
  37951. bool getFileInfo (const int index,
  37952. FileInfo& resultInfo) const;
  37953. /** Returns one of the files in the list.
  37954. @param index should be less than getNumFiles(). If this is out-of-range, the
  37955. return value will be File::nonexistent
  37956. @see getNumFiles, getFileInfo
  37957. */
  37958. const File getFile (const int index) const;
  37959. /** Returns the file filter being used.
  37960. The filter is specified in the constructor.
  37961. */
  37962. const FileFilter* getFilter() const throw() { return fileFilter; }
  37963. /** @internal */
  37964. bool useTimeSlice();
  37965. /** @internal */
  37966. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  37967. /** @internal */
  37968. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  37969. const DirectoryContentsList::FileInfo* const second) throw();
  37970. juce_UseDebuggingNewOperator
  37971. private:
  37972. File root;
  37973. const FileFilter* fileFilter;
  37974. TimeSliceThread& thread;
  37975. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  37976. CriticalSection fileListLock;
  37977. OwnedArray <FileInfo> files;
  37978. void* volatile fileFindHandle;
  37979. bool volatile shouldStop;
  37980. void changed();
  37981. bool checkNextFile (bool& hasChanged);
  37982. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  37983. const int64 fileSize, const Time& modTime,
  37984. const Time& creationTime, const bool isReadOnly);
  37985. DirectoryContentsList (const DirectoryContentsList&);
  37986. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  37987. };
  37988. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37989. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  37990. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  37991. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37992. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37993. /**
  37994. A listener for user selection events in a file browser.
  37995. This is used by a FileBrowserComponent or FileListComponent.
  37996. */
  37997. class JUCE_API FileBrowserListener
  37998. {
  37999. public:
  38000. /** Destructor. */
  38001. virtual ~FileBrowserListener();
  38002. /** Callback when the user selects a different file in the browser. */
  38003. virtual void selectionChanged() = 0;
  38004. /** Callback when the user clicks on a file in the browser. */
  38005. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  38006. /** Callback when the user double-clicks on a file in the browser. */
  38007. virtual void fileDoubleClicked (const File& file) = 0;
  38008. };
  38009. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38010. /********* End of inlined file: juce_FileBrowserListener.h *********/
  38011. /**
  38012. A base class for components that display a list of the files in a directory.
  38013. @see DirectoryContentsList
  38014. */
  38015. class JUCE_API DirectoryContentsDisplayComponent
  38016. {
  38017. public:
  38018. /**
  38019. */
  38020. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  38021. /** Destructor. */
  38022. virtual ~DirectoryContentsDisplayComponent();
  38023. /** Returns the file that the user has currently selected.
  38024. Returns File::nonexistent if none is selected.
  38025. */
  38026. virtual const File getSelectedFile() const = 0;
  38027. /** Scrolls this view to the top. */
  38028. virtual void scrollToTop() = 0;
  38029. /** Adds a listener to be told when files are selected or clicked.
  38030. @see removeListener
  38031. */
  38032. void addListener (FileBrowserListener* const listener) throw();
  38033. /** Removes a listener.
  38034. @see addListener
  38035. */
  38036. void removeListener (FileBrowserListener* const listener) throw();
  38037. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38038. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38039. methods.
  38040. Note that you can also use the constants from TextEditor::ColourIds to change the
  38041. colour of the text editor that is opened when a label is editable.
  38042. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38043. */
  38044. enum ColourIds
  38045. {
  38046. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  38047. textColourId = 0x1000541, /**< The colour for the text. */
  38048. };
  38049. /** @internal */
  38050. void sendSelectionChangeMessage();
  38051. /** @internal */
  38052. void sendDoubleClickMessage (const File& file);
  38053. /** @internal */
  38054. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  38055. juce_UseDebuggingNewOperator
  38056. protected:
  38057. DirectoryContentsList& fileList;
  38058. SortedSet <void*> listeners;
  38059. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  38060. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  38061. };
  38062. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38063. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  38064. #endif
  38065. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38066. #endif
  38067. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38068. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  38069. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38070. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38071. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  38072. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38073. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38074. /**
  38075. Base class for components that live inside a file chooser dialog box and
  38076. show previews of the files that get selected.
  38077. One of these allows special extra information to be displayed for files
  38078. in a dialog box as the user selects them. Each time the current file or
  38079. directory is changed, the selectedFileChanged() method will be called
  38080. to allow it to update itself appropriately.
  38081. @see FileChooser, ImagePreviewComponent
  38082. */
  38083. class JUCE_API FilePreviewComponent : public Component
  38084. {
  38085. public:
  38086. /** Creates a FilePreviewComponent. */
  38087. FilePreviewComponent();
  38088. /** Destructor. */
  38089. ~FilePreviewComponent();
  38090. /** Called to indicate that the user's currently selected file has changed.
  38091. @param newSelectedFile the newly selected file or directory, which may be
  38092. File::nonexistent if none is selected.
  38093. */
  38094. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  38095. juce_UseDebuggingNewOperator
  38096. private:
  38097. FilePreviewComponent (const FilePreviewComponent&);
  38098. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  38099. };
  38100. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38101. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  38102. /**
  38103. A component for browsing and selecting a file or directory to open or save.
  38104. This contains a FileListComponent and adds various boxes and controls for
  38105. navigating and selecting a file. It can work in different modes so that it can
  38106. be used for loading or saving a file, or for choosing a directory.
  38107. @see FileChooserDialogBox, FileChooser, FileListComponent
  38108. */
  38109. class JUCE_API FileBrowserComponent : public Component,
  38110. public ChangeBroadcaster,
  38111. private FileBrowserListener,
  38112. private TextEditorListener,
  38113. private ButtonListener,
  38114. private ComboBoxListener
  38115. {
  38116. public:
  38117. /** Various modes that the browser can be used in.
  38118. One of these is passed into the constructor.
  38119. */
  38120. enum FileChooserMode
  38121. {
  38122. loadFileMode, /**< the component should allow the user to choose an existing
  38123. file with the intention of opening it. */
  38124. saveFileMode, /**< the component should allow the user to specify the name of
  38125. a file that will be used to save something. */
  38126. chooseDirectoryMode /**< the component should allow the user to select an existing
  38127. directory. */
  38128. };
  38129. /** Creates a FileBrowserComponent.
  38130. @param browserMode The intended purpose for the browser - see the
  38131. FileChooserMode enum for the various options
  38132. @param initialFileOrDirectory The file or directory that should be selected when
  38133. the component begins. If this is File::nonexistent,
  38134. a default directory will be chosen.
  38135. @param fileFilter an optional filter to use to determine which files
  38136. are shown. If this is 0 then all files are displayed. Note
  38137. that a pointer is kept internally to this object, so
  38138. make sure that it is not deleted before the browser object
  38139. is deleted.
  38140. @param previewComp an optional preview component that will be used to
  38141. show previews of files that the user selects
  38142. @param useTreeView if this is false, the files are shown in a list; if true,
  38143. they are shown in a treeview
  38144. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  38145. text into the filename box.
  38146. */
  38147. FileBrowserComponent (FileChooserMode browserMode,
  38148. const File& initialFileOrDirectory,
  38149. const FileFilter* fileFilter,
  38150. FilePreviewComponent* previewComp,
  38151. const bool useTreeView = false,
  38152. const bool filenameTextBoxIsReadOnly = false);
  38153. /** Destructor. */
  38154. ~FileBrowserComponent();
  38155. /** Returns the file that the user has currently chosen.
  38156. @see getHighlightedFile
  38157. */
  38158. const File getCurrentFile() const throw();
  38159. /** Returns true if the current file is usable.
  38160. This can be used to decide whether the user can press "ok" for the
  38161. current file. What it does depends on the mode, so for example in an "open"
  38162. mode, the current file is only valid if one has been selected and if the file
  38163. exists. In a "save" mode, a non-existent file would also be valid.
  38164. */
  38165. bool currentFileIsValid() const;
  38166. /** This returns the item in the view that is currently highlighted.
  38167. This may be different from getCurrentFile(), which returns the value
  38168. that is shown in the filename box.
  38169. @see getCurrentFile
  38170. */
  38171. const File getHighlightedFile() const throw();
  38172. /** Returns the directory whose contents are currently being shown in the listbox. */
  38173. const File getRoot() const;
  38174. /** Changes the directory that's being shown in the listbox. */
  38175. void setRoot (const File& newRootDirectory);
  38176. /** Equivalent to pressing the "up" button to browse the parent directory. */
  38177. void goUp();
  38178. /** Refreshes the directory that's currently being listed. */
  38179. void refresh();
  38180. /** Returns the browser's current mode. */
  38181. FileChooserMode getMode() const throw() { return mode; }
  38182. /** Returns a verb to describe what should happen when the file is accepted.
  38183. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  38184. mode, it'll be "Save", etc.
  38185. */
  38186. virtual const String getActionVerb() const;
  38187. /** Adds a listener to be told when the user selects and clicks on files.
  38188. @see removeListener
  38189. */
  38190. void addListener (FileBrowserListener* const listener) throw();
  38191. /** Removes a listener.
  38192. @see addListener
  38193. */
  38194. void removeListener (FileBrowserListener* const listener) throw();
  38195. /** @internal */
  38196. void resized();
  38197. /** @internal */
  38198. void buttonClicked (Button* b);
  38199. /** @internal */
  38200. void comboBoxChanged (ComboBox*);
  38201. /** @internal */
  38202. void textEditorTextChanged (TextEditor& editor);
  38203. /** @internal */
  38204. void textEditorReturnKeyPressed (TextEditor& editor);
  38205. /** @internal */
  38206. void textEditorEscapeKeyPressed (TextEditor& editor);
  38207. /** @internal */
  38208. void textEditorFocusLost (TextEditor& editor);
  38209. /** @internal */
  38210. bool keyPressed (const KeyPress& key);
  38211. /** @internal */
  38212. void selectionChanged();
  38213. /** @internal */
  38214. void fileClicked (const File& f, const MouseEvent& e);
  38215. /** @internal */
  38216. void fileDoubleClicked (const File& f);
  38217. /** @internal */
  38218. FilePreviewComponent* getPreviewComponent() const throw();
  38219. juce_UseDebuggingNewOperator
  38220. protected:
  38221. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  38222. private:
  38223. DirectoryContentsList* fileList;
  38224. FileFilter* directoriesOnlyFilter;
  38225. FileChooserMode mode;
  38226. File currentRoot;
  38227. SortedSet <void*> listeners;
  38228. DirectoryContentsDisplayComponent* fileListComponent;
  38229. FilePreviewComponent* previewComp;
  38230. ComboBox* currentPathBox;
  38231. TextEditor* filenameBox;
  38232. Button* goUpButton;
  38233. TimeSliceThread thread;
  38234. void sendListenerChangeMessage();
  38235. FileBrowserComponent (const FileBrowserComponent&);
  38236. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  38237. };
  38238. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38239. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  38240. #endif
  38241. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38242. #endif
  38243. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  38244. /********* Start of inlined file: juce_FileChooser.h *********/
  38245. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  38246. #define __JUCE_FILECHOOSER_JUCEHEADER__
  38247. /**
  38248. Creates a dialog box to choose a file or directory to load or save.
  38249. To use a FileChooser:
  38250. - create one (as a local stack variable is the neatest way)
  38251. - call one of its browseFor.. methods
  38252. - if this returns true, the user has selected a file, so you can retrieve it
  38253. with the getResult() method.
  38254. e.g. @code
  38255. void loadMooseFile()
  38256. {
  38257. FileChooser myChooser ("Please select the moose you want to load...",
  38258. File::getSpecialLocation (File::userHomeDirectory),
  38259. "*.moose");
  38260. if (myChooser.browseForFileToOpen())
  38261. {
  38262. File mooseFile (myChooser.getResult());
  38263. loadMoose (mooseFile);
  38264. }
  38265. }
  38266. @endcode
  38267. */
  38268. class JUCE_API FileChooser
  38269. {
  38270. public:
  38271. /** Creates a FileChooser.
  38272. After creating one of these, use one of the browseFor... methods to display it.
  38273. @param dialogBoxTitle a text string to display in the dialog box to
  38274. tell the user what's going on
  38275. @param initialFileOrDirectory the file or directory that should be selected when
  38276. the dialog box opens. If this parameter is set to
  38277. File::nonexistent, a sensible default directory
  38278. will be used instead.
  38279. @param filePatternsAllowed a set of file patterns to specify which files can be
  38280. selected - each pattern should be separated by a
  38281. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  38282. empty string means that all files are allowed
  38283. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  38284. possible; if false, then a Juce-based browser dialog
  38285. box will always be used
  38286. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  38287. */
  38288. FileChooser (const String& dialogBoxTitle,
  38289. const File& initialFileOrDirectory = File::nonexistent,
  38290. const String& filePatternsAllowed = String::empty,
  38291. const bool useOSNativeDialogBox = true);
  38292. /** Destructor. */
  38293. ~FileChooser();
  38294. /** Shows a dialog box to choose a file to open.
  38295. This will display the dialog box modally, using an "open file" mode, so that
  38296. it won't allow non-existent files or directories to be chosen.
  38297. @param previewComponent an optional component to display inside the dialog
  38298. box to show special info about the files that the user
  38299. is browsing. The component will not be deleted by this
  38300. object, so the caller must take care of it.
  38301. @returns true if the user selected a file, in which case, use the getResult()
  38302. method to find out what it was. Returns false if they cancelled instead.
  38303. @see browseForFileToSave, browseForDirectory
  38304. */
  38305. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  38306. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  38307. The files that are returned can be obtained by calling getResults(). See
  38308. browseForFileToOpen() for more info about the behaviour of this method.
  38309. */
  38310. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  38311. /** Shows a dialog box to choose a file to save.
  38312. This will display the dialog box modally, using an "save file" mode, so it
  38313. will allow non-existent files to be chosen, but not directories.
  38314. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  38315. the user if they're sure they want to overwrite a file that already
  38316. exists
  38317. @returns true if the user chose a file and pressed 'ok', in which case, use
  38318. the getResult() method to find out what the file was. Returns false
  38319. if they cancelled instead.
  38320. @see browseForFileToOpen, browseForDirectory
  38321. */
  38322. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  38323. /** Shows a dialog box to choose a directory.
  38324. This will display the dialog box modally, using an "open directory" mode, so it
  38325. will only allow directories to be returned, not files.
  38326. @returns true if the user chose a directory and pressed 'ok', in which case, use
  38327. the getResult() method to find out what they chose. Returns false
  38328. if they cancelled instead.
  38329. @see browseForFileToOpen, browseForFileToSave
  38330. */
  38331. bool browseForDirectory();
  38332. /** Returns the last file that was chosen by one of the browseFor methods.
  38333. After calling the appropriate browseFor... method, this method lets you
  38334. find out what file or directory they chose.
  38335. Note that the file returned is only valid if the browse method returned true (i.e.
  38336. if the user pressed 'ok' rather than cancelling).
  38337. If you're using a multiple-file select, then use the getResults() method instead,
  38338. to obtain the list of all files chosen.
  38339. @see getResults
  38340. */
  38341. const File getResult() const;
  38342. /** Returns a list of all the files that were chosen during the last call to a
  38343. browse method.
  38344. This array may be empty if no files were chosen, or can contain multiple entries
  38345. if multiple files were chosen.
  38346. @see getResult
  38347. */
  38348. const OwnedArray <File>& getResults() const;
  38349. juce_UseDebuggingNewOperator
  38350. private:
  38351. String title, filters;
  38352. File startingFile;
  38353. OwnedArray <File> results;
  38354. bool useNativeDialogBox;
  38355. bool showDialog (const bool isDirectory,
  38356. const bool isSave,
  38357. const bool warnAboutOverwritingExistingFiles,
  38358. const bool selectMultipleFiles,
  38359. FilePreviewComponent* const previewComponent);
  38360. static void showPlatformDialog (OwnedArray<File>& results,
  38361. const String& title,
  38362. const File& file,
  38363. const String& filters,
  38364. bool isDirectory,
  38365. bool isSave,
  38366. bool warnAboutOverwritingExistingFiles,
  38367. bool selectMultipleFiles,
  38368. FilePreviewComponent* previewComponent);
  38369. };
  38370. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  38371. /********* End of inlined file: juce_FileChooser.h *********/
  38372. #endif
  38373. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  38374. #endif
  38375. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38376. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  38377. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38378. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38379. /**
  38380. A file open/save dialog box.
  38381. This is a Juce-based file dialog box; to use a native file chooser, see the
  38382. FileChooser class.
  38383. To use one of these, create it and call its show() method. e.g.
  38384. @code
  38385. {
  38386. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  38387. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  38388. File::nonexistent,
  38389. &wildcardFilter,
  38390. 0);
  38391. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  38392. T("Please choose some kind of file that you want to open..."),
  38393. browser,
  38394. getLookAndFeel().alertWindowBackground);
  38395. if (dialogBox.show())
  38396. {
  38397. File selectedFile = browser.getCurrentFile();
  38398. ...
  38399. }
  38400. }
  38401. @endcode
  38402. @see FileChooser
  38403. */
  38404. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  38405. public ButtonListener,
  38406. public FileBrowserListener
  38407. {
  38408. public:
  38409. /** Creates a file chooser box.
  38410. @param title the main title to show at the top of the box
  38411. @param instructions an optional longer piece of text to show below the title in
  38412. a smaller font, describing in more detail what's required.
  38413. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  38414. box. Make sure you delete this after (but not before!) the
  38415. dialog box has been deleted.
  38416. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  38417. if they try to select a file that already exists. (This
  38418. flag is only used when saving files)
  38419. @param backgroundColour the background colour for the top level window
  38420. @see FileBrowserComponent, FilePreviewComponent
  38421. */
  38422. FileChooserDialogBox (const String& title,
  38423. const String& instructions,
  38424. FileBrowserComponent& browserComponent,
  38425. const bool warnAboutOverwritingExistingFiles,
  38426. const Colour& backgroundColour);
  38427. /** Destructor. */
  38428. ~FileChooserDialogBox();
  38429. /** Displays and runs the dialog box modally.
  38430. This will show the box with the specified size, returning true if the user
  38431. pressed 'ok', or false if they cancelled.
  38432. Leave the width or height as 0 to use the default size
  38433. */
  38434. bool show (int width = 0,int height = 0);
  38435. /** @internal */
  38436. void buttonClicked (Button* button);
  38437. /** @internal */
  38438. void closeButtonPressed();
  38439. /** @internal */
  38440. void selectionChanged();
  38441. /** @internal */
  38442. void fileClicked (const File& file, const MouseEvent& e);
  38443. /** @internal */
  38444. void fileDoubleClicked (const File& file);
  38445. juce_UseDebuggingNewOperator
  38446. private:
  38447. class ContentComponent : public Component
  38448. {
  38449. public:
  38450. ContentComponent();
  38451. ~ContentComponent();
  38452. void paint (Graphics& g);
  38453. void resized();
  38454. String instructions;
  38455. GlyphArrangement text;
  38456. FileBrowserComponent* chooserComponent;
  38457. FilePreviewComponent* previewComponent;
  38458. TextButton* okButton;
  38459. TextButton* cancelButton;
  38460. };
  38461. ContentComponent* content;
  38462. const bool warnAboutOverwritingExistingFiles;
  38463. FileChooserDialogBox (const FileChooserDialogBox&);
  38464. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  38465. };
  38466. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38467. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  38468. #endif
  38469. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38470. /********* Start of inlined file: juce_FileListComponent.h *********/
  38471. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38472. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38473. /**
  38474. A component that displays the files in a directory as a listbox.
  38475. This implements the DirectoryContentsDisplayComponent base class so that
  38476. it can be used in a FileBrowserComponent.
  38477. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38478. class and the FileBrowserListener class.
  38479. @see DirectoryContentsList, FileTreeComponent
  38480. */
  38481. class JUCE_API FileListComponent : public ListBox,
  38482. public DirectoryContentsDisplayComponent,
  38483. private ListBoxModel,
  38484. private ChangeListener
  38485. {
  38486. public:
  38487. /** Creates a listbox to show the contents of a specified directory.
  38488. */
  38489. FileListComponent (DirectoryContentsList& listToShow);
  38490. /** Destructor. */
  38491. ~FileListComponent();
  38492. /** Returns the file that the user has currently selected.
  38493. Returns File::nonexistent if none is selected.
  38494. */
  38495. const File getSelectedFile() const;
  38496. /** Scrolls to the top of the list. */
  38497. void scrollToTop();
  38498. /** @internal */
  38499. void changeListenerCallback (void*);
  38500. /** @internal */
  38501. int getNumRows();
  38502. /** @internal */
  38503. void paintListBoxItem (int, Graphics&, int, int, bool);
  38504. /** @internal */
  38505. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  38506. /** @internal */
  38507. void selectedRowsChanged (int lastRowSelected);
  38508. /** @internal */
  38509. void deleteKeyPressed (int currentSelectedRow);
  38510. /** @internal */
  38511. void returnKeyPressed (int currentSelectedRow);
  38512. juce_UseDebuggingNewOperator
  38513. private:
  38514. FileListComponent (const FileListComponent&);
  38515. const FileListComponent& operator= (const FileListComponent&);
  38516. File lastDirectory;
  38517. };
  38518. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38519. /********* End of inlined file: juce_FileListComponent.h *********/
  38520. #endif
  38521. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38522. #endif
  38523. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38524. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  38525. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38526. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38527. /**
  38528. A component that displays the files in a directory as a treeview.
  38529. This implements the DirectoryContentsDisplayComponent base class so that
  38530. it can be used in a FileBrowserComponent.
  38531. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38532. class and the FileBrowserListener class.
  38533. @see DirectoryContentsList, FileListComponent
  38534. */
  38535. class JUCE_API FileTreeComponent : public TreeView,
  38536. public DirectoryContentsDisplayComponent
  38537. {
  38538. public:
  38539. /** Creates a listbox to show the contents of a specified directory.
  38540. */
  38541. FileTreeComponent (DirectoryContentsList& listToShow);
  38542. /** Destructor. */
  38543. ~FileTreeComponent();
  38544. /** Returns the number of selected files in the tree.
  38545. */
  38546. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  38547. /** Returns one of the files that the user has currently selected.
  38548. Returns File::nonexistent if none is selected.
  38549. */
  38550. const File getSelectedFile (int index) const throw();
  38551. /** Returns the first of the files that the user has currently selected.
  38552. Returns File::nonexistent if none is selected.
  38553. */
  38554. const File getSelectedFile() const;
  38555. /** Scrolls the list to the top. */
  38556. void scrollToTop();
  38557. /** Setting a name for this allows tree items to be dragged.
  38558. The string that you pass in here will be returned by the getDragSourceDescription()
  38559. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38560. */
  38561. void setDragAndDropDescription (const String& description) throw();
  38562. /** Returns the last value that was set by setDragAndDropDescription().
  38563. */
  38564. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38565. juce_UseDebuggingNewOperator
  38566. private:
  38567. String dragAndDropDescription;
  38568. FileTreeComponent (const FileTreeComponent&);
  38569. const FileTreeComponent& operator= (const FileTreeComponent&);
  38570. };
  38571. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38572. /********* End of inlined file: juce_FileTreeComponent.h *********/
  38573. #endif
  38574. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38575. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  38576. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38577. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38578. /**
  38579. Shows a set of file paths in a list, allowing them to be added, removed or
  38580. re-ordered.
  38581. @see FileSearchPath
  38582. */
  38583. class JUCE_API FileSearchPathListComponent : public Component,
  38584. public SettableTooltipClient,
  38585. public FileDragAndDropTarget,
  38586. private ButtonListener,
  38587. private ListBoxModel
  38588. {
  38589. public:
  38590. /** Creates an empty FileSearchPathListComponent.
  38591. */
  38592. FileSearchPathListComponent();
  38593. /** Destructor. */
  38594. ~FileSearchPathListComponent();
  38595. /** Returns the path as it is currently shown. */
  38596. const FileSearchPath& getPath() const throw() { return path; }
  38597. /** Changes the current path. */
  38598. void setPath (const FileSearchPath& newPath);
  38599. /** Sets a file or directory to be the default starting point for the browser to show.
  38600. This is only used if the current file hasn't been set.
  38601. */
  38602. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  38603. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38604. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38605. methods.
  38606. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38607. */
  38608. enum ColourIds
  38609. {
  38610. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  38611. Make this transparent if you don't want the background to be filled. */
  38612. };
  38613. /** @internal */
  38614. int getNumRows();
  38615. /** @internal */
  38616. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  38617. /** @internal */
  38618. void deleteKeyPressed (int lastRowSelected);
  38619. /** @internal */
  38620. void returnKeyPressed (int lastRowSelected);
  38621. /** @internal */
  38622. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  38623. /** @internal */
  38624. void selectedRowsChanged (int lastRowSelected);
  38625. /** @internal */
  38626. void resized();
  38627. /** @internal */
  38628. void paint (Graphics& g);
  38629. /** @internal */
  38630. bool isInterestedInFileDrag (const StringArray& files);
  38631. /** @internal */
  38632. void filesDropped (const StringArray& files, int, int);
  38633. /** @internal */
  38634. void buttonClicked (Button* button);
  38635. juce_UseDebuggingNewOperator
  38636. private:
  38637. FileSearchPath path;
  38638. File defaultBrowseTarget;
  38639. ListBox* listBox;
  38640. Button* addButton;
  38641. Button* removeButton;
  38642. Button* changeButton;
  38643. Button* upButton;
  38644. Button* downButton;
  38645. void changed() throw();
  38646. void updateButtons() throw();
  38647. FileSearchPathListComponent (const FileSearchPathListComponent&);
  38648. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  38649. };
  38650. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38651. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  38652. #endif
  38653. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38654. /********* Start of inlined file: juce_FilenameComponent.h *********/
  38655. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38656. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38657. class FilenameComponent;
  38658. /**
  38659. Listens for events happening to a FilenameComponent.
  38660. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  38661. register one of these objects for event callbacks when the filename is changed.
  38662. @see FilenameComponent
  38663. */
  38664. class JUCE_API FilenameComponentListener
  38665. {
  38666. public:
  38667. /** Destructor. */
  38668. virtual ~FilenameComponentListener() {}
  38669. /** This method is called after the FilenameComponent's file has been changed. */
  38670. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  38671. };
  38672. /**
  38673. Shows a filename as an editable text box, with a 'browse' button and a
  38674. drop-down list for recently selected files.
  38675. A handy component for dialogue boxes where you want the user to be able to
  38676. select a file or directory.
  38677. Attach an FilenameComponentListener using the addListener() method, and it will
  38678. get called each time the user changes the filename, either by browsing for a file
  38679. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38680. @see FileChooser, ComboBox
  38681. */
  38682. class JUCE_API FilenameComponent : public Component,
  38683. public SettableTooltipClient,
  38684. public FileDragAndDropTarget,
  38685. private AsyncUpdater,
  38686. private ButtonListener,
  38687. private ComboBoxListener
  38688. {
  38689. public:
  38690. /** Creates a FilenameComponent.
  38691. @param name the name for this component.
  38692. @param currentFile the file to initially show in the box
  38693. @param canEditFilename if true, the user can manually edit the filename; if false,
  38694. they can only change it by browsing for a new file
  38695. @param isDirectory if true, the file will be treated as a directory, and
  38696. an appropriate directory browser used
  38697. @param isForSaving if true, the file browser will allow non-existent files to
  38698. be picked, as the file is assumed to be used for saving rather
  38699. than loading
  38700. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38701. If an empty string is passed in, then the pattern is assumed to be "*"
  38702. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38703. to any filenames that are entered or chosen
  38704. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38705. will only appear if the initial file isn't valid)
  38706. */
  38707. FilenameComponent (const String& name,
  38708. const File& currentFile,
  38709. const bool canEditFilename,
  38710. const bool isDirectory,
  38711. const bool isForSaving,
  38712. const String& fileBrowserWildcard,
  38713. const String& enforcedSuffix,
  38714. const String& textWhenNothingSelected);
  38715. /** Destructor. */
  38716. ~FilenameComponent();
  38717. /** Returns the currently displayed filename. */
  38718. const File getCurrentFile() const;
  38719. /** Changes the current filename.
  38720. If addToRecentlyUsedList is true, the filename will also be added to the
  38721. drop-down list of recent files.
  38722. If sendChangeNotification is false, then the listeners won't be told of the
  38723. change.
  38724. */
  38725. void setCurrentFile (File newFile,
  38726. const bool addToRecentlyUsedList,
  38727. const bool sendChangeNotification = true);
  38728. /** Changes whether the use can type into the filename box.
  38729. */
  38730. void setFilenameIsEditable (const bool shouldBeEditable);
  38731. /** Sets a file or directory to be the default starting point for the browser to show.
  38732. This is only used if the current file hasn't been set.
  38733. */
  38734. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  38735. /** Returns all the entries on the recent files list.
  38736. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  38737. state of this list.
  38738. @see setRecentlyUsedFilenames
  38739. */
  38740. const StringArray getRecentlyUsedFilenames() const;
  38741. /** Sets all the entries on the recent files list.
  38742. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  38743. state of this list.
  38744. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  38745. */
  38746. void setRecentlyUsedFilenames (const StringArray& filenames);
  38747. /** Adds an entry to the recently-used files dropdown list.
  38748. If the file is already in the list, it will be moved to the top. A limit
  38749. is also placed on the number of items that are kept in the list.
  38750. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  38751. */
  38752. void addRecentlyUsedFile (const File& file);
  38753. /** Changes the limit for the number of files that will be stored in the recent-file list.
  38754. */
  38755. void setMaxNumberOfRecentFiles (const int newMaximum);
  38756. /** Changes the text shown on the 'browse' button.
  38757. By default this button just says "..." but you can change it. The button itself
  38758. can be changed using the look-and-feel classes, so it might not actually have any
  38759. text on it.
  38760. */
  38761. void setBrowseButtonText (const String& browseButtonText);
  38762. /** Adds a listener that will be called when the selected file is changed. */
  38763. void addListener (FilenameComponentListener* const listener) throw();
  38764. /** Removes a previously-registered listener. */
  38765. void removeListener (FilenameComponentListener* const listener) throw();
  38766. /** Gives the component a tooltip. */
  38767. void setTooltip (const String& newTooltip);
  38768. /** @internal */
  38769. void paintOverChildren (Graphics& g);
  38770. /** @internal */
  38771. void resized();
  38772. /** @internal */
  38773. void lookAndFeelChanged();
  38774. /** @internal */
  38775. bool isInterestedInFileDrag (const StringArray& files);
  38776. /** @internal */
  38777. void filesDropped (const StringArray& files, int, int);
  38778. /** @internal */
  38779. void fileDragEnter (const StringArray& files, int, int);
  38780. /** @internal */
  38781. void fileDragExit (const StringArray& files);
  38782. juce_UseDebuggingNewOperator
  38783. private:
  38784. ComboBox* filenameBox;
  38785. String lastFilename;
  38786. Button* browseButton;
  38787. int maxRecentFiles;
  38788. bool isDir, isSaving, isFileDragOver;
  38789. String wildcard, enforcedSuffix, browseButtonText;
  38790. SortedSet <void*> listeners;
  38791. File defaultBrowseFile;
  38792. void comboBoxChanged (ComboBox*);
  38793. void buttonClicked (Button* button);
  38794. void handleAsyncUpdate();
  38795. FilenameComponent (const FilenameComponent&);
  38796. const FilenameComponent& operator= (const FilenameComponent&);
  38797. };
  38798. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38799. /********* End of inlined file: juce_FilenameComponent.h *********/
  38800. #endif
  38801. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38802. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  38803. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38804. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38805. /**
  38806. A type of FileFilter that works by wildcard pattern matching.
  38807. This filter only allows files that match one of the specified patterns, but
  38808. allows all directories through.
  38809. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38810. */
  38811. class JUCE_API WildcardFileFilter : public FileFilter
  38812. {
  38813. public:
  38814. /**
  38815. Creates a wildcard filter for one or more patterns.
  38816. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38817. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38818. or .aiff.
  38819. The description is a name to show the user in a list of possible patterns, so
  38820. for the wav/aiff example, your description might be "audio files".
  38821. */
  38822. WildcardFileFilter (const String& wildcardPatterns,
  38823. const String& description);
  38824. /** Destructor. */
  38825. ~WildcardFileFilter();
  38826. /** Returns true if the filename matches one of the patterns specified. */
  38827. bool isFileSuitable (const File& file) const;
  38828. /** This always returns true. */
  38829. bool isDirectorySuitable (const File& file) const;
  38830. juce_UseDebuggingNewOperator
  38831. private:
  38832. StringArray wildcards;
  38833. };
  38834. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38835. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  38836. #endif
  38837. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38838. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  38839. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38840. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38841. /**
  38842. A simple preview component that shows thumbnails of image files.
  38843. @see FileChooserDialogBox, FilePreviewComponent
  38844. */
  38845. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  38846. private Timer
  38847. {
  38848. public:
  38849. /** Creates an ImagePreviewComponent. */
  38850. ImagePreviewComponent();
  38851. /** Destructor. */
  38852. ~ImagePreviewComponent();
  38853. /** @internal */
  38854. void selectedFileChanged (const File& newSelectedFile);
  38855. /** @internal */
  38856. void paint (Graphics& g);
  38857. /** @internal */
  38858. void timerCallback();
  38859. juce_UseDebuggingNewOperator
  38860. private:
  38861. File fileToLoad;
  38862. Image* currentThumbnail;
  38863. String currentDetails;
  38864. void getThumbSize (int& w, int& h) const;
  38865. ImagePreviewComponent (const ImagePreviewComponent&);
  38866. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  38867. };
  38868. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38869. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  38870. #endif
  38871. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  38872. /********* Start of inlined file: juce_AlertWindow.h *********/
  38873. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  38874. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  38875. /** A window that displays a message and has buttons for the user to react to it.
  38876. For simple dialog boxes with just a couple of buttons on them, there are
  38877. some static methods for running these.
  38878. For more complex dialogs, an AlertWindow can be created, then it can have some
  38879. buttons and components added to it, and its runModalLoop() method is then used to
  38880. show it. The value returned by runModalLoop() shows which button the
  38881. user pressed to dismiss the box.
  38882. @see ThreadWithProgressWindow
  38883. */
  38884. class JUCE_API AlertWindow : public TopLevelWindow,
  38885. private ButtonListener
  38886. {
  38887. public:
  38888. /** The type of icon to show in the dialog box. */
  38889. enum AlertIconType
  38890. {
  38891. NoIcon, /**< No icon will be shown on the dialog box. */
  38892. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  38893. user to answer a question. */
  38894. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  38895. warning about something and shouldn't be ignored. */
  38896. InfoIcon /**< An icon that indicates that the dialog box is just
  38897. giving the user some information, which doesn't require
  38898. a response from them. */
  38899. };
  38900. /** Creates an AlertWindow.
  38901. @param title the headline to show at the top of the dialog box
  38902. @param message a longer, more descriptive message to show underneath the
  38903. headline
  38904. @param iconType the type of icon to display
  38905. @param associatedComponent if this is non-zero, it specifies the component that the
  38906. alert window should be associated with. Depending on the look
  38907. and feel, this might be used for positioning of the alert window.
  38908. */
  38909. AlertWindow (const String& title,
  38910. const String& message,
  38911. AlertIconType iconType,
  38912. Component* associatedComponent = 0);
  38913. /** Destroys the AlertWindow */
  38914. ~AlertWindow();
  38915. /** Returns the type of alert icon that was specified when the window
  38916. was created. */
  38917. AlertIconType getAlertType() const throw() { return alertIconType; }
  38918. /** Changes the dialog box's message.
  38919. This will also resize the window to fit the new message if required.
  38920. */
  38921. void setMessage (const String& message);
  38922. /** Adds a button to the window.
  38923. @param name the text to show on the button
  38924. @param returnValue the value that should be returned from runModalLoop()
  38925. if this is the button that the user presses.
  38926. @param shortcutKey1 an optional key that can be pressed to trigger this button
  38927. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  38928. */
  38929. void addButton (const String& name,
  38930. const int returnValue,
  38931. const KeyPress& shortcutKey1 = KeyPress(),
  38932. const KeyPress& shortcutKey2 = KeyPress());
  38933. /** Returns the number of buttons that the window currently has. */
  38934. int getNumButtons() const;
  38935. /** Adds a textbox to the window for entering strings.
  38936. @param name an internal name for the text-box. This is the name to pass to
  38937. the getTextEditorContents() method to find out what the
  38938. user typed-in.
  38939. @param initialContents a string to show in the text box when it's first shown
  38940. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38941. text-box to label it.
  38942. @param isPasswordBox if true, the text editor will display asterisks instead of
  38943. the actual text
  38944. @see getTextEditorContents
  38945. */
  38946. void addTextEditor (const String& name,
  38947. const String& initialContents,
  38948. const String& onScreenLabel = String::empty,
  38949. const bool isPasswordBox = false);
  38950. /** Returns the contents of a named textbox.
  38951. After showing an AlertWindow that contains a text editor, this can be
  38952. used to find out what the user has typed into it.
  38953. @param nameOfTextEditor the name of the text box that you're interested in
  38954. @see addTextEditor
  38955. */
  38956. const String getTextEditorContents (const String& nameOfTextEditor) const;
  38957. /** Adds a drop-down list of choices to the box.
  38958. After the box has been shown, the getComboBoxComponent() method can
  38959. be used to find out which item the user picked.
  38960. @param name the label to use for the drop-down list
  38961. @param items the list of items to show in it
  38962. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38963. combo-box to label it.
  38964. @see getComboBoxComponent
  38965. */
  38966. void addComboBox (const String& name,
  38967. const StringArray& items,
  38968. const String& onScreenLabel = String::empty);
  38969. /** Returns a drop-down list that was added to the AlertWindow.
  38970. @param nameOfList the name that was passed into the addComboBox() method
  38971. when creating the drop-down
  38972. @returns the ComboBox component, or 0 if none was found for the given name.
  38973. */
  38974. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  38975. /** Adds a block of text.
  38976. This is handy for adding a multi-line note next to a textbox or combo-box,
  38977. to provide more details about what's going on.
  38978. */
  38979. void addTextBlock (const String& text);
  38980. /** Adds a progress-bar to the window.
  38981. @param progressValue a variable that will be repeatedly checked while the
  38982. dialog box is visible, to see how far the process has
  38983. got. The value should be in the range 0 to 1.0
  38984. */
  38985. void addProgressBarComponent (double& progressValue);
  38986. /** Adds a user-defined component to the dialog box.
  38987. @param component the component to add - its size should be set up correctly
  38988. before it is passed in. The caller is responsible for deleting
  38989. the component later on - the AlertWindow won't delete it.
  38990. */
  38991. void addCustomComponent (Component* const component);
  38992. /** Returns the number of custom components in the dialog box.
  38993. @see getCustomComponent, addCustomComponent
  38994. */
  38995. int getNumCustomComponents() const;
  38996. /** Returns one of the custom components in the dialog box.
  38997. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38998. will return 0
  38999. @see getNumCustomComponents, addCustomComponent
  39000. */
  39001. Component* getCustomComponent (const int index) const;
  39002. /** Removes one of the custom components in the dialog box.
  39003. Note that this won't delete it, it just removes the component from the window
  39004. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39005. will return 0
  39006. @returns the component that was removed (or zero)
  39007. @see getNumCustomComponents, addCustomComponent
  39008. */
  39009. Component* removeCustomComponent (const int index);
  39010. /** Returns true if the window contains any components other than just buttons.*/
  39011. bool containsAnyExtraComponents() const;
  39012. // easy-to-use message box functions:
  39013. /** Shows a dialog box that just has a message and a single button to get rid of it.
  39014. The box is shown modally, and the method returns after the user
  39015. has clicked the button (or pressed the escape or return keys).
  39016. @param iconType the type of icon to show
  39017. @param title the headline to show at the top of the box
  39018. @param message a longer, more descriptive message to show underneath the
  39019. headline
  39020. @param buttonText the text to show in the button - if this string is empty, the
  39021. default string "ok" (or a localised version) will be used.
  39022. @param associatedComponent if this is non-zero, it specifies the component that the
  39023. alert window should be associated with. Depending on the look
  39024. and feel, this might be used for positioning of the alert window.
  39025. */
  39026. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  39027. const String& title,
  39028. const String& message,
  39029. const String& buttonText = String::empty,
  39030. Component* associatedComponent = 0);
  39031. /** Shows a dialog box with two buttons.
  39032. Ideal for ok/cancel or yes/no choices. The return key can also be used
  39033. to trigger the first button, and the escape key for the second button.
  39034. @param iconType the type of icon to show
  39035. @param title the headline to show at the top of the box
  39036. @param message a longer, more descriptive message to show underneath the
  39037. headline
  39038. @param button1Text the text to show in the first button - if this string is
  39039. empty, the default string "ok" (or a localised version of it)
  39040. will be used.
  39041. @param button2Text the text to show in the second button - if this string is
  39042. empty, the default string "cancel" (or a localised version of it)
  39043. will be used.
  39044. @param associatedComponent if this is non-zero, it specifies the component that the
  39045. alert window should be associated with. Depending on the look
  39046. and feel, this might be used for positioning of the alert window.
  39047. @returns true if button 1 was clicked, false if it was button 2
  39048. */
  39049. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  39050. const String& title,
  39051. const String& message,
  39052. const String& button1Text = String::empty,
  39053. const String& button2Text = String::empty,
  39054. Component* associatedComponent = 0);
  39055. /** Shows a dialog box with three buttons.
  39056. Ideal for yes/no/cancel boxes.
  39057. The escape key can be used to trigger the third button.
  39058. @param iconType the type of icon to show
  39059. @param title the headline to show at the top of the box
  39060. @param message a longer, more descriptive message to show underneath the
  39061. headline
  39062. @param button1Text the text to show in the first button - if an empty string, then
  39063. "yes" will be used (or a localised version of it)
  39064. @param button2Text the text to show in the first button - if an empty string, then
  39065. "no" will be used (or a localised version of it)
  39066. @param button3Text the text to show in the first button - if an empty string, then
  39067. "cancel" will be used (or a localised version of it)
  39068. @param associatedComponent if this is non-zero, it specifies the component that the
  39069. alert window should be associated with. Depending on the look
  39070. and feel, this might be used for positioning of the alert window.
  39071. @returns one of the following values:
  39072. - 0 if the third button was pressed (normally used for 'cancel')
  39073. - 1 if the first button was pressed (normally used for 'yes')
  39074. - 2 if the middle button was pressed (normally used for 'no')
  39075. */
  39076. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  39077. const String& title,
  39078. const String& message,
  39079. const String& button1Text = String::empty,
  39080. const String& button2Text = String::empty,
  39081. const String& button3Text = String::empty,
  39082. Component* associatedComponent = 0);
  39083. /** Shows an operating-system native dialog box.
  39084. @param title the title to use at the top
  39085. @param bodyText the longer message to show
  39086. @param isOkCancel if true, this will show an ok/cancel box, if false,
  39087. it'll show a box with just an ok button
  39088. @returns true if the ok button was pressed, false if they pressed cancel.
  39089. */
  39090. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  39091. const String& bodyText,
  39092. bool isOkCancel);
  39093. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  39094. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39095. methods.
  39096. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39097. */
  39098. enum ColourIds
  39099. {
  39100. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  39101. textColourId = 0x1001810, /**< The colour for the text. */
  39102. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  39103. };
  39104. juce_UseDebuggingNewOperator
  39105. protected:
  39106. /** @internal */
  39107. void paint (Graphics& g);
  39108. /** @internal */
  39109. void mouseDown (const MouseEvent& e);
  39110. /** @internal */
  39111. void mouseDrag (const MouseEvent& e);
  39112. /** @internal */
  39113. bool keyPressed (const KeyPress& key);
  39114. /** @internal */
  39115. void buttonClicked (Button* button);
  39116. /** @internal */
  39117. void lookAndFeelChanged();
  39118. /** @internal */
  39119. void userTriedToCloseWindow();
  39120. /** @internal */
  39121. int getDesktopWindowStyleFlags() const;
  39122. private:
  39123. String text;
  39124. TextLayout textLayout;
  39125. AlertIconType alertIconType;
  39126. ComponentBoundsConstrainer constrainer;
  39127. ComponentDragger dragger;
  39128. Rectangle textArea;
  39129. VoidArray buttons, textBoxes, comboBoxes;
  39130. VoidArray progressBars, customComps, textBlocks, allComps;
  39131. StringArray textboxNames, comboBoxNames;
  39132. Font font;
  39133. Component* associatedComponent;
  39134. void updateLayout (const bool onlyIncreaseSize);
  39135. // disable copy constructor
  39136. AlertWindow (const AlertWindow&);
  39137. const AlertWindow& operator= (const AlertWindow&);
  39138. };
  39139. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  39140. /********* End of inlined file: juce_AlertWindow.h *********/
  39141. #endif
  39142. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  39143. #endif
  39144. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  39145. /********* Start of inlined file: juce_DialogWindow.h *********/
  39146. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  39147. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  39148. /**
  39149. A dialog-box style window.
  39150. This class is a convenient way of creating a DocumentWindow with a close button
  39151. that can be triggered by pressing the escape key.
  39152. Any of the methods available to a DocumentWindow or ResizableWindow are also
  39153. available to this, so it can be made resizable, have a menu bar, etc.
  39154. To add items to the box, see the ResizableWindow::setContentComponent() method.
  39155. Don't add components directly to this class - always put them in a content component!
  39156. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  39157. the user clicking the close button - for more info, see the DocumentWindow
  39158. help.
  39159. @see DocumentWindow, ResizableWindow
  39160. */
  39161. class JUCE_API DialogWindow : public DocumentWindow
  39162. {
  39163. public:
  39164. /** Creates a DialogWindow.
  39165. @param name the name to give the component - this is also
  39166. the title shown at the top of the window. To change
  39167. this later, use setName()
  39168. @param backgroundColour the colour to use for filling the window's background.
  39169. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  39170. close button to be triggered
  39171. @param addToDesktop if true, the window will be automatically added to the
  39172. desktop; if false, you can use it as a child component
  39173. */
  39174. DialogWindow (const String& name,
  39175. const Colour& backgroundColour,
  39176. const bool escapeKeyTriggersCloseButton,
  39177. const bool addToDesktop = true);
  39178. /** Destructor.
  39179. If a content component has been set with setContentComponent(), it
  39180. will be deleted.
  39181. */
  39182. ~DialogWindow();
  39183. /** Easy way of quickly showing a dialog box containing a given component.
  39184. This will open and display a DialogWindow containing a given component, returning
  39185. when the user clicks its close button.
  39186. It returns the value that was returned by the dialog box's runModalLoop() call.
  39187. To close the dialog programatically, you should call exitModalState (returnValue) on
  39188. the DialogWindow that is created. To find a pointer to this window from your
  39189. contentComponent, you can do something like this:
  39190. @code
  39191. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  39192. if (dw != 0)
  39193. dw->exitModalState (1234);
  39194. @endcode
  39195. @param dialogTitle the dialog box's title
  39196. @param contentComponent the content component for the dialog box. Make sure
  39197. that this has been set to the size you want it to
  39198. be before calling this method. The component won't
  39199. be deleted by this call, so you can re-use it or delete
  39200. it afterwards
  39201. @param componentToCentreAround if this is non-zero, it indicates a component that
  39202. you'd like to show this dialog box in front of. See the
  39203. DocumentWindow::centreAroundComponent() method for more
  39204. info on this parameter
  39205. @param backgroundColour a colour to use for the dialog box's background colour
  39206. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  39207. close button to be triggered
  39208. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  39209. a corner resizer
  39210. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  39211. to use a border or corner resizer component. See ResizableWindow::setResizable()
  39212. */
  39213. static int showModalDialog (const String& dialogTitle,
  39214. Component* contentComponent,
  39215. Component* componentToCentreAround,
  39216. const Colour& backgroundColour,
  39217. const bool escapeKeyTriggersCloseButton,
  39218. const bool shouldBeResizable = false,
  39219. const bool useBottomRightCornerResizer = false);
  39220. juce_UseDebuggingNewOperator
  39221. protected:
  39222. /** @internal */
  39223. void resized();
  39224. private:
  39225. bool escapeKeyTriggersCloseButton;
  39226. DialogWindow (const DialogWindow&);
  39227. const DialogWindow& operator= (const DialogWindow&);
  39228. };
  39229. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  39230. /********* End of inlined file: juce_DialogWindow.h *********/
  39231. #endif
  39232. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39233. #endif
  39234. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  39235. #endif
  39236. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  39237. /********* Start of inlined file: juce_SplashScreen.h *********/
  39238. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  39239. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  39240. /** A component for showing a splash screen while your app starts up.
  39241. This will automatically position itself, and delete itself when the app has
  39242. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  39243. this).
  39244. To use it, just create one of these in your JUCEApplication::initialise() method,
  39245. call its show() method and let the object delete itself later.
  39246. E.g. @code
  39247. void MyApp::initialise (const String& commandLine)
  39248. {
  39249. SplashScreen* splash = new SplashScreen();
  39250. splash->show (T("welcome to my app"),
  39251. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  39252. 4000, false);
  39253. .. no need to delete the splash screen - it'll do that itself.
  39254. }
  39255. @endcode
  39256. */
  39257. class JUCE_API SplashScreen : public Component,
  39258. public Timer,
  39259. private DeletedAtShutdown
  39260. {
  39261. public:
  39262. /** Creates a SplashScreen object.
  39263. After creating one of these (or your subclass of it), call one of the show()
  39264. methods to display it.
  39265. */
  39266. SplashScreen();
  39267. /** Destructor. */
  39268. ~SplashScreen();
  39269. /** Creates a SplashScreen object that will display an image.
  39270. As soon as this is called, the SplashScreen will be displayed in the centre of the
  39271. screen. This method will also dispatch any pending messages to make sure that when
  39272. it returns, the splash screen has been completely drawn, and your initialisation
  39273. code can carry on.
  39274. @param title the name to give the component
  39275. @param backgroundImage an image to draw on the component. The component's size
  39276. will be set to the size of this image, and if the image is
  39277. semi-transparent, the component will be made semi-transparent
  39278. too. This image will be deleted (or released from the ImageCache
  39279. if that's how it was created) by the splash screen object when
  39280. it is itself deleted.
  39281. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  39282. should stay visible for. If the initialisation takes longer than
  39283. this time, the splash screen will wait for it to finish before
  39284. disappearing, but if initialisation is very quick, this lets
  39285. you make sure that people get a good look at your splash.
  39286. @param useDropShadow if true, the window will have a drop shadow
  39287. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  39288. the mouse (anywhere)
  39289. */
  39290. void show (const String& title,
  39291. Image* const backgroundImage,
  39292. const int minimumTimeToDisplayFor,
  39293. const bool useDropShadow,
  39294. const bool removeOnMouseClick = true);
  39295. /** Creates a SplashScreen object with a specified size.
  39296. For a custom splash screen, you can use this method to display it at a certain size
  39297. and then override the paint() method yourself to do whatever's necessary.
  39298. As soon as this is called, the SplashScreen will be displayed in the centre of the
  39299. screen. This method will also dispatch any pending messages to make sure that when
  39300. it returns, the splash screen has been completely drawn, and your initialisation
  39301. code can carry on.
  39302. @param title the name to give the component
  39303. @param width the width to use
  39304. @param height the height to use
  39305. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  39306. should stay visible for. If the initialisation takes longer than
  39307. this time, the splash screen will wait for it to finish before
  39308. disappearing, but if initialisation is very quick, this lets
  39309. you make sure that people get a good look at your splash.
  39310. @param useDropShadow if true, the window will have a drop shadow
  39311. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  39312. the mouse (anywhere)
  39313. */
  39314. void show (const String& title,
  39315. const int width,
  39316. const int height,
  39317. const int minimumTimeToDisplayFor,
  39318. const bool useDropShadow,
  39319. const bool removeOnMouseClick = true);
  39320. /** @internal */
  39321. void paint (Graphics& g);
  39322. /** @internal */
  39323. void timerCallback();
  39324. juce_UseDebuggingNewOperator
  39325. private:
  39326. Image* backgroundImage;
  39327. Time earliestTimeToDelete;
  39328. int originalClickCounter;
  39329. bool isImageInCache;
  39330. SplashScreen (const SplashScreen&);
  39331. const SplashScreen& operator= (const SplashScreen&);
  39332. };
  39333. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  39334. /********* End of inlined file: juce_SplashScreen.h *********/
  39335. #endif
  39336. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39337. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  39338. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39339. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39340. /**
  39341. A thread that automatically pops up a modal dialog box with a progress bar
  39342. and cancel button while it's busy running.
  39343. These are handy for performing some sort of task while giving the user feedback
  39344. about how long there is to go, etc.
  39345. E.g. @code
  39346. class MyTask : public ThreadWithProgressWindow
  39347. {
  39348. public:
  39349. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  39350. {
  39351. }
  39352. ~MyTask()
  39353. {
  39354. }
  39355. void run()
  39356. {
  39357. for (int i = 0; i < thingsToDo; ++i)
  39358. {
  39359. // must check this as often as possible, because this is
  39360. // how we know if the user's pressed 'cancel'
  39361. if (threadShouldExit())
  39362. break;
  39363. // this will update the progress bar on the dialog box
  39364. setProgress (i / (double) thingsToDo);
  39365. // ... do the business here...
  39366. }
  39367. }
  39368. };
  39369. void doTheTask()
  39370. {
  39371. MyTask m;
  39372. if (m.runThread())
  39373. {
  39374. // thread finished normally..
  39375. }
  39376. else
  39377. {
  39378. // user pressed the cancel button..
  39379. }
  39380. }
  39381. @endcode
  39382. @see Thread, AlertWindow
  39383. */
  39384. class JUCE_API ThreadWithProgressWindow : public Thread,
  39385. private Timer
  39386. {
  39387. public:
  39388. /** Creates the thread.
  39389. Initially, the dialog box won't be visible, it'll only appear when the
  39390. runThread() method is called.
  39391. @param windowTitle the title to go at the top of the dialog box
  39392. @param hasProgressBar whether the dialog box should have a progress bar (see
  39393. setProgress() )
  39394. @param hasCancelButton whether the dialog box should have a cancel button
  39395. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  39396. the thread to stop before killing it forcibly (see
  39397. Thread::stopThread() )
  39398. @param cancelButtonText the text that should be shown in the cancel button
  39399. (if it has one)
  39400. */
  39401. ThreadWithProgressWindow (const String& windowTitle,
  39402. const bool hasProgressBar,
  39403. const bool hasCancelButton,
  39404. const int timeOutMsWhenCancelling = 10000,
  39405. const String& cancelButtonText = JUCE_T("Cancel"));
  39406. /** Destructor. */
  39407. ~ThreadWithProgressWindow();
  39408. /** Starts the thread and waits for it to finish.
  39409. This will start the thread, make the dialog box appear, and wait until either
  39410. the thread finishes normally, or until the cancel button is pressed.
  39411. Before returning, the dialog box will be hidden.
  39412. @param threadPriority the priority to use when starting the thread - see
  39413. Thread::startThread() for values
  39414. @returns true if the thread finished normally; false if the user pressed cancel
  39415. */
  39416. bool runThread (const int threadPriority = 5);
  39417. /** The thread should call this periodically to update the position of the progress bar.
  39418. @param newProgress the progress, from 0.0 to 1.0
  39419. @see setStatusMessage
  39420. */
  39421. void setProgress (const double newProgress);
  39422. /** The thread can call this to change the message that's displayed in the dialog box.
  39423. */
  39424. void setStatusMessage (const String& newStatusMessage);
  39425. /** Returns the AlertWindow that is being used.
  39426. */
  39427. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  39428. juce_UseDebuggingNewOperator
  39429. private:
  39430. void timerCallback();
  39431. double progress;
  39432. AlertWindow* alertWindow;
  39433. String message;
  39434. CriticalSection messageLock;
  39435. const int timeOutMsWhenCancelling;
  39436. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  39437. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  39438. };
  39439. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39440. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  39441. #endif
  39442. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  39443. #endif
  39444. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  39445. #endif
  39446. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39447. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  39448. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39449. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39450. #if JUCE_WINDOWS || DOXYGEN
  39451. /**
  39452. A Windows-specific class that can create and embed an ActiveX control inside
  39453. itself.
  39454. To use it, create one of these, put it in place and make sure it's visible in a
  39455. window, then use createControl() to instantiate an ActiveX control. The control
  39456. will then be moved and resized to follow the movements of this component.
  39457. Of course, since the control is a heavyweight window, it'll obliterate any
  39458. juce components that may overlap this component, but that's life.
  39459. */
  39460. class JUCE_API ActiveXControlComponent : public Component
  39461. {
  39462. public:
  39463. /** Create an initially-empty container. */
  39464. ActiveXControlComponent();
  39465. /** Destructor. */
  39466. ~ActiveXControlComponent();
  39467. /** Tries to create an ActiveX control and embed it in this peer.
  39468. The peer controlIID is a pointer to an IID structure - it's treated
  39469. as a void* because when including the Juce headers, you might not always
  39470. have included windows.h first, in which case IID wouldn't be defined.
  39471. e.g. @code
  39472. const IID myIID = __uuidof (QTControl);
  39473. myControlComp->createControl (&myIID);
  39474. @endcode
  39475. */
  39476. bool createControl (const void* controlIID);
  39477. /** Deletes the ActiveX control, if one has been created.
  39478. */
  39479. void deleteControl();
  39480. /** Returns true if a control is currently in use. */
  39481. bool isControlOpen() const throw() { return control != 0; }
  39482. /** Does a QueryInterface call on the embedded control object.
  39483. This allows you to cast the control to whatever type of COM object you need.
  39484. The iid parameter is a pointer to an IID structure - it's treated
  39485. as a void* because when including the Juce headers, you might not always
  39486. have included windows.h first, in which case IID wouldn't be defined, but
  39487. you should just pass a pointer to an IID.
  39488. e.g. @code
  39489. const IID iid = __uuidof (IOleWindow);
  39490. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  39491. if (oleWindow != 0)
  39492. {
  39493. HWND hwnd;
  39494. oleWindow->GetWindow (&hwnd);
  39495. ...
  39496. oleWindow->Release();
  39497. }
  39498. @endcode
  39499. */
  39500. void* queryInterface (const void* iid) const;
  39501. /** Set this to false to stop mouse events being allowed through to the control.
  39502. */
  39503. void setMouseEventsAllowed (const bool eventsCanReachControl);
  39504. /** Returns true if mouse events are allowed to get through to the control.
  39505. */
  39506. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  39507. /** @internal */
  39508. void paint (Graphics& g);
  39509. /** @internal */
  39510. void* originalWndProc;
  39511. juce_UseDebuggingNewOperator
  39512. private:
  39513. friend class ActiveXControlData;
  39514. void* control;
  39515. bool mouseEventsAllowed;
  39516. ActiveXControlComponent (const ActiveXControlComponent&);
  39517. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  39518. void setControlBounds (const Rectangle& bounds) const;
  39519. void setControlVisible (const bool b) const;
  39520. };
  39521. #endif
  39522. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39523. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  39524. #endif
  39525. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39526. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39527. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39528. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39529. class MidiInputSelectorComponentListBox;
  39530. /**
  39531. A component containing controls to let the user change the audio settings of
  39532. an AudioDeviceManager object.
  39533. Very easy to use - just create one of these and show it to the user.
  39534. @see AudioDeviceManager
  39535. */
  39536. class JUCE_API AudioDeviceSelectorComponent : public Component,
  39537. public ComboBoxListener,
  39538. public ButtonListener,
  39539. public ChangeListener
  39540. {
  39541. public:
  39542. /** Creates the component.
  39543. If your app needs only output channels, you might ask for a maximum of 0 input
  39544. channels, and the component won't display any options for choosing the input
  39545. channels. And likewise if you're doing an input-only app.
  39546. @param deviceManager the device manager that this component should control
  39547. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  39548. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  39549. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  39550. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  39551. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  39552. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  39553. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  39554. treated as a set of separate mono channels.
  39555. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  39556. are shown, with an "advanced" button that shows the rest of them
  39557. */
  39558. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  39559. const int minAudioInputChannels,
  39560. const int maxAudioInputChannels,
  39561. const int minAudioOutputChannels,
  39562. const int maxAudioOutputChannels,
  39563. const bool showMidiInputOptions,
  39564. const bool showMidiOutputSelector,
  39565. const bool showChannelsAsStereoPairs,
  39566. const bool hideAdvancedOptionsWithButton);
  39567. /** Destructor */
  39568. ~AudioDeviceSelectorComponent();
  39569. /** @internal */
  39570. void resized();
  39571. /** @internal */
  39572. void comboBoxChanged (ComboBox*);
  39573. /** @internal */
  39574. void buttonClicked (Button*);
  39575. /** @internal */
  39576. void changeListenerCallback (void*);
  39577. /** @internal */
  39578. void childBoundsChanged (Component*);
  39579. juce_UseDebuggingNewOperator
  39580. private:
  39581. AudioDeviceManager& deviceManager;
  39582. ComboBox* deviceTypeDropDown;
  39583. Label* deviceTypeDropDownLabel;
  39584. Component* audioDeviceSettingsComp;
  39585. String audioDeviceSettingsCompType;
  39586. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  39587. const bool showChannelsAsStereoPairs;
  39588. const bool hideAdvancedOptionsWithButton;
  39589. MidiInputSelectorComponentListBox* midiInputsList;
  39590. Label* midiInputsLabel;
  39591. ComboBox* midiOutputSelector;
  39592. Label* midiOutputLabel;
  39593. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  39594. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  39595. };
  39596. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39597. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39598. #endif
  39599. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39600. /********* Start of inlined file: juce_BubbleComponent.h *********/
  39601. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39602. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39603. /**
  39604. A component for showing a message or other graphics inside a speech-bubble-shaped
  39605. outline, pointing at a location on the screen.
  39606. This is a base class that just draws and positions the bubble shape, but leaves
  39607. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  39608. that draws a text message.
  39609. To use it, create your subclass, then either add it to a parent component or
  39610. put it on the desktop with addToDesktop (0), use setPosition() to
  39611. resize and position it, then make it visible.
  39612. @see BubbleMessageComponent
  39613. */
  39614. class JUCE_API BubbleComponent : public Component
  39615. {
  39616. protected:
  39617. /** Creates a BubbleComponent.
  39618. Your subclass will need to implement the getContentSize() and paintContent()
  39619. methods to draw the bubble's contents.
  39620. */
  39621. BubbleComponent();
  39622. public:
  39623. /** Destructor. */
  39624. ~BubbleComponent();
  39625. /** A list of permitted placements for the bubble, relative to the co-ordinates
  39626. at which it should be pointing.
  39627. @see setAllowedPlacement
  39628. */
  39629. enum BubblePlacement
  39630. {
  39631. above = 1,
  39632. below = 2,
  39633. left = 4,
  39634. right = 8
  39635. };
  39636. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  39637. point at which it's pointing.
  39638. By default when setPosition() is called, the bubble will place itself either
  39639. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  39640. the values in BubblePlacement to restrict this choice.
  39641. E.g. if you only want your bubble to appear above or below the target area,
  39642. use setAllowedPlacement (above | below);
  39643. @see BubblePlacement
  39644. */
  39645. void setAllowedPlacement (const int newPlacement);
  39646. /** Moves and resizes the bubble to point at a given component.
  39647. This will resize the bubble to fit its content, then find a position for it
  39648. so that it's next to, but doesn't overlap the given component.
  39649. It'll put itself either above, below, or to the side of the component depending
  39650. on where there's the most space, honouring any restrictions that were set
  39651. with setAllowedPlacement().
  39652. */
  39653. void setPosition (Component* componentToPointTo);
  39654. /** Moves and resizes the bubble to point at a given point.
  39655. This will resize the bubble to fit its content, then position it
  39656. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  39657. are relative to either the bubble component's parent component if it has one, or
  39658. they are screen co-ordinates if not.
  39659. It'll put itself either above, below, or to the side of this point, depending
  39660. on where there's the most space, honouring any restrictions that were set
  39661. with setAllowedPlacement().
  39662. */
  39663. void setPosition (const int arrowTipX,
  39664. const int arrowTipY);
  39665. /** Moves and resizes the bubble to point at a given rectangle.
  39666. This will resize the bubble to fit its content, then find a position for it
  39667. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  39668. co-ordinates are relative to either the bubble component's parent component
  39669. if it has one, or they are screen co-ordinates if not.
  39670. It'll put itself either above, below, or to the side of the component depending
  39671. on where there's the most space, honouring any restrictions that were set
  39672. with setAllowedPlacement().
  39673. */
  39674. void setPosition (const Rectangle& rectangleToPointTo);
  39675. protected:
  39676. /** Subclasses should override this to return the size of the content they
  39677. want to draw inside the bubble.
  39678. */
  39679. virtual void getContentSize (int& width, int& height) = 0;
  39680. /** Subclasses should override this to draw their bubble's contents.
  39681. The graphics object's clip region and the dimensions passed in here are
  39682. set up to paint just the rectangle inside the bubble.
  39683. */
  39684. virtual void paintContent (Graphics& g, int width, int height) = 0;
  39685. public:
  39686. /** @internal */
  39687. void paint (Graphics& g);
  39688. juce_UseDebuggingNewOperator
  39689. private:
  39690. Rectangle content;
  39691. int side, allowablePlacements;
  39692. float arrowTipX, arrowTipY;
  39693. DropShadowEffect shadow;
  39694. BubbleComponent (const BubbleComponent&);
  39695. const BubbleComponent& operator= (const BubbleComponent&);
  39696. };
  39697. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39698. /********* End of inlined file: juce_BubbleComponent.h *********/
  39699. #endif
  39700. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39701. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  39702. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39703. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39704. /**
  39705. A speech-bubble component that displays a short message.
  39706. This can be used to show a message with the tail of the speech bubble
  39707. pointing to a particular component or location on the screen.
  39708. @see BubbleComponent
  39709. */
  39710. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  39711. private Timer
  39712. {
  39713. public:
  39714. /** Creates a bubble component.
  39715. After creating one a BubbleComponent, do the following:
  39716. - add it to an appropriate parent component, or put it on the
  39717. desktop with Component::addToDesktop (0).
  39718. - use the showAt() method to show a message.
  39719. - it will make itself invisible after it times-out (and can optionally
  39720. also delete itself), or you can reuse it somewhere else by calling
  39721. showAt() again.
  39722. */
  39723. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  39724. /** Destructor. */
  39725. ~BubbleMessageComponent();
  39726. /** Shows a message bubble at a particular position.
  39727. This shows the bubble with its stem pointing to the given location
  39728. (co-ordinates being relative to its parent component).
  39729. For details about exactly how it decides where to position itself, see
  39730. BubbleComponent::updatePosition().
  39731. @param x the x co-ordinate of end of the bubble's tail
  39732. @param y the y co-ordinate of end of the bubble's tail
  39733. @param message the text to display
  39734. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39735. from its parent compnent. If this is 0 or less, it
  39736. will stay there until manually removed.
  39737. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39738. mouse button is pressed (anywhere on the screen)
  39739. @param deleteSelfAfterUse if true, then the component will delete itself after
  39740. it becomes invisible
  39741. */
  39742. void showAt (int x, int y,
  39743. const String& message,
  39744. const int numMillisecondsBeforeRemoving,
  39745. const bool removeWhenMouseClicked = true,
  39746. const bool deleteSelfAfterUse = false);
  39747. /** Shows a message bubble next to a particular component.
  39748. This shows the bubble with its stem pointing at the given component.
  39749. For details about exactly how it decides where to position itself, see
  39750. BubbleComponent::updatePosition().
  39751. @param component the component that you want to point at
  39752. @param message the text to display
  39753. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39754. from its parent compnent. If this is 0 or less, it
  39755. will stay there until manually removed.
  39756. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39757. mouse button is pressed (anywhere on the screen)
  39758. @param deleteSelfAfterUse if true, then the component will delete itself after
  39759. it becomes invisible
  39760. */
  39761. void showAt (Component* const component,
  39762. const String& message,
  39763. const int numMillisecondsBeforeRemoving,
  39764. const bool removeWhenMouseClicked = true,
  39765. const bool deleteSelfAfterUse = false);
  39766. /** @internal */
  39767. void getContentSize (int& w, int& h);
  39768. /** @internal */
  39769. void paintContent (Graphics& g, int w, int h);
  39770. /** @internal */
  39771. void timerCallback();
  39772. juce_UseDebuggingNewOperator
  39773. private:
  39774. int fadeOutLength, mouseClickCounter;
  39775. TextLayout textLayout;
  39776. int64 expiryTime;
  39777. bool deleteAfterUse;
  39778. void init (const int numMillisecondsBeforeRemoving,
  39779. const bool removeWhenMouseClicked,
  39780. const bool deleteSelfAfterUse);
  39781. BubbleMessageComponent (const BubbleMessageComponent&);
  39782. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  39783. };
  39784. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39785. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  39786. #endif
  39787. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39788. /********* Start of inlined file: juce_ColourSelector.h *********/
  39789. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39790. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  39791. /**
  39792. A component that lets the user choose a colour.
  39793. This shows RGB sliders and a colourspace that the user can pick colours from.
  39794. This class is also a ChangeBroadcaster, so listeners can register to be told
  39795. when the colour changes.
  39796. */
  39797. class JUCE_API ColourSelector : public Component,
  39798. public ChangeBroadcaster,
  39799. protected SliderListener
  39800. {
  39801. public:
  39802. /** Options for the type of selector to show. These are passed into the constructor. */
  39803. enum ColourSelectorOptions
  39804. {
  39805. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  39806. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  39807. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  39808. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  39809. };
  39810. /** Creates a ColourSelector object.
  39811. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  39812. which of the selector's features should be visible.
  39813. The edgeGap value specifies the amount of space to leave around the edge.
  39814. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  39815. colourspace and hue selector components.
  39816. */
  39817. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  39818. const int edgeGap = 4,
  39819. const int gapAroundColourSpaceComponent = 7);
  39820. /** Destructor. */
  39821. ~ColourSelector();
  39822. /** Returns the colour that the user has currently selected.
  39823. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  39824. register to be told when the colour changes.
  39825. @see setCurrentColour
  39826. */
  39827. const Colour getCurrentColour() const;
  39828. /** Changes the colour that is currently being shown.
  39829. */
  39830. void setCurrentColour (const Colour& newColour);
  39831. /** Tells the selector how many preset colour swatches you want to have on the component.
  39832. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39833. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39834. their values.
  39835. */
  39836. virtual int getNumSwatches() const;
  39837. /** Called by the selector to find out the colour of one of the swatches.
  39838. Your subclass should return the colour of the swatch with the given index.
  39839. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39840. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39841. their values.
  39842. */
  39843. virtual const Colour getSwatchColour (const int index) const;
  39844. /** Called by the selector when the user puts a new colour into one of the swatches.
  39845. Your subclass should change the colour of the swatch with the given index.
  39846. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39847. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39848. their values.
  39849. */
  39850. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  39851. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39852. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39853. methods.
  39854. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39855. */
  39856. enum ColourIds
  39857. {
  39858. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  39859. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  39860. };
  39861. juce_UseDebuggingNewOperator
  39862. private:
  39863. friend class ColourSpaceView;
  39864. friend class HueSelectorComp;
  39865. Colour colour;
  39866. float h, s, v;
  39867. Slider* sliders[4];
  39868. Component* colourSpace;
  39869. Component* hueSelector;
  39870. VoidArray swatchComponents;
  39871. const int flags;
  39872. int topSpace, edgeGap;
  39873. void setHue (float newH);
  39874. void setSV (float newS, float newV);
  39875. void updateHSV();
  39876. void update();
  39877. void sliderValueChanged (Slider*);
  39878. void paint (Graphics& g);
  39879. void resized();
  39880. ColourSelector (const ColourSelector&);
  39881. const ColourSelector& operator= (const ColourSelector&);
  39882. // this constructor is here temporarily to prevent old code compiling, because the parameters
  39883. // have changed - if you get an error here, update your code to use the new constructor instead..
  39884. // (xxx - note to self: remember to remove this at some point in the future)
  39885. ColourSelector (const bool);
  39886. };
  39887. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  39888. /********* End of inlined file: juce_ColourSelector.h *********/
  39889. #endif
  39890. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39891. #endif
  39892. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39893. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  39894. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39895. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39896. /**
  39897. A component that contains another component, and can magnify or shrink it.
  39898. This component will continually update its size so that it fits the zoomed
  39899. version of the content component that you put inside it, so don't try to
  39900. change the size of this component directly - instead change that of the
  39901. content component.
  39902. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  39903. to remap mouse events correctly. This means that the content component won't
  39904. appear to be a direct child of this component, and instead will think its
  39905. on the desktop.
  39906. */
  39907. class JUCE_API MagnifierComponent : public Component
  39908. {
  39909. public:
  39910. /** Creates a MagnifierComponent.
  39911. This component will continually update its size so that it fits the zoomed
  39912. version of the content component that you put inside it, so don't try to
  39913. change the size of this component directly - instead change that of the
  39914. content component.
  39915. @param contentComponent the component to add as the magnified one
  39916. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  39917. be deleted when this component is deleted. If false,
  39918. it's the caller's responsibility to delete it later.
  39919. */
  39920. MagnifierComponent (Component* const contentComponent,
  39921. const bool deleteContentCompWhenNoLongerNeeded);
  39922. /** Destructor. */
  39923. ~MagnifierComponent();
  39924. /** Returns the current content component. */
  39925. Component* getContentComponent() const throw() { return content; }
  39926. /** Changes the zoom level.
  39927. The scale factor must be greater than zero. Values less than 1 will shrink the
  39928. image; values greater than 1 will multiply its size by this amount.
  39929. When this is called, this component will change its size to fit the full extent
  39930. of the newly zoomed content.
  39931. */
  39932. void setScaleFactor (double newScaleFactor);
  39933. /** Returns the current zoom factor. */
  39934. double getScaleFactor() const throw() { return scaleFactor; }
  39935. /** Changes the quality setting used to rescale the graphics.
  39936. */
  39937. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  39938. juce_UseDebuggingNewOperator
  39939. /** @internal */
  39940. void childBoundsChanged (Component*);
  39941. private:
  39942. Component* content;
  39943. Component* holderComp;
  39944. double scaleFactor;
  39945. ComponentPeer* peer;
  39946. bool deleteContent;
  39947. Graphics::ResamplingQuality quality;
  39948. void paint (Graphics& g);
  39949. void mouseDown (const MouseEvent& e);
  39950. void mouseUp (const MouseEvent& e);
  39951. void mouseDrag (const MouseEvent& e);
  39952. void mouseMove (const MouseEvent& e);
  39953. void mouseEnter (const MouseEvent& e);
  39954. void mouseExit (const MouseEvent& e);
  39955. void mouseWheelMove (const MouseEvent& e, float, float);
  39956. int scaleInt (const int n) const throw();
  39957. MagnifierComponent (const MagnifierComponent&);
  39958. const MagnifierComponent& operator= (const MagnifierComponent&);
  39959. };
  39960. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39961. /********* End of inlined file: juce_MagnifierComponent.h *********/
  39962. #endif
  39963. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39964. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  39965. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39966. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39967. /**
  39968. A component that displays a piano keyboard, whose notes can be clicked on.
  39969. This component will mimic a physical midi keyboard, showing the current state of
  39970. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  39971. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  39972. Another feature is that the computer keyboard can also be used to play notes. By
  39973. default it maps the top two rows of a standard querty keyboard to the notes, but
  39974. these can be remapped if needed. It will only respond to keypresses when it has
  39975. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  39976. The component is also a ChangeBroadcaster, so if you want to be informed when the
  39977. keyboard is scrolled, you can register a ChangeListener for callbacks.
  39978. @see MidiKeyboardState
  39979. */
  39980. class JUCE_API MidiKeyboardComponent : public Component,
  39981. public MidiKeyboardStateListener,
  39982. public ChangeBroadcaster,
  39983. private Timer,
  39984. private AsyncUpdater
  39985. {
  39986. public:
  39987. /** The direction of the keyboard.
  39988. @see setOrientation
  39989. */
  39990. enum Orientation
  39991. {
  39992. horizontalKeyboard,
  39993. verticalKeyboardFacingLeft,
  39994. verticalKeyboardFacingRight,
  39995. };
  39996. /** Creates a MidiKeyboardComponent.
  39997. @param state the midi keyboard model that this component will represent
  39998. @param orientation whether the keyboard is horizonal or vertical
  39999. */
  40000. MidiKeyboardComponent (MidiKeyboardState& state,
  40001. const Orientation orientation);
  40002. /** Destructor. */
  40003. ~MidiKeyboardComponent();
  40004. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  40005. on the component.
  40006. Values are 0 to 1.0, where 1.0 is the heaviest.
  40007. @see setMidiChannel
  40008. */
  40009. void setVelocity (const float velocity);
  40010. /** Changes the midi channel number that will be used for events triggered by clicking
  40011. on the component.
  40012. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  40013. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  40014. Although this is the channel used for outgoing events, the component can display
  40015. incoming events from more than one channel - see setMidiChannelsToDisplay()
  40016. @see setVelocity
  40017. */
  40018. void setMidiChannel (const int midiChannelNumber);
  40019. /** Returns the midi channel that the keyboard is using for midi messages.
  40020. @see setMidiChannel
  40021. */
  40022. int getMidiChannel() const throw() { return midiChannel; }
  40023. /** Sets a mask to indicate which incoming midi channels should be represented by
  40024. key movements.
  40025. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  40026. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  40027. in this mask, the on-screen keys will also go down.
  40028. By default, this mask is set to 0xffff (all channels displayed).
  40029. @see setMidiChannel
  40030. */
  40031. void setMidiChannelsToDisplay (const int midiChannelMask);
  40032. /** Returns the current set of midi channels represented by the component.
  40033. This is the value that was set with setMidiChannelsToDisplay().
  40034. */
  40035. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  40036. /** Changes the width used to draw the white keys. */
  40037. void setKeyWidth (const float widthInPixels);
  40038. /** Returns the width that was set by setKeyWidth(). */
  40039. float getKeyWidth() const throw() { return keyWidth; }
  40040. /** Changes the keyboard's current direction. */
  40041. void setOrientation (const Orientation newOrientation);
  40042. /** Returns the keyboard's current direction. */
  40043. const Orientation getOrientation() const throw() { return orientation; }
  40044. /** Sets the range of midi notes that the keyboard will be limited to.
  40045. By default the range is 0 to 127 (inclusive), but you can limit this if you
  40046. only want a restricted set of the keys to be shown.
  40047. Note that the values here are inclusive and must be between 0 and 127.
  40048. */
  40049. void setAvailableRange (const int lowestNote,
  40050. const int highestNote);
  40051. /** Returns the first note in the available range.
  40052. @see setAvailableRange
  40053. */
  40054. int getRangeStart() const throw() { return rangeStart; }
  40055. /** Returns the last note in the available range.
  40056. @see setAvailableRange
  40057. */
  40058. int getRangeEnd() const throw() { return rangeEnd; }
  40059. /** If the keyboard extends beyond the size of the component, this will scroll
  40060. it to show the given key at the start.
  40061. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  40062. base class to send a callback to any ChangeListeners that have been registered.
  40063. */
  40064. void setLowestVisibleKey (int noteNumber);
  40065. /** Returns the number of the first key shown in the component.
  40066. @see setLowestVisibleKey
  40067. */
  40068. int getLowestVisibleKey() const throw() { return firstKey; }
  40069. /** Returns the length of the black notes.
  40070. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  40071. */
  40072. int getBlackNoteLength() const throw() { return blackNoteLength; }
  40073. /** If set to true, then scroll buttons will appear at either end of the keyboard
  40074. if there are too many notes to fit them all in the component at once.
  40075. */
  40076. void setScrollButtonsVisible (const bool canScroll);
  40077. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  40078. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40079. methods.
  40080. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40081. */
  40082. enum ColourIds
  40083. {
  40084. whiteNoteColourId = 0x1005000,
  40085. blackNoteColourId = 0x1005001,
  40086. keySeparatorLineColourId = 0x1005002,
  40087. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  40088. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  40089. textLabelColourId = 0x1005005,
  40090. upDownButtonBackgroundColourId = 0x1005006,
  40091. upDownButtonArrowColourId = 0x1005007
  40092. };
  40093. /** Returns the position within the component of the left-hand edge of a key.
  40094. Depending on the keyboard's orientation, this may be a horizontal or vertical
  40095. distance, in either direction.
  40096. */
  40097. int getKeyStartPosition (const int midiNoteNumber) const;
  40098. /** Deletes all key-mappings.
  40099. @see setKeyPressForNote
  40100. */
  40101. void clearKeyMappings();
  40102. /** Maps a key-press to a given note.
  40103. @param key the key that should trigger the note
  40104. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  40105. be. The actual midi note that gets played will be
  40106. this value + (12 * the current base octave). To change
  40107. the base octave, see setKeyPressBaseOctave()
  40108. */
  40109. void setKeyPressForNote (const KeyPress& key,
  40110. const int midiNoteOffsetFromC);
  40111. /** Removes any key-mappings for a given note.
  40112. For a description of what the note number means, see setKeyPressForNote().
  40113. */
  40114. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  40115. /** Changes the base note above which key-press-triggered notes are played.
  40116. The set of key-mappings that trigger notes can be moved up and down to cover
  40117. the entire scale using this method.
  40118. The value passed in is an octave number between 0 and 10 (inclusive), and
  40119. indicates which C is the base note to which the key-mapped notes are
  40120. relative.
  40121. */
  40122. void setKeyPressBaseOctave (const int newOctaveNumber);
  40123. /** This sets the octave number which is shown as the octave number for middle C.
  40124. This affects only the default implementation of getWhiteNoteText(), which
  40125. passes this octave number to MidiMessage::getMidiNoteName() in order to
  40126. get the note text. See MidiMessage::getMidiNoteName() for more info about
  40127. the parameter.
  40128. By default this value is set to 3.
  40129. @see getOctaveForMiddleC
  40130. */
  40131. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  40132. /** This returns the value set by setOctaveForMiddleC().
  40133. @see setOctaveForMiddleC
  40134. */
  40135. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  40136. /** @internal */
  40137. void paint (Graphics& g);
  40138. /** @internal */
  40139. void resized();
  40140. /** @internal */
  40141. void mouseMove (const MouseEvent& e);
  40142. /** @internal */
  40143. void mouseDrag (const MouseEvent& e);
  40144. /** @internal */
  40145. void mouseDown (const MouseEvent& e);
  40146. /** @internal */
  40147. void mouseUp (const MouseEvent& e);
  40148. /** @internal */
  40149. void mouseEnter (const MouseEvent& e);
  40150. /** @internal */
  40151. void mouseExit (const MouseEvent& e);
  40152. /** @internal */
  40153. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40154. /** @internal */
  40155. void timerCallback();
  40156. /** @internal */
  40157. bool keyStateChanged (const bool isKeyDown);
  40158. /** @internal */
  40159. void focusLost (FocusChangeType cause);
  40160. /** @internal */
  40161. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  40162. /** @internal */
  40163. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  40164. /** @internal */
  40165. void handleAsyncUpdate();
  40166. /** @internal */
  40167. void colourChanged();
  40168. juce_UseDebuggingNewOperator
  40169. protected:
  40170. friend class MidiKeyboardUpDownButton;
  40171. /** Draws a white note in the given rectangle.
  40172. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  40173. currently pressed down.
  40174. When doing this, be sure to note the keyboard's orientation.
  40175. */
  40176. virtual void drawWhiteNote (int midiNoteNumber,
  40177. Graphics& g,
  40178. int x, int y, int w, int h,
  40179. bool isDown, bool isOver,
  40180. const Colour& lineColour,
  40181. const Colour& textColour);
  40182. /** Draws a black note in the given rectangle.
  40183. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  40184. currently pressed down.
  40185. When doing this, be sure to note the keyboard's orientation.
  40186. */
  40187. virtual void drawBlackNote (int midiNoteNumber,
  40188. Graphics& g,
  40189. int x, int y, int w, int h,
  40190. bool isDown, bool isOver,
  40191. const Colour& noteFillColour);
  40192. /** Allows text to be drawn on the white notes.
  40193. By default this is used to label the C in each octave, but could be used for other things.
  40194. @see setOctaveForMiddleC
  40195. */
  40196. virtual const String getWhiteNoteText (const int midiNoteNumber);
  40197. /** Draws the up and down buttons that change the base note. */
  40198. virtual void drawUpDownButton (Graphics& g, int w, int h,
  40199. const bool isMouseOver,
  40200. const bool isButtonPressed,
  40201. const bool movesOctavesUp);
  40202. /** Callback when the mouse is clicked on a key.
  40203. You could use this to do things like handle right-clicks on keys, etc.
  40204. Return true if you want the click to trigger the note, or false if you
  40205. want to handle it yourself and not have the note played.
  40206. @see mouseDraggedToKey
  40207. */
  40208. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  40209. /** Callback when the mouse is dragged from one key onto another.
  40210. @see mouseDownOnKey
  40211. */
  40212. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  40213. /** Calculates the positon of a given midi-note.
  40214. This can be overridden to create layouts with custom key-widths.
  40215. @param midiNoteNumber the note to find
  40216. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  40217. @param x the x position of the left-hand edge of the key (this method
  40218. always works in terms of a horizontal keyboard)
  40219. @param w the width of the key
  40220. */
  40221. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  40222. int& x, int& w) const;
  40223. private:
  40224. MidiKeyboardState& state;
  40225. int xOffset, blackNoteLength;
  40226. float keyWidth;
  40227. Orientation orientation;
  40228. int midiChannel, midiInChannelMask;
  40229. float velocity;
  40230. int noteUnderMouse, mouseDownNote;
  40231. BitArray keysPressed, keysCurrentlyDrawnDown;
  40232. int rangeStart, rangeEnd, firstKey;
  40233. bool canScroll, mouseDragging;
  40234. Button* scrollDown;
  40235. Button* scrollUp;
  40236. Array <KeyPress> keyPresses;
  40237. Array <int> keyPressNotes;
  40238. int keyMappingOctave;
  40239. int octaveNumForMiddleC;
  40240. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  40241. int xyToNote (int x, int y);
  40242. int remappedXYToNote (int x, int y) const;
  40243. void resetAnyKeysInUse();
  40244. void updateNoteUnderMouse (int x, int y);
  40245. void repaintNote (const int midiNoteNumber);
  40246. MidiKeyboardComponent (const MidiKeyboardComponent&);
  40247. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  40248. };
  40249. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40250. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  40251. #endif
  40252. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40253. /********* Start of inlined file: juce_NSViewComponent.h *********/
  40254. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40255. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40256. #if ! DOXYGEN
  40257. class NSViewComponentInternal;
  40258. #endif
  40259. #if JUCE_MAC || DOXYGEN
  40260. /**
  40261. A Mac-specific class that can create and embed an NSView inside itself.
  40262. To use it, create one of these, put it in place and make sure it's visible in a
  40263. window, then use setView() to assign an NSView to it. The view will then be
  40264. moved and resized to follow the movements of this component.
  40265. Of course, since the view is a native object, it'll obliterate any
  40266. juce components that may overlap this component, but that's life.
  40267. */
  40268. class JUCE_API NSViewComponent : public Component
  40269. {
  40270. public:
  40271. /** Create an initially-empty container. */
  40272. NSViewComponent();
  40273. /** Destructor. */
  40274. ~NSViewComponent();
  40275. /** Assigns an NSView to this peer.
  40276. The view will be retained and released by this component for as long as
  40277. it is needed. To remove the current view, just call setView (0).
  40278. Note: a void* is used here to avoid including the cocoa headers as
  40279. part of the juce.h, but the method expects an NSView*.
  40280. */
  40281. void setView (void* nsView);
  40282. /** Returns the current NSView.
  40283. Note: a void* is returned here to avoid including the cocoa headers as
  40284. a requirement of juce.h, so you should just cast the object to an NSView*.
  40285. */
  40286. void* getView() const;
  40287. /** @internal */
  40288. void paint (Graphics& g);
  40289. juce_UseDebuggingNewOperator
  40290. private:
  40291. friend class NSViewComponentInternal;
  40292. NSViewComponentInternal* info;
  40293. NSViewComponent (const NSViewComponent&);
  40294. const NSViewComponent& operator= (const NSViewComponent&);
  40295. };
  40296. #endif
  40297. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40298. /********* End of inlined file: juce_NSViewComponent.h *********/
  40299. #endif
  40300. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40301. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  40302. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40303. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40304. // this is used to disable OpenGL, and is defined in juce_Config.h
  40305. #if JUCE_OPENGL || DOXYGEN
  40306. class OpenGLComponentWatcher;
  40307. /**
  40308. Represents the various properties of an OpenGL bitmap format.
  40309. @see OpenGLComponent::setPixelFormat
  40310. */
  40311. class JUCE_API OpenGLPixelFormat
  40312. {
  40313. public:
  40314. /** Creates an OpenGLPixelFormat.
  40315. The default constructor just initialises the object as a simple 8-bit
  40316. RGBA format.
  40317. */
  40318. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  40319. const int alphaBits = 8,
  40320. const int depthBufferBits = 16,
  40321. const int stencilBufferBits = 0) throw();
  40322. int redBits; /**< The number of bits per pixel to use for the red channel. */
  40323. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  40324. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  40325. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  40326. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  40327. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  40328. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  40329. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  40330. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  40331. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  40332. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  40333. /** Returns a list of all the pixel formats that can be used in this system.
  40334. A reference component is needed in case there are multiple screens with different
  40335. capabilities - in which case, the one that the component is on will be used.
  40336. */
  40337. static void getAvailablePixelFormats (Component* component,
  40338. OwnedArray <OpenGLPixelFormat>& results);
  40339. bool operator== (const OpenGLPixelFormat&) const throw();
  40340. juce_UseDebuggingNewOperator
  40341. };
  40342. /**
  40343. A base class for types of OpenGL context.
  40344. An OpenGLComponent will supply its own context for drawing in its window.
  40345. */
  40346. class JUCE_API OpenGLContext
  40347. {
  40348. public:
  40349. /** Destructor. */
  40350. virtual ~OpenGLContext();
  40351. /** Makes this context the currently active one. */
  40352. virtual bool makeActive() const throw() = 0;
  40353. /** If this context is currently active, it is disactivated. */
  40354. virtual bool makeInactive() const throw() = 0;
  40355. /** Returns true if this context is currently active. */
  40356. virtual bool isActive() const throw() = 0;
  40357. /** Swaps the buffers (if the context can do this). */
  40358. virtual void swapBuffers() = 0;
  40359. /** Sets whether the context checks the vertical sync before swapping.
  40360. The value is the number of frames to allow between buffer-swapping. This is
  40361. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  40362. and greater numbers indicate that it should swap less often.
  40363. Returns true if it sets the value successfully.
  40364. */
  40365. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  40366. /** Returns the current swap-sync interval.
  40367. See setSwapInterval() for info about the value returned.
  40368. */
  40369. virtual int getSwapInterval() const = 0;
  40370. /** Returns the pixel format being used by this context. */
  40371. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  40372. /** For windowed contexts, this moves the context within the bounds of
  40373. its parent window.
  40374. */
  40375. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  40376. /** For windowed contexts, this triggers a repaint of the window.
  40377. (Not relevent on all platforms).
  40378. */
  40379. virtual void repaint() = 0;
  40380. /** Returns an OS-dependent handle to the raw GL context.
  40381. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  40382. a GLXContext.
  40383. */
  40384. virtual void* getRawContext() const throw() = 0;
  40385. /** This tries to create a context that can be used for drawing into the
  40386. area occupied by the specified component.
  40387. Note that you probably shouldn't use this method directly unless you know what
  40388. you're doing - the OpenGLComponent calls this and manages the context for you.
  40389. */
  40390. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  40391. const OpenGLPixelFormat& pixelFormat,
  40392. const OpenGLContext* const contextToShareWith);
  40393. /** Returns the context that's currently in active use by the calling thread.
  40394. Returns 0 if there isn't an active context.
  40395. */
  40396. static OpenGLContext* getCurrentContext();
  40397. juce_UseDebuggingNewOperator
  40398. protected:
  40399. OpenGLContext() throw();
  40400. };
  40401. /**
  40402. A component that contains an OpenGL canvas.
  40403. Override this, add it to whatever component you want to, and use the renderOpenGL()
  40404. method to draw its contents.
  40405. */
  40406. class JUCE_API OpenGLComponent : public Component
  40407. {
  40408. public:
  40409. /** Creates an OpenGLComponent.
  40410. */
  40411. OpenGLComponent();
  40412. /** Destructor. */
  40413. ~OpenGLComponent();
  40414. /** Changes the pixel format used by this component.
  40415. @see OpenGLPixelFormat::getAvailablePixelFormats()
  40416. */
  40417. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  40418. /** Returns the pixel format that this component is currently using. */
  40419. const OpenGLPixelFormat getPixelFormat() const;
  40420. /** Specifies an OpenGL context which should be shared with the one that this
  40421. component is using.
  40422. This is an OpenGL feature that lets two contexts share their texture data.
  40423. Note that this pointer is stored by the component, and when the component
  40424. needs to recreate its internal context for some reason, the same context
  40425. will be used again to share lists. So if you pass a context in here,
  40426. don't delete the context while this component is still using it! You can
  40427. call shareWith (0) to stop this component from sharing with it.
  40428. */
  40429. void shareWith (OpenGLContext* contextToShareListsWith);
  40430. /** Returns the context that this component is sharing with.
  40431. @see shareWith
  40432. */
  40433. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  40434. /** Flips the openGL buffers over. */
  40435. void swapBuffers();
  40436. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  40437. When this is called, makeCurrentContextActive() will already have been called
  40438. for you, so you just need to draw.
  40439. */
  40440. virtual void renderOpenGL() = 0;
  40441. /** This method is called when the component creates a new OpenGL context.
  40442. A new context may be created when the component is first used, or when it
  40443. is moved to a different window, or when the window is hidden and re-shown,
  40444. etc.
  40445. You can use this callback as an opportunity to set up things like textures
  40446. that your context needs.
  40447. New contexts are created on-demand by the makeCurrentContextActive() method - so
  40448. if the context is deleted, e.g. by changing the pixel format or window, no context
  40449. will be created until the next call to makeCurrentContextActive(), which will
  40450. synchronously create one and call this method. This means that if you're using
  40451. a non-GUI thread for rendering, you can make sure this method is be called by
  40452. your renderer thread.
  40453. When this callback happens, the context will already have been made current
  40454. using the makeCurrentContextActive() method, so there's no need to call it
  40455. again in your code.
  40456. */
  40457. virtual void newOpenGLContextCreated() = 0;
  40458. /** Returns the context that will draw into this component.
  40459. This may return 0 if the component is currently invisible or hasn't currently
  40460. got a context. The context object can be deleted and a new one created during
  40461. the lifetime of this component, and there may be times when it doesn't have one.
  40462. @see newOpenGLContextCreated()
  40463. */
  40464. OpenGLContext* getCurrentContext() const throw() { return context; }
  40465. /** Makes this component the current openGL context.
  40466. You might want to use this in things like your resize() method, before calling
  40467. GL commands.
  40468. If this returns false, then the context isn't active, so you should avoid
  40469. making any calls.
  40470. This call may actually create a context if one isn't currently initialised. If
  40471. it does this, it will also synchronously call the newOpenGLContextCreated()
  40472. method to let you initialise it as necessary.
  40473. @see OpenGLContext::makeActive
  40474. */
  40475. bool makeCurrentContextActive();
  40476. /** Stops the current component being the active OpenGL context.
  40477. This is the opposite of makeCurrentContextActive()
  40478. @see OpenGLContext::makeInactive
  40479. */
  40480. void makeCurrentContextInactive();
  40481. /** Returns true if this component is the active openGL context for the
  40482. current thread.
  40483. @see OpenGLContext::isActive
  40484. */
  40485. bool isActiveContext() const throw();
  40486. /** Calls the rendering callback, and swaps the buffers afterwards.
  40487. This is called automatically by paint() when the component needs to be rendered.
  40488. It can be overridden if you need to decouple the rendering from the paint callback
  40489. and render with a custom thread.
  40490. Returns true if the operation succeeded.
  40491. */
  40492. virtual bool renderAndSwapBuffers();
  40493. /** This returns a critical section that can be used to lock the current context.
  40494. Because the context that is used by this component can change, e.g. when the
  40495. component is shown or hidden, then if you're rendering to it on a background
  40496. thread, this allows you to lock the context for the duration of your rendering
  40497. routine.
  40498. */
  40499. CriticalSection& getContextLock() throw() { return contextLock; }
  40500. /** @internal */
  40501. void paint (Graphics& g);
  40502. /** Returns the native handle of an embedded heavyweight window, if there is one.
  40503. E.g. On windows, this will return the HWND of the sub-window containing
  40504. the opengl context, on the mac it'll be the NSOpenGLView.
  40505. */
  40506. void* getNativeWindowHandle() const;
  40507. juce_UseDebuggingNewOperator
  40508. private:
  40509. friend class OpenGLComponentWatcher;
  40510. OpenGLComponentWatcher* componentWatcher;
  40511. OpenGLContext* context;
  40512. OpenGLContext* contextToShareListsWith;
  40513. CriticalSection contextLock;
  40514. OpenGLPixelFormat preferredPixelFormat;
  40515. bool needToUpdateViewport;
  40516. void deleteContext();
  40517. void updateContextPosition();
  40518. void internalRepaint (int x, int y, int w, int h);
  40519. OpenGLComponent (const OpenGLComponent&);
  40520. const OpenGLComponent& operator= (const OpenGLComponent&);
  40521. };
  40522. #endif
  40523. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40524. /********* End of inlined file: juce_OpenGLComponent.h *********/
  40525. #endif
  40526. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40527. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  40528. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40529. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40530. /**
  40531. A component with a set of buttons at the top for changing between pages of
  40532. preferences.
  40533. This is just a handy way of writing a Mac-style preferences panel where you
  40534. have a row of buttons along the top for the different preference categories,
  40535. each button having an icon above its name. Clicking these will show an
  40536. appropriate prefs page below it.
  40537. You can either put one of these inside your own component, or just use the
  40538. showInDialogBox() method to show it in a window and run it modally.
  40539. To use it, just add a set of named pages with the addSettingsPage() method,
  40540. and implement the createComponentForPage() method to create suitable components
  40541. for each of these pages.
  40542. */
  40543. class JUCE_API PreferencesPanel : public Component,
  40544. private ButtonListener
  40545. {
  40546. public:
  40547. /** Creates an empty panel.
  40548. Use addSettingsPage() to add some pages to it in your constructor.
  40549. */
  40550. PreferencesPanel();
  40551. /** Destructor. */
  40552. ~PreferencesPanel();
  40553. /** Creates a page using a set of drawables to define the page's icon.
  40554. Note that the other version of this method is much easier if you're using
  40555. an image instead of a custom drawable.
  40556. @param pageTitle the name of this preferences page - you'll need to
  40557. make sure your createComponentForPage() method creates
  40558. a suitable component when it is passed this name
  40559. @param normalIcon the drawable to display in the page's button normally
  40560. @param overIcon the drawable to display in the page's button when the mouse is over
  40561. @param downIcon the drawable to display in the page's button when the button is down
  40562. @see DrawableButton
  40563. */
  40564. void addSettingsPage (const String& pageTitle,
  40565. const Drawable* normalIcon,
  40566. const Drawable* overIcon,
  40567. const Drawable* downIcon);
  40568. /** Creates a page using a set of drawables to define the page's icon.
  40569. The other version of this method gives you more control over the icon, but this
  40570. one is much easier if you're just loading it from a file.
  40571. @param pageTitle the name of this preferences page - you'll need to
  40572. make sure your createComponentForPage() method creates
  40573. a suitable component when it is passed this name
  40574. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  40575. For this to look good, you'll probably want to use a nice
  40576. transparent png file.
  40577. @param imageDataSize the size of the image data, in bytes
  40578. */
  40579. void addSettingsPage (const String& pageTitle,
  40580. const char* imageData,
  40581. const int imageDataSize);
  40582. /** Utility method to display this panel in a DialogWindow.
  40583. Calling this will create a DialogWindow containing this panel with the
  40584. given size and title, and will run it modally, returning when the user
  40585. closes the dialog box.
  40586. */
  40587. void showInDialogBox (const String& dialogtitle,
  40588. int dialogWidth,
  40589. int dialogHeight,
  40590. const Colour& backgroundColour = Colours::white);
  40591. /** Subclasses must override this to return a component for each preferences page.
  40592. The subclass should return a pointer to a new component representing the named
  40593. page, which the panel will then display.
  40594. The panel will delete the component later when the user goes to another page
  40595. or deletes the panel.
  40596. */
  40597. virtual Component* createComponentForPage (const String& pageName) = 0;
  40598. /** Changes the current page being displayed. */
  40599. void setCurrentPage (const String& pageName);
  40600. /** @internal */
  40601. void resized();
  40602. /** @internal */
  40603. void paint (Graphics& g);
  40604. /** @internal */
  40605. void buttonClicked (Button* button);
  40606. juce_UseDebuggingNewOperator
  40607. private:
  40608. String currentPageName;
  40609. Component* currentPage;
  40610. int buttonSize;
  40611. PreferencesPanel (const PreferencesPanel&);
  40612. const PreferencesPanel& operator= (const PreferencesPanel&);
  40613. };
  40614. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40615. /********* End of inlined file: juce_PreferencesPanel.h *********/
  40616. #endif
  40617. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40618. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  40619. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40620. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40621. #if JUCE_WEB_BROWSER || DOXYGEN
  40622. #if ! DOXYGEN
  40623. class WebBrowserComponentInternal;
  40624. #endif
  40625. /**
  40626. A component that displays an embedded web browser.
  40627. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  40628. Windows, probably IE.
  40629. */
  40630. class JUCE_API WebBrowserComponent : public Component
  40631. {
  40632. public:
  40633. /** Creates a WebBrowserComponent.
  40634. Once it's created and visible, send the browser to a URL using goToURL().
  40635. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  40636. component is taken offscreen, it'll clear the current page
  40637. and replace it with a blank page - this can be handy to stop
  40638. the browser using resources in the background when it's not
  40639. actually being used.
  40640. */
  40641. WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden = true);
  40642. /** Destructor. */
  40643. ~WebBrowserComponent();
  40644. /** Sends the browser to a particular URL.
  40645. @param url the URL to go to.
  40646. @param headers an optional set of parameters to put in the HTTP header. If
  40647. you supply this, it should be a set of string in the form
  40648. "HeaderKey: HeaderValue"
  40649. @param postData an optional block of data that will be attached to the HTTP
  40650. POST request
  40651. */
  40652. void goToURL (const String& url,
  40653. const StringArray* headers = 0,
  40654. const MemoryBlock* postData = 0);
  40655. /** Stops the current page loading.
  40656. */
  40657. void stop();
  40658. /** Sends the browser back one page.
  40659. */
  40660. void goBack();
  40661. /** Sends the browser forward one page.
  40662. */
  40663. void goForward();
  40664. /** Refreshes the browser.
  40665. */
  40666. void refresh();
  40667. /** This callback is called when the browser is about to navigate
  40668. to a new location.
  40669. You can override this method to perform some action when the user
  40670. tries to go to a particular URL. To allow the operation to carry on,
  40671. return true, or return false to stop the navigation happening.
  40672. */
  40673. virtual bool pageAboutToLoad (const String& newURL);
  40674. /** @internal */
  40675. void paint (Graphics& g);
  40676. /** @internal */
  40677. void resized();
  40678. /** @internal */
  40679. void parentHierarchyChanged();
  40680. /** @internal */
  40681. void visibilityChanged();
  40682. juce_UseDebuggingNewOperator
  40683. private:
  40684. WebBrowserComponentInternal* browser;
  40685. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  40686. String lastURL;
  40687. StringArray lastHeaders;
  40688. MemoryBlock lastPostData;
  40689. void reloadLastURL();
  40690. void checkWindowAssociation();
  40691. WebBrowserComponent (const WebBrowserComponent&);
  40692. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  40693. };
  40694. #endif
  40695. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40696. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  40697. #endif
  40698. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40699. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  40700. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40701. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40702. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  40703. /**
  40704. On Windows only, this component sits in the taskbar tray as a small icon.
  40705. To use it, just create one of these components, but don't attempt to make it
  40706. visible, add it to a parent, or put it on the desktop.
  40707. You can then call setIconImage() to create an icon for it in the taskbar.
  40708. To change the icon's tooltip, you can use setIconTooltip().
  40709. To respond to mouse-events, you can override the normal mouseDown(),
  40710. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  40711. position will not be valid, you can use this to respond to clicks. Traditionally
  40712. you'd use a left-click to show your application's window, and a right-click
  40713. to show a pop-up menu.
  40714. */
  40715. class JUCE_API SystemTrayIconComponent : public Component
  40716. {
  40717. public:
  40718. SystemTrayIconComponent();
  40719. /** Destructor. */
  40720. ~SystemTrayIconComponent();
  40721. /** Changes the image shown in the taskbar.
  40722. */
  40723. void setIconImage (const Image& newImage);
  40724. /** Changes the tooltip that Windows shows above the icon. */
  40725. void setIconTooltip (const String& tooltip);
  40726. #if JUCE_LINUX
  40727. /** @internal */
  40728. void paint (Graphics& g);
  40729. #endif
  40730. juce_UseDebuggingNewOperator
  40731. private:
  40732. SystemTrayIconComponent (const SystemTrayIconComponent&);
  40733. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  40734. };
  40735. #endif
  40736. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40737. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  40738. #endif
  40739. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40740. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  40741. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40742. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40743. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  40744. // amalgamated build)
  40745. #if JUCE_WINDOWS
  40746. typedef ActiveXControlComponent QTCompBaseClass;
  40747. #elif JUCE_MAC
  40748. typedef NSViewComponent QTCompBaseClass;
  40749. #endif
  40750. // this is used to disable QuickTime, and is defined in juce_Config.h
  40751. #if JUCE_QUICKTIME || DOXYGEN
  40752. /**
  40753. A window that can play back a QuickTime movie.
  40754. */
  40755. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  40756. {
  40757. public:
  40758. /** Creates a QuickTimeMovieComponent, initially blank.
  40759. Use the loadMovie() method to load a movie once you've added the
  40760. component to a window, (or put it on the desktop as a heavyweight window).
  40761. Loading a movie when the component isn't visible can cause problems, as
  40762. QuickTime needs a window handle to initialise properly.
  40763. */
  40764. QuickTimeMovieComponent();
  40765. /** Destructor. */
  40766. ~QuickTimeMovieComponent();
  40767. /** Returns true if QT is installed and working on this machine.
  40768. */
  40769. static bool isQuickTimeAvailable() throw();
  40770. /** Tries to load a QuickTime movie from a file into the player.
  40771. It's best to call this function once you've added the component to a window,
  40772. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40773. component isn't visible can cause problems, because QuickTime needs a window
  40774. handle to do its stuff.
  40775. @param movieFile the .mov file to open
  40776. @param isControllerVisible whether to show a controller bar at the bottom
  40777. @returns true if the movie opens successfully
  40778. */
  40779. bool loadMovie (const File& movieFile,
  40780. const bool isControllerVisible);
  40781. /** Tries to load a QuickTime movie from a URL into the player.
  40782. It's best to call this function once you've added the component to a window,
  40783. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40784. component isn't visible can cause problems, because QuickTime needs a window
  40785. handle to do its stuff.
  40786. @param movieURL the .mov file to open
  40787. @param isControllerVisible whether to show a controller bar at the bottom
  40788. @returns true if the movie opens successfully
  40789. */
  40790. bool loadMovie (const URL& movieURL,
  40791. const bool isControllerVisible);
  40792. /** Tries to load a QuickTime movie from a stream into the player.
  40793. It's best to call this function once you've added the component to a window,
  40794. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40795. component isn't visible can cause problems, because QuickTime needs a window
  40796. handle to do its stuff.
  40797. @param movieStream a stream containing a .mov file. The component may try
  40798. to read the whole stream before playing, rather than
  40799. streaming from it.
  40800. @param isControllerVisible whether to show a controller bar at the bottom
  40801. @returns true if the movie opens successfully
  40802. */
  40803. bool loadMovie (InputStream* movieStream,
  40804. const bool isControllerVisible);
  40805. /** Closes the movie, if one is open. */
  40806. void closeMovie();
  40807. /** Returns the movie file that is currently open.
  40808. If there isn't one, this returns File::nonexistent
  40809. */
  40810. const File getCurrentMovieFile() const;
  40811. /** Returns true if there's currently a movie open. */
  40812. bool isMovieOpen() const;
  40813. /** Returns the length of the movie, in seconds. */
  40814. double getMovieDuration() const;
  40815. /** Returns the movie's natural size, in pixels.
  40816. You can use this to resize the component to show the movie at its preferred
  40817. scale.
  40818. If no movie is loaded, the size returned will be 0 x 0.
  40819. */
  40820. void getMovieNormalSize (int& width, int& height) const;
  40821. /** This will position the component within a given area, keeping its aspect
  40822. ratio correct according to the movie's normal size.
  40823. The component will be made as large as it can go within the space, and will
  40824. be aligned according to the justification value if this means there are gaps at
  40825. the top or sides.
  40826. */
  40827. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  40828. const RectanglePlacement& placement);
  40829. /** Starts the movie playing. */
  40830. void play();
  40831. /** Stops the movie playing. */
  40832. void stop();
  40833. /** Returns true if the movie is currently playing. */
  40834. bool isPlaying() const;
  40835. /** Moves the movie's position back to the start. */
  40836. void goToStart();
  40837. /** Sets the movie's position to a given time. */
  40838. void setPosition (const double seconds);
  40839. /** Returns the current play position of the movie. */
  40840. double getPosition() const;
  40841. /** Changes the movie playback rate.
  40842. A value of 1 is normal speed, greater values play it proportionately faster,
  40843. smaller values play it slower.
  40844. */
  40845. void setSpeed (const float newSpeed);
  40846. /** Changes the movie's playback volume.
  40847. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  40848. */
  40849. void setMovieVolume (const float newVolume);
  40850. /** Returns the movie's playback volume.
  40851. @returns the volume in the range 0 (silent) to 1.0 (full)
  40852. */
  40853. float getMovieVolume() const;
  40854. /** Tells the movie whether it should loop. */
  40855. void setLooping (const bool shouldLoop);
  40856. /** Returns true if the movie is currently looping.
  40857. @see setLooping
  40858. */
  40859. bool isLooping() const;
  40860. /** True if the native QuickTime controller bar is shown in the window.
  40861. @see loadMovie
  40862. */
  40863. bool isControllerVisible() const;
  40864. /** @internal */
  40865. void paint (Graphics& g);
  40866. juce_UseDebuggingNewOperator
  40867. private:
  40868. File movieFile;
  40869. bool movieLoaded, controllerVisible, looping;
  40870. #if JUCE_WINDOWS
  40871. /** @internal */
  40872. void parentHierarchyChanged();
  40873. /** @internal */
  40874. void visibilityChanged();
  40875. void createControlIfNeeded();
  40876. bool isControlCreated() const;
  40877. void* internal;
  40878. #else
  40879. void* movie;
  40880. #endif
  40881. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  40882. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  40883. };
  40884. #endif
  40885. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40886. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  40887. #endif
  40888. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40889. /********* Start of inlined file: juce_LookAndFeel.h *********/
  40890. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40891. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  40892. class ToggleButton;
  40893. class TextButton;
  40894. class AlertWindow;
  40895. class TextLayout;
  40896. class ScrollBar;
  40897. class BubbleComponent;
  40898. class ComboBox;
  40899. class Button;
  40900. class FilenameComponent;
  40901. class DocumentWindow;
  40902. class ResizableWindow;
  40903. class GroupComponent;
  40904. class MenuBarComponent;
  40905. class DropShadower;
  40906. class GlyphArrangement;
  40907. class PropertyComponent;
  40908. class TableHeaderComponent;
  40909. class Toolbar;
  40910. class ToolbarItemComponent;
  40911. class PopupMenu;
  40912. class ProgressBar;
  40913. class FileBrowserComponent;
  40914. class DirectoryContentsDisplayComponent;
  40915. class FilePreviewComponent;
  40916. class ImageButton;
  40917. /**
  40918. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40919. can be used to apply different 'skins' to the application.
  40920. */
  40921. class JUCE_API LookAndFeel
  40922. {
  40923. public:
  40924. /** Creates the default JUCE look and feel. */
  40925. LookAndFeel();
  40926. /** Destructor. */
  40927. virtual ~LookAndFeel();
  40928. /** Returns the current default look-and-feel for a component to use when it
  40929. hasn't got one explicitly set.
  40930. @see setDefaultLookAndFeel
  40931. */
  40932. static LookAndFeel& getDefaultLookAndFeel() throw();
  40933. /** Changes the default look-and-feel.
  40934. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40935. set to 0, it will revert to using the default one. The
  40936. object passed-in must be deleted by the caller when
  40937. it's no longer needed.
  40938. @see getDefaultLookAndFeel
  40939. */
  40940. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40941. /** Looks for a colour that has been registered with the given colour ID number.
  40942. If a colour has been set for this ID number using setColour(), then it is
  40943. returned. If none has been set, it will just return Colours::black.
  40944. The colour IDs for various purposes are stored as enums in the components that
  40945. they are relevent to - for an example, see Slider::ColourIds,
  40946. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40947. If you're looking up a colour for use in drawing a component, it's usually
  40948. best not to call this directly, but to use the Component::findColour() method
  40949. instead. That will first check whether a suitable colour has been registered
  40950. directly with the component, and will fall-back on calling the component's
  40951. LookAndFeel's findColour() method if none is found.
  40952. @see setColour, Component::findColour, Component::setColour
  40953. */
  40954. const Colour findColour (const int colourId) const throw();
  40955. /** Registers a colour to be used for a particular purpose.
  40956. For more details, see the comments for findColour().
  40957. @see findColour, Component::findColour, Component::setColour
  40958. */
  40959. void setColour (const int colourId, const Colour& colour) throw();
  40960. /** Returns true if the specified colour ID has been explicitly set using the
  40961. setColour() method.
  40962. */
  40963. bool isColourSpecified (const int colourId) const throw();
  40964. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40965. /** Allows you to change the default sans-serif font.
  40966. If you need to supply your own Typeface object for any of the default fonts, rather
  40967. than just supplying the name (e.g. if you want to use an embedded font), then
  40968. you should instead override getTypefaceForFont() to create and return the typeface.
  40969. */
  40970. void setDefaultSansSerifTypefaceName (const String& newName);
  40971. /** Draws the lozenge-shaped background for a standard button. */
  40972. virtual void drawButtonBackground (Graphics& g,
  40973. Button& button,
  40974. const Colour& backgroundColour,
  40975. bool isMouseOverButton,
  40976. bool isButtonDown);
  40977. virtual const Font getFontForTextButton (TextButton& button);
  40978. /** Draws the text for a TextButton. */
  40979. virtual void drawButtonText (Graphics& g,
  40980. TextButton& button,
  40981. bool isMouseOverButton,
  40982. bool isButtonDown);
  40983. /** Draws the contents of a standard ToggleButton. */
  40984. virtual void drawToggleButton (Graphics& g,
  40985. ToggleButton& button,
  40986. bool isMouseOverButton,
  40987. bool isButtonDown);
  40988. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40989. virtual void drawTickBox (Graphics& g,
  40990. Component& component,
  40991. int x, int y, int w, int h,
  40992. const bool ticked,
  40993. const bool isEnabled,
  40994. const bool isMouseOverButton,
  40995. const bool isButtonDown);
  40996. /* AlertWindow handling..
  40997. */
  40998. virtual AlertWindow* createAlertWindow (const String& title,
  40999. const String& message,
  41000. const String& button1,
  41001. const String& button2,
  41002. const String& button3,
  41003. AlertWindow::AlertIconType iconType,
  41004. int numButtons,
  41005. Component* associatedComponent);
  41006. virtual void drawAlertBox (Graphics& g,
  41007. AlertWindow& alert,
  41008. const Rectangle& textArea,
  41009. TextLayout& textLayout);
  41010. virtual int getAlertBoxWindowFlags();
  41011. virtual int getAlertWindowButtonHeight();
  41012. virtual const Font getAlertWindowFont();
  41013. /** Draws a progress bar.
  41014. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  41015. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  41016. isn't known). It can use the current time as a basis for playing an animation.
  41017. (Used by progress bars in AlertWindow).
  41018. */
  41019. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  41020. int width, int height,
  41021. double progress, const String& textToShow);
  41022. // Draws a small image that spins to indicate that something's happening..
  41023. // This method should use the current time to animate itself, so just keep
  41024. // repainting it every so often.
  41025. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  41026. int x, int y, int w, int h);
  41027. /** Draws one of the buttons on a scrollbar.
  41028. @param g the context to draw into
  41029. @param scrollbar the bar itself
  41030. @param width the width of the button
  41031. @param height the height of the button
  41032. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  41033. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  41034. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  41035. @param isButtonDown whether the mouse button's held down
  41036. */
  41037. virtual void drawScrollbarButton (Graphics& g,
  41038. ScrollBar& scrollbar,
  41039. int width, int height,
  41040. int buttonDirection,
  41041. bool isScrollbarVertical,
  41042. bool isMouseOverButton,
  41043. bool isButtonDown);
  41044. /** Draws the thumb area of a scrollbar.
  41045. @param g the context to draw into
  41046. @param scrollbar the bar itself
  41047. @param x the x position of the left edge of the thumb area to draw in
  41048. @param y the y position of the top edge of the thumb area to draw in
  41049. @param width the width of the thumb area to draw in
  41050. @param height the height of the thumb area to draw in
  41051. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  41052. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  41053. thumb, or its x position for horizontal bars
  41054. @param thumbSize for vertical bars, the height of the thumb, or its width for
  41055. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  41056. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  41057. currently dragging the thumb
  41058. @param isMouseDown whether the mouse is currently dragging the scrollbar
  41059. */
  41060. virtual void drawScrollbar (Graphics& g,
  41061. ScrollBar& scrollbar,
  41062. int x, int y,
  41063. int width, int height,
  41064. bool isScrollbarVertical,
  41065. int thumbStartPosition,
  41066. int thumbSize,
  41067. bool isMouseOver,
  41068. bool isMouseDown);
  41069. /** Returns the component effect to use for a scrollbar */
  41070. virtual ImageEffectFilter* getScrollbarEffect();
  41071. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  41072. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  41073. /** Returns the default thickness to use for a scrollbar. */
  41074. virtual int getDefaultScrollbarWidth();
  41075. /** Returns the length in pixels to use for a scrollbar button. */
  41076. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  41077. /** Returns a tick shape for use in yes/no boxes, etc. */
  41078. virtual const Path getTickShape (const float height);
  41079. /** Returns a cross shape for use in yes/no boxes, etc. */
  41080. virtual const Path getCrossShape (const float height);
  41081. /** Draws the + or - box in a treeview. */
  41082. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  41083. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  41084. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  41085. // these return an image from the ImageCache, so use ImageCache::release() to free it
  41086. virtual Image* getDefaultFolderImage();
  41087. virtual Image* getDefaultDocumentFileImage();
  41088. virtual void createFileChooserHeaderText (const String& title,
  41089. const String& instructions,
  41090. GlyphArrangement& destArrangement,
  41091. int width);
  41092. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  41093. const String& filename, Image* icon,
  41094. const String& fileSizeDescription,
  41095. const String& fileTimeDescription,
  41096. const bool isDirectory,
  41097. const bool isItemSelected,
  41098. const int itemIndex);
  41099. virtual Button* createFileBrowserGoUpButton();
  41100. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  41101. DirectoryContentsDisplayComponent* fileListComponent,
  41102. FilePreviewComponent* previewComp,
  41103. ComboBox* currentPathBox,
  41104. TextEditor* filenameBox,
  41105. Button* goUpButton);
  41106. virtual void drawBubble (Graphics& g,
  41107. float tipX, float tipY,
  41108. float boxX, float boxY, float boxW, float boxH);
  41109. /** Fills the background of a popup menu component. */
  41110. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  41111. /** Draws one of the items in a popup menu. */
  41112. virtual void drawPopupMenuItem (Graphics& g,
  41113. int width, int height,
  41114. const bool isSeparator,
  41115. const bool isActive,
  41116. const bool isHighlighted,
  41117. const bool isTicked,
  41118. const bool hasSubMenu,
  41119. const String& text,
  41120. const String& shortcutKeyText,
  41121. Image* image,
  41122. const Colour* const textColour);
  41123. /** Returns the size and style of font to use in popup menus. */
  41124. virtual const Font getPopupMenuFont();
  41125. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  41126. int width, int height,
  41127. bool isScrollUpArrow);
  41128. /** Finds the best size for an item in a popup menu. */
  41129. virtual void getIdealPopupMenuItemSize (const String& text,
  41130. const bool isSeparator,
  41131. int standardMenuItemHeight,
  41132. int& idealWidth,
  41133. int& idealHeight);
  41134. virtual int getMenuWindowFlags();
  41135. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  41136. bool isMouseOverBar,
  41137. MenuBarComponent& menuBar);
  41138. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  41139. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  41140. virtual void drawMenuBarItem (Graphics& g,
  41141. int width, int height,
  41142. int itemIndex,
  41143. const String& itemText,
  41144. bool isMouseOverItem,
  41145. bool isMenuOpen,
  41146. bool isMouseOverBar,
  41147. MenuBarComponent& menuBar);
  41148. virtual void drawComboBox (Graphics& g, int width, int height,
  41149. const bool isButtonDown,
  41150. int buttonX, int buttonY,
  41151. int buttonW, int buttonH,
  41152. ComboBox& box);
  41153. virtual const Font getComboBoxFont (ComboBox& box);
  41154. virtual Label* createComboBoxTextBox (ComboBox& box);
  41155. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  41156. virtual void drawLabel (Graphics& g, Label& label);
  41157. virtual void drawLinearSlider (Graphics& g,
  41158. int x, int y,
  41159. int width, int height,
  41160. float sliderPos,
  41161. float minSliderPos,
  41162. float maxSliderPos,
  41163. const Slider::SliderStyle style,
  41164. Slider& slider);
  41165. virtual void drawLinearSliderBackground (Graphics& g,
  41166. int x, int y,
  41167. int width, int height,
  41168. float sliderPos,
  41169. float minSliderPos,
  41170. float maxSliderPos,
  41171. const Slider::SliderStyle style,
  41172. Slider& slider);
  41173. virtual void drawLinearSliderThumb (Graphics& g,
  41174. int x, int y,
  41175. int width, int height,
  41176. float sliderPos,
  41177. float minSliderPos,
  41178. float maxSliderPos,
  41179. const Slider::SliderStyle style,
  41180. Slider& slider);
  41181. virtual int getSliderThumbRadius (Slider& slider);
  41182. virtual void drawRotarySlider (Graphics& g,
  41183. int x, int y,
  41184. int width, int height,
  41185. float sliderPosProportional,
  41186. const float rotaryStartAngle,
  41187. const float rotaryEndAngle,
  41188. Slider& slider);
  41189. virtual Button* createSliderButton (const bool isIncrement);
  41190. virtual Label* createSliderTextBox (Slider& slider);
  41191. virtual ImageEffectFilter* getSliderEffect();
  41192. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  41193. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  41194. virtual Button* createFilenameComponentBrowseButton (const String& text);
  41195. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  41196. ComboBox* filenameBox, Button* browseButton);
  41197. virtual void drawCornerResizer (Graphics& g,
  41198. int w, int h,
  41199. bool isMouseOver,
  41200. bool isMouseDragging);
  41201. virtual void drawResizableFrame (Graphics& g,
  41202. int w, int h,
  41203. const BorderSize& borders);
  41204. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  41205. const BorderSize& border,
  41206. ResizableWindow& window);
  41207. virtual void drawResizableWindowBorder (Graphics& g,
  41208. int w, int h,
  41209. const BorderSize& border,
  41210. ResizableWindow& window);
  41211. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  41212. Graphics& g, int w, int h,
  41213. int titleSpaceX, int titleSpaceW,
  41214. const Image* icon,
  41215. bool drawTitleTextOnLeft);
  41216. virtual Button* createDocumentWindowButton (int buttonType);
  41217. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  41218. int titleBarX, int titleBarY,
  41219. int titleBarW, int titleBarH,
  41220. Button* minimiseButton,
  41221. Button* maximiseButton,
  41222. Button* closeButton,
  41223. bool positionTitleBarButtonsOnLeft);
  41224. virtual int getDefaultMenuBarHeight();
  41225. virtual DropShadower* createDropShadowerForComponent (Component* component);
  41226. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  41227. int w, int h,
  41228. bool isVerticalBar,
  41229. bool isMouseOver,
  41230. bool isMouseDragging);
  41231. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  41232. const String& text,
  41233. const Justification& position,
  41234. GroupComponent& group);
  41235. virtual void createTabButtonShape (Path& p,
  41236. int width, int height,
  41237. int tabIndex,
  41238. const String& text,
  41239. Button& button,
  41240. TabbedButtonBar::Orientation orientation,
  41241. const bool isMouseOver,
  41242. const bool isMouseDown,
  41243. const bool isFrontTab);
  41244. virtual void fillTabButtonShape (Graphics& g,
  41245. const Path& path,
  41246. const Colour& preferredBackgroundColour,
  41247. int tabIndex,
  41248. const String& text,
  41249. Button& button,
  41250. TabbedButtonBar::Orientation orientation,
  41251. const bool isMouseOver,
  41252. const bool isMouseDown,
  41253. const bool isFrontTab);
  41254. virtual void drawTabButtonText (Graphics& g,
  41255. int x, int y, int w, int h,
  41256. const Colour& preferredBackgroundColour,
  41257. int tabIndex,
  41258. const String& text,
  41259. Button& button,
  41260. TabbedButtonBar::Orientation orientation,
  41261. const bool isMouseOver,
  41262. const bool isMouseDown,
  41263. const bool isFrontTab);
  41264. virtual int getTabButtonOverlap (int tabDepth);
  41265. virtual int getTabButtonSpaceAroundImage();
  41266. virtual int getTabButtonBestWidth (int tabIndex,
  41267. const String& text,
  41268. int tabDepth,
  41269. Button& button);
  41270. virtual void drawTabButton (Graphics& g,
  41271. int w, int h,
  41272. const Colour& preferredColour,
  41273. int tabIndex,
  41274. const String& text,
  41275. Button& button,
  41276. TabbedButtonBar::Orientation orientation,
  41277. const bool isMouseOver,
  41278. const bool isMouseDown,
  41279. const bool isFrontTab);
  41280. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  41281. int w, int h,
  41282. TabbedButtonBar& tabBar,
  41283. TabbedButtonBar::Orientation orientation);
  41284. virtual Button* createTabBarExtrasButton();
  41285. virtual void drawImageButton (Graphics& g, Image* image,
  41286. int imageX, int imageY, int imageW, int imageH,
  41287. const Colour& overlayColour,
  41288. float imageOpacity,
  41289. ImageButton& button);
  41290. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  41291. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  41292. int width, int height,
  41293. bool isMouseOver, bool isMouseDown,
  41294. int columnFlags);
  41295. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  41296. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  41297. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  41298. bool isMouseOver, bool isMouseDown,
  41299. ToolbarItemComponent& component);
  41300. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  41301. const String& text, ToolbarItemComponent& component);
  41302. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  41303. bool isOpen, int width, int height);
  41304. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  41305. PropertyComponent& component);
  41306. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  41307. PropertyComponent& component);
  41308. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  41309. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  41310. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  41311. /**
  41312. */
  41313. virtual void playAlertSound();
  41314. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  41315. static void drawGlassSphere (Graphics& g,
  41316. const float x, const float y,
  41317. const float diameter,
  41318. const Colour& colour,
  41319. const float outlineThickness) throw();
  41320. static void drawGlassPointer (Graphics& g,
  41321. const float x, const float y,
  41322. const float diameter,
  41323. const Colour& colour, const float outlineThickness,
  41324. const int direction) throw();
  41325. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  41326. static void drawGlassLozenge (Graphics& g,
  41327. const float x, const float y,
  41328. const float width, const float height,
  41329. const Colour& colour,
  41330. const float outlineThickness,
  41331. const float cornerSize,
  41332. const bool flatOnLeft, const bool flatOnRight,
  41333. const bool flatOnTop, const bool flatOnBottom) throw();
  41334. juce_UseDebuggingNewOperator
  41335. protected:
  41336. // xxx the following methods are only here to cause a compiler error, because they've been
  41337. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  41338. // error if you try to build a subclass with the old versions.
  41339. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  41340. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  41341. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  41342. virtual void getTabButtonBestWidth (int, const String&, int) {}
  41343. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  41344. private:
  41345. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  41346. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  41347. Array <int> colourIds;
  41348. Array <Colour> colours;
  41349. // default typeface names
  41350. String defaultSans, defaultSerif, defaultFixed;
  41351. void drawShinyButtonShape (Graphics& g,
  41352. float x, float y, float w, float h, float maxCornerSize,
  41353. const Colour& baseColour,
  41354. const float strokeWidth,
  41355. const bool flatOnLeft,
  41356. const bool flatOnRight,
  41357. const bool flatOnTop,
  41358. const bool flatOnBottom) throw();
  41359. LookAndFeel (const LookAndFeel&);
  41360. const LookAndFeel& operator= (const LookAndFeel&);
  41361. };
  41362. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  41363. /********* End of inlined file: juce_LookAndFeel.h *********/
  41364. #endif
  41365. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41366. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  41367. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41368. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41369. /**
  41370. The original Juce look-and-feel.
  41371. */
  41372. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  41373. {
  41374. public:
  41375. /** Creates the default JUCE look and feel. */
  41376. OldSchoolLookAndFeel();
  41377. /** Destructor. */
  41378. virtual ~OldSchoolLookAndFeel();
  41379. /** Draws the lozenge-shaped background for a standard button. */
  41380. virtual void drawButtonBackground (Graphics& g,
  41381. Button& button,
  41382. const Colour& backgroundColour,
  41383. bool isMouseOverButton,
  41384. bool isButtonDown);
  41385. /** Draws the contents of a standard ToggleButton. */
  41386. virtual void drawToggleButton (Graphics& g,
  41387. ToggleButton& button,
  41388. bool isMouseOverButton,
  41389. bool isButtonDown);
  41390. virtual void drawTickBox (Graphics& g,
  41391. Component& component,
  41392. int x, int y, int w, int h,
  41393. const bool ticked,
  41394. const bool isEnabled,
  41395. const bool isMouseOverButton,
  41396. const bool isButtonDown);
  41397. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  41398. int width, int height,
  41399. double progress, const String& textToShow);
  41400. virtual void drawScrollbarButton (Graphics& g,
  41401. ScrollBar& scrollbar,
  41402. int width, int height,
  41403. int buttonDirection,
  41404. bool isScrollbarVertical,
  41405. bool isMouseOverButton,
  41406. bool isButtonDown);
  41407. virtual void drawScrollbar (Graphics& g,
  41408. ScrollBar& scrollbar,
  41409. int x, int y,
  41410. int width, int height,
  41411. bool isScrollbarVertical,
  41412. int thumbStartPosition,
  41413. int thumbSize,
  41414. bool isMouseOver,
  41415. bool isMouseDown);
  41416. virtual ImageEffectFilter* getScrollbarEffect();
  41417. virtual void drawTextEditorOutline (Graphics& g,
  41418. int width, int height,
  41419. TextEditor& textEditor);
  41420. /** Fills the background of a popup menu component. */
  41421. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  41422. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  41423. bool isMouseOverBar,
  41424. MenuBarComponent& menuBar);
  41425. virtual void drawComboBox (Graphics& g, int width, int height,
  41426. const bool isButtonDown,
  41427. int buttonX, int buttonY,
  41428. int buttonW, int buttonH,
  41429. ComboBox& box);
  41430. virtual const Font getComboBoxFont (ComboBox& box);
  41431. virtual void drawLinearSlider (Graphics& g,
  41432. int x, int y,
  41433. int width, int height,
  41434. float sliderPos,
  41435. float minSliderPos,
  41436. float maxSliderPos,
  41437. const Slider::SliderStyle style,
  41438. Slider& slider);
  41439. virtual int getSliderThumbRadius (Slider& slider);
  41440. virtual Button* createSliderButton (const bool isIncrement);
  41441. virtual ImageEffectFilter* getSliderEffect();
  41442. virtual void drawCornerResizer (Graphics& g,
  41443. int w, int h,
  41444. bool isMouseOver,
  41445. bool isMouseDragging);
  41446. virtual Button* createDocumentWindowButton (int buttonType);
  41447. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  41448. int titleBarX, int titleBarY,
  41449. int titleBarW, int titleBarH,
  41450. Button* minimiseButton,
  41451. Button* maximiseButton,
  41452. Button* closeButton,
  41453. bool positionTitleBarButtonsOnLeft);
  41454. juce_UseDebuggingNewOperator
  41455. private:
  41456. DropShadowEffect scrollbarShadow;
  41457. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  41458. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  41459. };
  41460. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41461. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  41462. #endif
  41463. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  41464. #endif
  41465. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41466. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  41467. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41468. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41469. /**
  41470. A class to take care of the logic involved with the loading/saving of some kind
  41471. of document.
  41472. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  41473. functions you need for documents that get saved to a file, so this class attempts
  41474. to abstract most of the boring stuff.
  41475. Your subclass should just implement all the pure virtual methods, and you can
  41476. then use the higher-level public methods to do the load/save dialogs, to warn the user
  41477. about overwriting files, etc.
  41478. The document object keeps track of whether it has changed since it was last saved or
  41479. loaded, so when you change something, call its changed() method. This will set a
  41480. flag so it knows it needs saving, and will also broadcast a change message using the
  41481. ChangeBroadcaster base class.
  41482. @see ChangeBroadcaster
  41483. */
  41484. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  41485. {
  41486. public:
  41487. /** Creates a FileBasedDocument.
  41488. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  41489. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  41490. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  41491. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  41492. */
  41493. FileBasedDocument (const String& fileExtension,
  41494. const String& fileWildCard,
  41495. const String& openFileDialogTitle,
  41496. const String& saveFileDialogTitle);
  41497. /** Destructor. */
  41498. virtual ~FileBasedDocument();
  41499. /** Returns true if the changed() method has been called since the file was
  41500. last saved or loaded.
  41501. @see resetChangedFlag, changed
  41502. */
  41503. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  41504. /** Called to indicate that the document has changed and needs saving.
  41505. This method will also trigger a change message to be sent out using the
  41506. ChangeBroadcaster base class.
  41507. After calling the method, the hasChangedSinceSaved() method will return true, until
  41508. it is reset either by saving to a file or using the resetChangedFlag() method.
  41509. @see hasChangedSinceSaved, resetChangedFlag
  41510. */
  41511. virtual void changed();
  41512. /** Sets the state of the 'changed' flag.
  41513. The 'changed' flag is set to true when the changed() method is called - use this method
  41514. to reset it or to set it without also broadcasting a change message.
  41515. @see changed, hasChangedSinceSaved
  41516. */
  41517. void setChangedFlag (const bool hasChanged);
  41518. /** Tries to open a file.
  41519. If the file opens correctly, the document's file (see the getFile() method) is set
  41520. to this new one; if it fails, the document's file is left unchanged, and optionally
  41521. a message box is shown telling the user there was an error.
  41522. @returns true if the new file loaded successfully
  41523. @see loadDocument, loadFromUserSpecifiedFile
  41524. */
  41525. bool loadFrom (const File& fileToLoadFrom,
  41526. const bool showMessageOnFailure);
  41527. /** Asks the user for a file and tries to load it.
  41528. This will pop up a dialog box using the title, file extension and
  41529. wildcard specified in the document's constructor, and asks the user
  41530. for a file. If they pick one, the loadFrom() method is used to
  41531. try to load it, optionally showing a message if it fails.
  41532. @returns true if a file was loaded; false if the user cancelled or if they
  41533. picked a file which failed to load correctly
  41534. @see loadFrom
  41535. */
  41536. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  41537. /** A set of possible outcomes of one of the save() methods
  41538. */
  41539. enum SaveResult
  41540. {
  41541. savedOk = 0, /**< indicates that a file was saved successfully. */
  41542. userCancelledSave, /**< indicates that the user aborted the save operation. */
  41543. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  41544. };
  41545. /** Tries to save the document to the last file it was saved or loaded from.
  41546. This will always try to write to the file, even if the document isn't flagged as
  41547. having changed.
  41548. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  41549. true, it will prompt the user to pick a file, as if
  41550. saveAsInteractive() was called.
  41551. @param showMessageOnFailure if true it will show a warning message when if the
  41552. save operation fails
  41553. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  41554. */
  41555. SaveResult save (const bool askUserForFileIfNotSpecified,
  41556. const bool showMessageOnFailure);
  41557. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  41558. it if they say yes.
  41559. If you've got a document open and want to close it (e.g. to quit the app), this is the
  41560. method to call.
  41561. If the document doesn't need saving it'll return the value savedOk so
  41562. you can go ahead and delete the document.
  41563. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  41564. return savedOk, so again, you can safely delete the document.
  41565. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  41566. close-document operation.
  41567. And if they click "save changes", it'll try to save and either return savedOk, or
  41568. failedToWriteToFile if there was a problem.
  41569. @see save, saveAs, saveAsInteractive
  41570. */
  41571. SaveResult saveIfNeededAndUserAgrees();
  41572. /** Tries to save the document to a specified file.
  41573. If this succeeds, it'll also change the document's internal file (as returned by
  41574. the getFile() method). If it fails, the file will be left unchanged.
  41575. @param newFile the file to try to write to
  41576. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  41577. the user first if they want to overwrite it
  41578. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  41579. use the saveAsInteractive() method to ask the user for a
  41580. filename
  41581. @param showMessageOnFailure if true and the write operation fails, it'll show
  41582. a message box to warn the user
  41583. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  41584. */
  41585. SaveResult saveAs (const File& newFile,
  41586. const bool warnAboutOverwritingExistingFiles,
  41587. const bool askUserForFileIfNotSpecified,
  41588. const bool showMessageOnFailure);
  41589. /** Prompts the user for a filename and tries to save to it.
  41590. This will pop up a dialog box using the title, file extension and
  41591. wildcard specified in the document's constructor, and asks the user
  41592. for a file. If they pick one, the saveAs() method is used to try to save
  41593. to this file.
  41594. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  41595. the user first if they want to overwrite it
  41596. @see saveIfNeededAndUserAgrees, save, saveAs
  41597. */
  41598. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  41599. /** Returns the file that this document was last successfully saved or loaded from.
  41600. When the document object is created, this will be set to File::nonexistent.
  41601. It is changed when one of the load or save methods is used, or when setFile()
  41602. is used to explicitly set it.
  41603. */
  41604. const File getFile() const throw() { return documentFile; }
  41605. /** Sets the file that this document thinks it was loaded from.
  41606. This won't actually load anything - it just changes the file stored internally.
  41607. @see getFile
  41608. */
  41609. void setFile (const File& newFile);
  41610. protected:
  41611. /** Overload this to return the title of the document.
  41612. This is used in message boxes, filenames and file choosers, so it should be
  41613. something sensible.
  41614. */
  41615. virtual const String getDocumentTitle() = 0;
  41616. /** This method should try to load your document from the given file.
  41617. If it fails, it should return an error message. If it succeeds, it should return
  41618. an empty string.
  41619. */
  41620. virtual const String loadDocument (const File& file) = 0;
  41621. /** This method should try to write your document to the given file.
  41622. If it fails, it should return an error message. If it succeeds, it should return
  41623. an empty string.
  41624. */
  41625. virtual const String saveDocument (const File& file) = 0;
  41626. /** This is used for dialog boxes to make them open at the last folder you
  41627. were using.
  41628. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  41629. the last document that was used - you might want to store this value
  41630. in a static variable, or even in your application's properties. It should
  41631. be a global setting rather than a property of this object.
  41632. This method works very well in conjunction with a RecentlyOpenedFilesList
  41633. object to manage your recent-files list.
  41634. As a default value, it's ok to return File::nonexistent, and the document
  41635. object will use a sensible one instead.
  41636. @see RecentlyOpenedFilesList
  41637. */
  41638. virtual const File getLastDocumentOpened() = 0;
  41639. /** This is used for dialog boxes to make them open at the last folder you
  41640. were using.
  41641. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  41642. the last document that was used - you might want to store this value
  41643. in a static variable, or even in your application's properties. It should
  41644. be a global setting rather than a property of this object.
  41645. This method works very well in conjunction with a RecentlyOpenedFilesList
  41646. object to manage your recent-files list.
  41647. @see RecentlyOpenedFilesList
  41648. */
  41649. virtual void setLastDocumentOpened (const File& file) = 0;
  41650. public:
  41651. juce_UseDebuggingNewOperator
  41652. private:
  41653. File documentFile;
  41654. bool changedSinceSave;
  41655. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  41656. FileBasedDocument (const FileBasedDocument&);
  41657. const FileBasedDocument& operator= (const FileBasedDocument&);
  41658. };
  41659. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41660. /********* End of inlined file: juce_FileBasedDocument.h *********/
  41661. #endif
  41662. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  41663. #endif
  41664. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41665. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  41666. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41667. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41668. /**
  41669. Manages a set of files for use as a list of recently-opened documents.
  41670. This is a handy class for holding your list of recently-opened documents, with
  41671. helpful methods for things like purging any non-existent files, automatically
  41672. adding them to a menu, and making persistence easy.
  41673. @see File, FileBasedDocument
  41674. */
  41675. class JUCE_API RecentlyOpenedFilesList
  41676. {
  41677. public:
  41678. /** Creates an empty list.
  41679. */
  41680. RecentlyOpenedFilesList();
  41681. /** Destructor. */
  41682. ~RecentlyOpenedFilesList();
  41683. /** Sets a limit for the number of files that will be stored in the list.
  41684. When addFile() is called, then if there is no more space in the list, the
  41685. least-recently added file will be dropped.
  41686. @see getMaxNumberOfItems
  41687. */
  41688. void setMaxNumberOfItems (const int newMaxNumber);
  41689. /** Returns the number of items that this list will store.
  41690. @see setMaxNumberOfItems
  41691. */
  41692. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  41693. /** Returns the number of files in the list.
  41694. The most recently added file is always at index 0.
  41695. */
  41696. int getNumFiles() const;
  41697. /** Returns one of the files in the list.
  41698. The most recently added file is always at index 0.
  41699. */
  41700. const File getFile (const int index) const;
  41701. /** Returns an array of all the absolute pathnames in the list.
  41702. */
  41703. const StringArray& getAllFilenames() const throw() { return files; }
  41704. /** Clears all the files from the list. */
  41705. void clear();
  41706. /** Adds a file to the list.
  41707. The file will be added at index 0. If this file is already in the list, it will
  41708. be moved up to index 0, but a file can only appear once in the list.
  41709. If the list already contains the maximum number of items that is permitted, the
  41710. least-recently added file will be dropped from the end.
  41711. */
  41712. void addFile (const File& file);
  41713. /** Checks each of the files in the list, removing any that don't exist.
  41714. You might want to call this after reloading a list of files, or before putting them
  41715. on a menu.
  41716. */
  41717. void removeNonExistentFiles();
  41718. /** Adds entries to a menu, representing each of the files in the list.
  41719. This is handy for creating an "open recent file..." menu in your app. The
  41720. menu items are numbered consecutively starting with the baseItemId value,
  41721. and can either be added as complete pathnames, or just the last part of the
  41722. filename.
  41723. If dontAddNonExistentFiles is true, then each file will be checked and only those
  41724. that exist will be added.
  41725. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  41726. pointers to file objects. Any files that appear in this list will not be added to the
  41727. menu - the reason for this is that you might have a number of files already open, so
  41728. might not want these to be shown in the menu.
  41729. It returns the number of items that were added.
  41730. */
  41731. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  41732. const int baseItemId,
  41733. const bool showFullPaths,
  41734. const bool dontAddNonExistentFiles,
  41735. const File** filesToAvoid = 0);
  41736. /** Returns a string that encapsulates all the files in the list.
  41737. The string that is returned can later be passed into restoreFromString() in
  41738. order to recreate the list. This is handy for persisting your list, e.g. in
  41739. a PropertiesFile object.
  41740. @see restoreFromString
  41741. */
  41742. const String toString() const;
  41743. /** Restores the list from a previously stringified version of the list.
  41744. Pass in a stringified version created with toString() in order to persist/restore
  41745. your list.
  41746. @see toString
  41747. */
  41748. void restoreFromString (const String& stringifiedVersion);
  41749. juce_UseDebuggingNewOperator
  41750. private:
  41751. StringArray files;
  41752. int maxNumberOfItems;
  41753. };
  41754. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41755. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  41756. #endif
  41757. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41758. #endif
  41759. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41760. /********* Start of inlined file: juce_SystemClipboard.h *********/
  41761. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41762. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41763. /**
  41764. Handles reading/writing to the system's clipboard.
  41765. */
  41766. class JUCE_API SystemClipboard
  41767. {
  41768. public:
  41769. /** Copies a string of text onto the clipboard */
  41770. static void copyTextToClipboard (const String& text) throw();
  41771. /** Gets the current clipboard's contents.
  41772. Obviously this might have come from another app, so could contain
  41773. anything..
  41774. */
  41775. static const String getTextFromClipboard() throw();
  41776. };
  41777. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41778. /********* End of inlined file: juce_SystemClipboard.h *********/
  41779. #endif
  41780. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  41781. #endif
  41782. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  41783. #endif
  41784. #endif
  41785. /********* End of inlined file: juce_app_includes.h *********/
  41786. #endif
  41787. #if JUCE_MSVC
  41788. #pragma warning (pop)
  41789. #pragma pack (pop)
  41790. #endif
  41791. #if JUCE_MAC || JUCE_IPHONE
  41792. #pragma align=reset
  41793. #endif
  41794. END_JUCE_NAMESPACE
  41795. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  41796. #ifdef JUCE_NAMESPACE
  41797. // this will obviously save a lot of typing, but can be disabled by
  41798. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  41799. using namespace JUCE_NAMESPACE;
  41800. /* On the Mac, these symbols are defined in the Mac libraries, so
  41801. these macros make it easier to reference them without writing out
  41802. the namespace every time.
  41803. If you run into difficulties where these macros interfere with the contents
  41804. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  41805. the comments in that file for more information.
  41806. */
  41807. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  41808. #define Component JUCE_NAMESPACE::Component
  41809. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  41810. #define Point JUCE_NAMESPACE::Point
  41811. #define Button JUCE_NAMESPACE::Button
  41812. #endif
  41813. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  41814. it easier to use the juce version explicitly.
  41815. If you run into difficulties where this macro interferes with other 3rd party header
  41816. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  41817. file for more information.
  41818. */
  41819. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  41820. #define Rectangle JUCE_NAMESPACE::Rectangle
  41821. #endif
  41822. #endif
  41823. #endif
  41824. /* Easy autolinking to the right JUCE libraries under win32.
  41825. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  41826. including this header file.
  41827. */
  41828. #if JUCE_MSVC
  41829. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  41830. /** If you want your application to link to Juce as a DLL instead of
  41831. a static library (on win32), just define the JUCE_DLL macro before
  41832. including juce.h
  41833. */
  41834. #ifdef JUCE_DLL
  41835. #ifdef JUCE_DEBUG
  41836. #define AUTOLINKEDLIB "JUCE_debug.lib"
  41837. #else
  41838. #define AUTOLINKEDLIB "JUCE.lib"
  41839. #endif
  41840. #else
  41841. #ifdef JUCE_DEBUG
  41842. #ifdef _WIN64
  41843. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  41844. #else
  41845. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  41846. #endif
  41847. #else
  41848. #ifdef _WIN64
  41849. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  41850. #else
  41851. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  41852. #endif
  41853. #endif
  41854. #endif
  41855. #pragma comment(lib, AUTOLINKEDLIB)
  41856. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  41857. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  41858. #endif
  41859. // Auto-link the other win32 libs that are needed by library calls..
  41860. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  41861. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  41862. // Auto-links to various win32 libs that are needed by library calls..
  41863. #pragma comment(lib, "kernel32.lib")
  41864. #pragma comment(lib, "user32.lib")
  41865. #pragma comment(lib, "shell32.lib")
  41866. #pragma comment(lib, "gdi32.lib")
  41867. #pragma comment(lib, "vfw32.lib")
  41868. #pragma comment(lib, "comdlg32.lib")
  41869. #pragma comment(lib, "winmm.lib")
  41870. #pragma comment(lib, "wininet.lib")
  41871. #pragma comment(lib, "ole32.lib")
  41872. #pragma comment(lib, "advapi32.lib")
  41873. #pragma comment(lib, "ws2_32.lib")
  41874. #pragma comment(lib, "comsupp.lib")
  41875. #pragma comment(lib, "version.lib")
  41876. #if JUCE_OPENGL
  41877. #pragma comment(lib, "OpenGL32.Lib")
  41878. #pragma comment(lib, "GlU32.Lib")
  41879. #endif
  41880. #if JUCE_QUICKTIME
  41881. #pragma comment (lib, "QTMLClient.lib")
  41882. #endif
  41883. #if JUCE_USE_CAMERA
  41884. #pragma comment (lib, "Strmiids.lib")
  41885. #endif
  41886. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  41887. #endif
  41888. #endif
  41889. #endif
  41890. /*
  41891. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  41892. AppSubClass is the name of a class derived from JUCEApplication.
  41893. See the JUCEApplication class documentation (juce_Application.h) for more details.
  41894. */
  41895. #if defined (JUCE_GCC) || defined (__MWERKS__)
  41896. #define START_JUCE_APPLICATION(AppClass) \
  41897. int main (int argc, char* argv[]) \
  41898. { \
  41899. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  41900. }
  41901. #elif JUCE_WINDOWS
  41902. #ifdef _CONSOLE
  41903. #define START_JUCE_APPLICATION(AppClass) \
  41904. int main (int, char* argv[]) \
  41905. { \
  41906. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41907. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41908. }
  41909. #elif ! defined (_AFXDLL)
  41910. #ifdef _WINDOWS_
  41911. #define START_JUCE_APPLICATION(AppClass) \
  41912. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  41913. { \
  41914. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41915. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41916. }
  41917. #else
  41918. #define START_JUCE_APPLICATION(AppClass) \
  41919. int __stdcall WinMain (int, int, const char*, int) \
  41920. { \
  41921. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41922. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41923. }
  41924. #endif
  41925. #endif
  41926. #endif
  41927. #endif // __JUCE_JUCEHEADER__
  41928. /********* End of inlined file: juce.h *********/
  41929. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__