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.

56421 lines
2.0MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. ==============================================================================
  20. This header contains the entire Juce source tree, and can be #included in
  21. all your source files.
  22. As well as including this in your files, you should also add juce_inline.cpp
  23. to your project (or juce_inline.mm on the Mac).
  24. ==============================================================================
  25. */
  26. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  27. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  28. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  29. /********* Start of inlined file: juce.h *********/
  30. #ifndef __JUCE_JUCEHEADER__
  31. #define __JUCE_JUCEHEADER__
  32. /*
  33. This is the main JUCE header file that applications need to include.
  34. */
  35. // (this includes things that need defining outside of the JUCE namespace)
  36. /********* Start of inlined file: juce_StandardHeader.h *********/
  37. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  38. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  39. /** Current Juce version number.
  40. See also SystemStats::getJUCEVersion() for a string version.
  41. */
  42. #define JUCE_MAJOR_VERSION 1
  43. #define JUCE_MINOR_VERSION 50
  44. /** Current Juce version number.
  45. Bits 16 to 32 = major version.
  46. Bits 8 to 16 = minor version.
  47. Bits 0 to 8 = point release (not currently used).
  48. See also SystemStats::getJUCEVersion() for a string version.
  49. */
  50. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8))
  51. /********* Start of inlined file: juce_TargetPlatform.h *********/
  52. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  53. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  54. /* This file figures out which platform is being built, and defines some macros
  55. that the rest of the code can use for OS-specific compilation.
  56. Macros that will be set here are:
  57. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  58. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  59. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  60. - Either JUCE_INTEL or JUCE_PPC
  61. - Either JUCE_GCC or JUCE_MSVC
  62. */
  63. #if (defined (_WIN32) || defined (_WIN64))
  64. #define JUCE_WIN32 1
  65. #define JUCE_WINDOWS 1
  66. #elif defined (LINUX) || defined (__linux__)
  67. #define JUCE_LINUX 1
  68. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  69. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  70. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  71. #define JUCE_IPHONE 1
  72. #else
  73. #define JUCE_MAC 1
  74. #endif
  75. #else
  76. #error "Unknown platform!"
  77. #endif
  78. #if JUCE_WINDOWS
  79. #ifdef _MSC_VER
  80. #ifdef _WIN64
  81. #define JUCE_64BIT 1
  82. #else
  83. #define JUCE_32BIT 1
  84. #endif
  85. #endif
  86. #ifdef _DEBUG
  87. #define JUCE_DEBUG 1
  88. #endif
  89. /** If defined, this indicates that the processor is little-endian. */
  90. #define JUCE_LITTLE_ENDIAN 1
  91. #define JUCE_INTEL 1
  92. #endif
  93. #if JUCE_MAC
  94. #ifndef NDEBUG
  95. #define JUCE_DEBUG 1
  96. #endif
  97. #ifdef __LITTLE_ENDIAN__
  98. #define JUCE_LITTLE_ENDIAN 1
  99. #else
  100. #define JUCE_BIG_ENDIAN 1
  101. #endif
  102. #if defined (__ppc__) || defined (__ppc64__)
  103. #define JUCE_PPC 1
  104. #else
  105. #define JUCE_INTEL 1
  106. #endif
  107. #ifdef __LP64__
  108. #define JUCE_64BIT 1
  109. #else
  110. #define JUCE_32BIT 1
  111. #endif
  112. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  113. #error "Building for OSX 10.3 is no longer supported!"
  114. #endif
  115. #ifndef MAC_OS_X_VERSION_10_5
  116. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  117. #endif
  118. #endif
  119. #if JUCE_IPHONE
  120. #ifndef NDEBUG
  121. #define JUCE_DEBUG 1
  122. #endif
  123. #ifdef __LITTLE_ENDIAN__
  124. #define JUCE_LITTLE_ENDIAN 1
  125. #else
  126. #define JUCE_BIG_ENDIAN 1
  127. #endif
  128. #endif
  129. #if JUCE_LINUX
  130. #ifdef _DEBUG
  131. #define JUCE_DEBUG 1
  132. #endif
  133. // Allow override for big-endian Linux platforms
  134. #ifndef JUCE_BIG_ENDIAN
  135. #define JUCE_LITTLE_ENDIAN 1
  136. #endif
  137. #if defined (__LP64__) || defined (_LP64)
  138. #define JUCE_64BIT 1
  139. #else
  140. #define JUCE_32BIT 1
  141. #endif
  142. #define JUCE_INTEL 1
  143. #endif
  144. // Compiler type macros.
  145. #ifdef __GNUC__
  146. #define JUCE_GCC 1
  147. #elif defined (_MSC_VER)
  148. #define JUCE_MSVC 1
  149. #if _MSC_VER >= 1400
  150. #define JUCE_USE_INTRINSICS 1
  151. #endif
  152. #else
  153. #error unknown compiler
  154. #endif
  155. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  156. /********* End of inlined file: juce_TargetPlatform.h *********/
  157. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  158. /********* Start of inlined file: juce_Config.h *********/
  159. #ifndef __JUCE_CONFIG_JUCEHEADER__
  160. #define __JUCE_CONFIG_JUCEHEADER__
  161. /*
  162. This file contains macros that enable/disable various JUCE features.
  163. */
  164. /** The name of the namespace that all Juce classes and functions will be
  165. put inside. If this is not defined, no namespace will be used.
  166. */
  167. #ifndef JUCE_NAMESPACE
  168. #define JUCE_NAMESPACE juce
  169. #endif
  170. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  171. but if you define this value, you can override this can force it to be true or
  172. false.
  173. */
  174. #ifndef JUCE_FORCE_DEBUG
  175. //#define JUCE_FORCE_DEBUG 1
  176. #endif
  177. /** If this flag is enabled, the the jassert and jassertfalse macros will
  178. always use Logger::writeToLog() to write a message when an assertion happens.
  179. Enabling it will also leave this turned on in release builds. When it's disabled,
  180. however, the jassert and jassertfalse macros will not be compiled in a
  181. release build.
  182. @see jassert, jassertfalse, Logger
  183. */
  184. #ifndef JUCE_LOG_ASSERTIONS
  185. // #define JUCE_LOG_ASSERTIONS 1
  186. #endif
  187. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  188. which the ASIOAudioIODevice class can't be built. See the comments in the
  189. ASIOAudioIODevice class's header file for more info about this.
  190. (This only affects a Win32 build)
  191. */
  192. #ifndef JUCE_ASIO
  193. #define JUCE_ASIO 1
  194. #endif
  195. /** Comment out this macro to disable the Windows WASAPI audio device type.
  196. */
  197. #ifndef JUCE_WASAPI
  198. // #define JUCE_WASAPI 1
  199. #endif
  200. /** Comment out this macro to disable the Windows WASAPI audio device type.
  201. */
  202. #ifndef JUCE_DIRECTSOUND
  203. #define JUCE_DIRECTSOUND 1
  204. #endif
  205. /** Comment out this macro to disable building of ALSA device support on Linux.
  206. */
  207. #ifndef JUCE_ALSA
  208. #define JUCE_ALSA 1
  209. #endif
  210. /** Comment out this macro to disable building of JACK device support on Linux.
  211. */
  212. #ifndef JUCE_JACK
  213. #define JUCE_JACK 1
  214. #endif
  215. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  216. have the SDK installed.
  217. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  218. classes will be unavailable.
  219. On Windows, if you enable this, you'll need to have the QuickTime SDK
  220. installed, and its header files will need to be on your include path.
  221. */
  222. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  223. #define JUCE_QUICKTIME 1
  224. #endif
  225. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  226. have the appropriate headers and libraries available. If it's not enabled, the
  227. OpenGLComponent class will be unavailable.
  228. */
  229. #ifndef JUCE_OPENGL
  230. #define JUCE_OPENGL 1
  231. #endif
  232. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  233. If you're not going to need either of these formats, turn off the flags to
  234. avoid bloating your codebase with them.
  235. */
  236. #ifndef JUCE_USE_FLAC
  237. #define JUCE_USE_FLAC 1
  238. #endif
  239. #ifndef JUCE_USE_OGGVORBIS
  240. #define JUCE_USE_OGGVORBIS 1
  241. #endif
  242. /** This flag lets you enable the AudioCDBurner class. You might want to disable
  243. it to build without the MS SDK under windows.
  244. */
  245. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  246. #define JUCE_USE_CDBURNER 1
  247. #endif
  248. /** This flag lets you enable support for the AudioCDReader class. You might want to disable
  249. it to build without the MS SDK under windows.
  250. */
  251. #ifndef JUCE_USE_CDREADER
  252. #define JUCE_USE_CDREADER 1
  253. #endif
  254. /** Enabling this provides support for cameras, using the CameraDevice class
  255. */
  256. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  257. // #define JUCE_USE_CAMERA 1
  258. #endif
  259. /** Enabling this macro means that all regions that get repainted will have a coloured
  260. line drawn around them.
  261. This is handy if you're trying to optimise drawing, because it lets you easily see
  262. when anything is being repainted unnecessarily.
  263. */
  264. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  265. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  266. #endif
  267. /** Enable this under Linux to use Xinerama for multi-monitor support.
  268. */
  269. #ifndef JUCE_USE_XINERAMA
  270. #define JUCE_USE_XINERAMA 1
  271. #endif
  272. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  273. */
  274. #ifndef JUCE_USE_XSHM
  275. #define JUCE_USE_XSHM 1
  276. #endif
  277. /** Enabling this builds support for VST audio plugins.
  278. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  279. */
  280. #ifndef JUCE_PLUGINHOST_VST
  281. // #define JUCE_PLUGINHOST_VST 1
  282. #endif
  283. /** Enabling this builds support for AudioUnit audio plugins.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. // #define JUCE_PLUGINHOST_AU 1
  288. #endif
  289. /** Enabling this will avoid including any UI code in the build. This is handy for
  290. writing command-line utilities, e.g. on linux boxes which don't have some
  291. of the UI libraries installed.
  292. */
  293. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  294. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  295. #endif
  296. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** Setting this allows the build to use old Carbon libraries that will be
  302. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  303. reasons.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  309. codebase - you might need to use this if you're linking to some of these libraries
  310. yourself.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** Enable this to add extra memory-leak info to the new and delete operators.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** Enable this to turn on juce's internal catching of exceptions.
  334. Turning it off will avoid any exception catching. With it on, all exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. /** If this macro is set, the Juce String class will use unicode as its
  341. internal representation. If it isn't set, it'll use ANSI.
  342. */
  343. #ifndef JUCE_STRINGS_ARE_UNICODE
  344. #define JUCE_STRINGS_ARE_UNICODE 1
  345. #endif
  346. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  347. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  348. #undef JUCE_QUICKTIME
  349. #define JUCE_QUICKTIME 0
  350. #undef JUCE_OPENGL
  351. #define JUCE_OPENGL 0
  352. #undef JUCE_USE_CDBURNER
  353. #define JUCE_USE_CDBURNER 0
  354. #undef JUCE_USE_CDREADER
  355. #define JUCE_USE_CDREADER 0
  356. #undef JUCE_WEB_BROWSER
  357. #define JUCE_WEB_BROWSER 0
  358. #undef JUCE_PLUGINHOST_AU
  359. #define JUCE_PLUGINHOST_AU 0
  360. #undef JUCE_PLUGINHOST_VST
  361. #define JUCE_PLUGINHOST_VST 0
  362. #endif
  363. #endif
  364. /********* End of inlined file: juce_Config.h *********/
  365. #ifdef JUCE_NAMESPACE
  366. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  367. #define END_JUCE_NAMESPACE }
  368. #else
  369. #define BEGIN_JUCE_NAMESPACE
  370. #define END_JUCE_NAMESPACE
  371. #endif
  372. /********* Start of inlined file: juce_PlatformDefs.h *********/
  373. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  374. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  375. /* This file defines miscellaneous macros for debugging, assertions, etc.
  376. */
  377. #ifdef JUCE_FORCE_DEBUG
  378. #undef JUCE_DEBUG
  379. #if JUCE_FORCE_DEBUG
  380. #define JUCE_DEBUG 1
  381. #endif
  382. #endif
  383. /** This macro defines the C calling convention used as the standard for Juce calls. */
  384. #if JUCE_MSVC
  385. #define JUCE_CALLTYPE __stdcall
  386. #else
  387. #define JUCE_CALLTYPE
  388. #endif
  389. // Debugging and assertion macros
  390. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  391. #if JUCE_LOG_ASSERTIONS
  392. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  393. #elif defined (JUCE_DEBUG)
  394. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  395. #else
  396. #define juce_LogCurrentAssertion
  397. #endif
  398. #ifdef JUCE_DEBUG
  399. // If debugging is enabled..
  400. /** Writes a string to the standard error stream.
  401. This is only compiled in a debug build.
  402. @see Logger::outputDebugString
  403. */
  404. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  405. /** Printf's a string to the standard error stream.
  406. This is only compiled in a debug build.
  407. @see Logger::outputDebugString
  408. */
  409. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  410. // Assertions..
  411. #if JUCE_WINDOWS || DOXYGEN
  412. #if JUCE_USE_INTRINSICS
  413. #pragma intrinsic (__debugbreak)
  414. /** This will try to break the debugger if one is currently hosting this app.
  415. @see jassert()
  416. */
  417. #define juce_breakDebugger __debugbreak();
  418. #elif JUCE_GCC
  419. /** This will try to break the debugger if one is currently hosting this app.
  420. @see jassert()
  421. */
  422. #define juce_breakDebugger asm("int $3");
  423. #else
  424. /** This will try to break the debugger if one is currently hosting this app.
  425. @see jassert()
  426. */
  427. #define juce_breakDebugger { __asm int 3 }
  428. #endif
  429. #elif JUCE_MAC
  430. #define juce_breakDebugger Debugger();
  431. #elif JUCE_IPHONE
  432. #define juce_breakDebugger kill (0, SIGTRAP);
  433. #elif JUCE_LINUX
  434. #define juce_breakDebugger kill (0, SIGTRAP);
  435. #endif
  436. /** This will always cause an assertion failure.
  437. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  438. in juce_Config.h).
  439. @see jassert()
  440. */
  441. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  442. /** Platform-independent assertion macro.
  443. This gets optimised out when not being built with debugging turned on.
  444. Be careful not to call any functions within its arguments that are vital to
  445. the behaviour of the program, because these won't get called in the release
  446. build.
  447. @see jassertfalse
  448. */
  449. #define jassert(expression) { if (! (expression)) jassertfalse }
  450. #else
  451. // If debugging is disabled, these dummy debug and assertion macros are used..
  452. #define DBG(dbgtext)
  453. #define DBG_PRINTF(dbgprintf)
  454. #define jassertfalse { juce_LogCurrentAssertion }
  455. #if JUCE_LOG_ASSERTIONS
  456. #define jassert(expression) { if (! (expression)) jassertfalse }
  457. #else
  458. #define jassert(a) { }
  459. #endif
  460. #endif
  461. #ifndef DOXYGEN
  462. template <bool b> struct JuceStaticAssert;
  463. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  464. #endif
  465. /** A compile-time assertion macro.
  466. If the expression parameter is false, the macro will cause a compile error.
  467. */
  468. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  469. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  470. #define JUCE_TRY try
  471. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  472. object so they can be logged by the application if it wants to.
  473. */
  474. #define JUCE_CATCH_EXCEPTION \
  475. catch (const std::exception& e) \
  476. { \
  477. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  478. } \
  479. catch (...) \
  480. { \
  481. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  482. }
  483. #define JUCE_CATCH_ALL catch (...) {}
  484. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  485. #else
  486. #define JUCE_TRY
  487. #define JUCE_CATCH_EXCEPTION
  488. #define JUCE_CATCH_ALL
  489. #define JUCE_CATCH_ALL_ASSERT
  490. #endif
  491. // Macros for inlining.
  492. #if JUCE_MSVC
  493. /** A platform-independent way of forcing an inline function.
  494. Use the syntax: @code
  495. forcedinline void myfunction (int x)
  496. @endcode
  497. */
  498. #ifdef JUCE_DEBUG
  499. #define forcedinline __forceinline
  500. #else
  501. #define forcedinline inline
  502. #endif
  503. /** A platform-independent way of stopping the compiler inlining a function.
  504. Use the syntax: @code
  505. juce_noinline void myfunction (int x)
  506. @endcode
  507. */
  508. #define juce_noinline
  509. #else
  510. /** A platform-independent way of forcing an inline function.
  511. Use the syntax: @code
  512. forcedinline void myfunction (int x)
  513. @endcode
  514. */
  515. #ifndef JUCE_DEBUG
  516. #define forcedinline inline __attribute__((always_inline))
  517. #else
  518. #define forcedinline inline
  519. #endif
  520. /** A platform-independent way of stopping the compiler inlining a function.
  521. Use the syntax: @code
  522. juce_noinline void myfunction (int x)
  523. @endcode
  524. */
  525. #define juce_noinline __attribute__((noinline))
  526. #endif
  527. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  528. /********* End of inlined file: juce_PlatformDefs.h *********/
  529. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  530. #if JUCE_MSVC
  531. #pragma warning (push)
  532. #pragma warning (disable: 4514 4245 4100)
  533. #endif
  534. #include <cstdlib>
  535. #include <cstdarg>
  536. #include <climits>
  537. #include <cmath>
  538. #include <cwchar>
  539. #include <stdexcept>
  540. #include <typeinfo>
  541. #include <cstring>
  542. #include <cstdio>
  543. #if JUCE_USE_INTRINSICS
  544. #include <intrin.h>
  545. #endif
  546. #if JUCE_MAC
  547. #include <libkern/OSAtomic.h>
  548. #endif
  549. #if JUCE_LINUX
  550. #include <signal.h>
  551. #endif
  552. #if JUCE_MSVC && JUCE_DEBUG
  553. #include <crtdbg.h>
  554. #endif
  555. #if JUCE_MSVC
  556. #include <malloc.h>
  557. #pragma warning (pop)
  558. #endif
  559. // DLL building settings on Win32
  560. #if JUCE_MSVC
  561. #ifdef JUCE_DLL_BUILD
  562. #define JUCE_API __declspec (dllexport)
  563. #pragma warning (disable: 4251)
  564. #elif defined (JUCE_DLL)
  565. #define JUCE_API __declspec (dllimport)
  566. #pragma warning (disable: 4251)
  567. #endif
  568. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  569. #ifdef JUCE_DLL_BUILD
  570. #define JUCE_API __attribute__ ((visibility("default")))
  571. #endif
  572. #endif
  573. #ifndef JUCE_API
  574. /** This macro is added to all juce public class declarations. */
  575. #define JUCE_API
  576. #endif
  577. /** This macro is added to all juce public function declarations. */
  578. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  579. // Now include some basics that are needed by most of the Juce classes...
  580. BEGIN_JUCE_NAMESPACE
  581. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  582. #if JUCE_LOG_ASSERTIONS
  583. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  584. #endif
  585. /********* Start of inlined file: juce_Memory.h *********/
  586. #ifndef __JUCE_MEMORY_JUCEHEADER__
  587. #define __JUCE_MEMORY_JUCEHEADER__
  588. /*
  589. This file defines the various juce_malloc(), juce_free() macros that should be used in
  590. preference to the standard calls.
  591. */
  592. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  593. #ifndef JUCE_DLL
  594. // Win32 debug non-DLL versions..
  595. /** This should be used instead of calling malloc directly. */
  596. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  597. /** This should be used instead of calling calloc directly. */
  598. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  599. /** This should be used instead of calling realloc directly. */
  600. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  601. /** This should be used instead of calling free directly. */
  602. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  603. #else
  604. // Win32 debug DLL versions..
  605. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  606. // way all juce calls in the DLL and in the host API will all use the same allocator.
  607. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  608. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  609. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  610. extern JUCE_API void juce_DebugFree (void* const block);
  611. /** This should be used instead of calling malloc directly. */
  612. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  613. /** This should be used instead of calling calloc directly. */
  614. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  615. /** This should be used instead of calling realloc directly. */
  616. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  617. /** This should be used instead of calling free directly. */
  618. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  619. #endif
  620. #if ! defined (_AFXDLL)
  621. /** This macro can be added to classes to add extra debugging information to the memory
  622. allocated for them, so you can see the type of objects involved when there's a dump
  623. of leaked objects at program shutdown. (Only works on win32 at the moment).
  624. */
  625. #define juce_UseDebuggingNewOperator \
  626. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  627. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  628. static void operator delete (void* p) { juce_free (p); }
  629. #endif
  630. #elif defined (JUCE_DLL)
  631. // Win32 DLL (release) versions..
  632. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  633. // way all juce calls in the DLL and in the host API will all use the same allocator.
  634. extern JUCE_API void* juce_Malloc (const int size);
  635. extern JUCE_API void* juce_Calloc (const int size);
  636. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  637. extern JUCE_API void juce_Free (void* const block);
  638. /** This should be used instead of calling malloc directly. */
  639. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  640. /** This should be used instead of calling calloc directly. */
  641. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  642. /** This should be used instead of calling realloc directly. */
  643. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  644. /** This should be used instead of calling free directly. */
  645. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  646. #define juce_UseDebuggingNewOperator \
  647. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  648. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  649. static void operator delete (void* p) { juce_free (p); }
  650. #else
  651. // Mac, Linux and Win32 (release) versions..
  652. /** This should be used instead of calling malloc directly. */
  653. #define juce_malloc(numBytes) malloc (numBytes)
  654. /** This should be used instead of calling calloc directly. */
  655. #define juce_calloc(numBytes) calloc (1, numBytes)
  656. /** This should be used instead of calling realloc directly. */
  657. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  658. /** This should be used instead of calling free directly. */
  659. #define juce_free(location) free (location)
  660. #endif
  661. /** This macro can be added to classes to add extra debugging information to the memory
  662. allocated for them, so you can see the type of objects involved when there's a dump
  663. of leaked objects at program shutdown. (Only works on win32 at the moment).
  664. Note that if you create a class that inherits from a class that uses this macro,
  665. your class must also use the macro, otherwise you'll probably get compile errors
  666. because of ambiguous new operators.
  667. Most of the JUCE classes use it, so see these for examples of where it should go.
  668. */
  669. #ifndef juce_UseDebuggingNewOperator
  670. #define juce_UseDebuggingNewOperator
  671. #endif
  672. #if JUCE_MSVC
  673. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  674. E.g.
  675. @code
  676. juce_ThreadLocal int myVariable;
  677. @endcode
  678. */
  679. #define juce_ThreadLocal __declspec(thread)
  680. #else
  681. #define juce_ThreadLocal __thread
  682. #endif
  683. /** Clears a block of memory. */
  684. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  685. /** Clears a reference to a local structure. */
  686. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  687. /** A handy macro that calls delete on a pointer if it's non-zero, and
  688. then sets the pointer to null.
  689. */
  690. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  691. #endif // __JUCE_MEMORY_JUCEHEADER__
  692. /********* End of inlined file: juce_Memory.h *********/
  693. /********* Start of inlined file: juce_MathsFunctions.h *********/
  694. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  695. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  696. /*
  697. This file sets up some handy mathematical typdefs and functions.
  698. */
  699. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  700. /** A platform-independent 8-bit signed integer type. */
  701. typedef signed char int8;
  702. /** A platform-independent 8-bit unsigned integer type. */
  703. typedef unsigned char uint8;
  704. /** A platform-independent 16-bit signed integer type. */
  705. typedef signed short int16;
  706. /** A platform-independent 16-bit unsigned integer type. */
  707. typedef unsigned short uint16;
  708. /** A platform-independent 32-bit signed integer type. */
  709. typedef signed int int32;
  710. /** A platform-independent 32-bit unsigned integer type. */
  711. typedef unsigned int uint32;
  712. #if JUCE_MSVC
  713. /** A platform-independent 64-bit integer type. */
  714. typedef __int64 int64;
  715. /** A platform-independent 64-bit unsigned integer type. */
  716. typedef unsigned __int64 uint64;
  717. /** A platform-independent macro for writing 64-bit literals, needed because
  718. different compilers have different syntaxes for this.
  719. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  720. GCC, or 0x1000000000 for MSVC.
  721. */
  722. #define literal64bit(longLiteral) ((__int64) longLiteral)
  723. #else
  724. /** A platform-independent 64-bit integer type. */
  725. typedef long long int64;
  726. /** A platform-independent 64-bit unsigned integer type. */
  727. typedef unsigned long long uint64;
  728. /** A platform-independent macro for writing 64-bit literals, needed because
  729. different compilers have different syntaxes for this.
  730. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  731. GCC, or 0x1000000000 for MSVC.
  732. */
  733. #define literal64bit(longLiteral) (longLiteral##LL)
  734. #endif
  735. #if JUCE_64BIT
  736. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  737. typedef int64 pointer_sized_int;
  738. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  739. typedef uint64 pointer_sized_uint;
  740. #elif _MSC_VER >= 1300
  741. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  742. typedef _W64 int pointer_sized_int;
  743. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  744. typedef _W64 unsigned int pointer_sized_uint;
  745. #else
  746. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  747. typedef int pointer_sized_int;
  748. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  749. typedef unsigned int pointer_sized_uint;
  750. #endif
  751. /** A platform-independent unicode character type. */
  752. typedef wchar_t juce_wchar;
  753. // Some indispensible min/max functions
  754. /** Returns the larger of two values. */
  755. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  756. /** Returns the larger of two values. */
  757. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  758. /** Returns the larger of two values. */
  759. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  760. /** Returns the larger of two values. */
  761. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  762. /** Returns the larger of three values. */
  763. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  764. /** Returns the larger of three values. */
  765. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  766. /** Returns the larger of three values. */
  767. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  768. /** Returns the larger of three values. */
  769. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  770. /** Returns the larger of four values. */
  771. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  772. /** Returns the larger of four values. */
  773. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  774. /** Returns the larger of four values. */
  775. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  776. /** Returns the larger of four values. */
  777. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  778. /** Returns the smaller of two values. */
  779. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  780. /** Returns the smaller of two values. */
  781. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  782. /** Returns the smaller of two values. */
  783. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  784. /** Returns the smaller of two values. */
  785. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  786. /** Returns the smaller of three values. */
  787. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  788. /** Returns the smaller of three values. */
  789. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  790. /** Returns the smaller of three values. */
  791. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  792. /** Returns the smaller of three values. */
  793. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  794. /** Returns the smaller of four values. */
  795. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  796. /** Returns the smaller of four values. */
  797. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  798. /** Returns the smaller of four values. */
  799. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  800. /** Returns the smaller of four values. */
  801. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  802. /** Constrains a value to keep it within a given range.
  803. This will check that the specified value lies between the lower and upper bounds
  804. specified, and if not, will return the nearest value that would be in-range. Effectively,
  805. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  806. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  807. the results will be unpredictable.
  808. @param lowerLimit the minimum value to return
  809. @param upperLimit the maximum value to return
  810. @param valueToConstrain the value to try to return
  811. @returns the closest value to valueToConstrain which lies between lowerLimit
  812. and upperLimit (inclusive)
  813. @see jlimit0To, jmin, jmax
  814. */
  815. template <class Type>
  816. inline Type jlimit (const Type lowerLimit,
  817. const Type upperLimit,
  818. const Type valueToConstrain) throw()
  819. {
  820. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  821. return (valueToConstrain < lowerLimit) ? lowerLimit
  822. : ((valueToConstrain > upperLimit) ? upperLimit
  823. : valueToConstrain);
  824. }
  825. /** Handy function to swap two values over.
  826. */
  827. template <class Type>
  828. inline void swapVariables (Type& variable1, Type& variable2) throw()
  829. {
  830. const Type tempVal = variable1;
  831. variable1 = variable2;
  832. variable2 = tempVal;
  833. }
  834. /** Handy macro for getting the number of elements in a simple const C array.
  835. E.g.
  836. @code
  837. static int myArray[] = { 1, 2, 3 };
  838. int numElements = numElementsInArray (myArray) // returns 3
  839. @endcode
  840. */
  841. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  842. // Some useful maths functions that aren't always present with all compilers and build settings.
  843. #if JUCE_WINDOWS || defined (DOXYGEN)
  844. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  845. versions of these functions of various platforms and compilers. */
  846. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  847. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  848. versions of these functions of various platforms and compilers. */
  849. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  850. #else
  851. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  852. versions of these functions of various platforms and compilers. */
  853. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  854. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  855. versions of these functions of various platforms and compilers. */
  856. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  857. #endif
  858. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  859. /** A predefined value for Pi, at double-precision.
  860. @see float_Pi
  861. */
  862. const double double_Pi = 3.1415926535897932384626433832795;
  863. /** A predefined value for Pi, at sngle-precision.
  864. @see double_Pi
  865. */
  866. const float float_Pi = 3.14159265358979323846f;
  867. /** The isfinite() method seems to vary greatly between platforms, so this is a
  868. platform-independent macro for it.
  869. */
  870. #if JUCE_LINUX || JUCE_MAC || JUCE_IPHONE
  871. #define juce_isfinite(v) std::isfinite(v)
  872. #elif JUCE_WINDOWS && ! defined (isfinite)
  873. #define juce_isfinite(v) _finite(v)
  874. #else
  875. #define juce_isfinite(v) isfinite(v)
  876. #endif
  877. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  878. /********* End of inlined file: juce_MathsFunctions.h *********/
  879. /********* Start of inlined file: juce_DataConversions.h *********/
  880. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  881. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  882. #if JUCE_USE_INTRINSICS
  883. #pragma intrinsic (_byteswap_ulong)
  884. #endif
  885. // Endianness conversions..
  886. #if JUCE_IPHONE
  887. // a gcc compiler error seems to mean that these functions only work properly
  888. // on the iPhone if they are declared static..
  889. static forcedinline uint32 swapByteOrder (uint32 n) throw();
  890. static inline uint16 swapByteOrder (const uint16 n) throw();
  891. static inline uint64 swapByteOrder (const uint64 value) throw();
  892. #endif
  893. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  894. forcedinline uint32 swapByteOrder (uint32 n) throw()
  895. {
  896. #if JUCE_MAC || JUCE_IPHONE
  897. // Mac version
  898. return OSSwapInt32 (n);
  899. #elif JUCE_GCC
  900. // Inpenetrable GCC version..
  901. asm("bswap %%eax" : "=a"(n) : "a"(n));
  902. return n;
  903. #elif JUCE_USE_INTRINSICS
  904. // Win32 intrinsics version..
  905. return _byteswap_ulong (n);
  906. #else
  907. // Win32 version..
  908. __asm {
  909. mov eax, n
  910. bswap eax
  911. mov n, eax
  912. }
  913. return n;
  914. #endif
  915. }
  916. /** Swaps the byte-order of a 16-bit short. */
  917. inline uint16 swapByteOrder (const uint16 n) throw()
  918. {
  919. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  920. // Win32 intrinsics version..
  921. return (uint16) _byteswap_ushort (n);
  922. #else
  923. return (uint16) ((n << 8) | (n >> 8));
  924. #endif
  925. }
  926. inline uint64 swapByteOrder (const uint64 value) throw()
  927. {
  928. #if JUCE_MAC || JUCE_IPHONE
  929. return OSSwapInt64 (value);
  930. #elif JUCE_USE_INTRINSICS
  931. return _byteswap_uint64 (value);
  932. #else
  933. return (((int64) swapByteOrder ((uint32) value)) << 32)
  934. | swapByteOrder ((uint32) (value >> 32));
  935. #endif
  936. }
  937. #if JUCE_LITTLE_ENDIAN
  938. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  939. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  940. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  941. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  942. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  943. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  944. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  945. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  946. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  947. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  948. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  949. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  950. /** Turns 4 bytes into a little-endian integer. */
  951. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  952. /** Turns 2 bytes into a little-endian integer. */
  953. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  954. /** Turns 4 bytes into a big-endian integer. */
  955. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  956. /** Turns 2 bytes into a big-endian integer. */
  957. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  958. #else
  959. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  960. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  961. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  962. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  963. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  964. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  965. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  966. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  967. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  968. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  969. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  970. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  971. /** Turns 4 bytes into a little-endian integer. */
  972. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  973. /** Turns 2 bytes into a little-endian integer. */
  974. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  975. /** Turns 4 bytes into a big-endian integer. */
  976. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  977. /** Turns 2 bytes into a big-endian integer. */
  978. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  979. #endif
  980. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  981. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  982. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  983. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  984. /** Copies a 24-bit number to 3 little-endian bytes. */
  985. 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); }
  986. /** Copies a 24-bit number to 3 big-endian bytes. */
  987. 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); }
  988. /** Fast floating-point-to-integer conversion.
  989. This is faster than using the normal c++ cast to convert a double to an int, and
  990. it will round the value to the nearest integer, rather than rounding it down
  991. like the normal cast does.
  992. Note that this routine gets its speed at the expense of some accuracy, and when
  993. rounding values whose floating point component is exactly 0.5, odd numbers and
  994. even numbers will be rounded up or down differently. For a more accurate conversion,
  995. see roundDoubleToIntAccurate().
  996. */
  997. inline int roundDoubleToInt (const double value) throw()
  998. {
  999. union { int asInt[2]; double asDouble; } n;
  1000. n.asDouble = value + 6755399441055744.0;
  1001. #if JUCE_BIG_ENDIAN
  1002. return n.asInt [1];
  1003. #else
  1004. return n.asInt [0];
  1005. #endif
  1006. }
  1007. /** Fast floating-point-to-integer conversion.
  1008. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1009. fine for values above zero, but negative numbers are rounded the wrong way.
  1010. */
  1011. inline int roundDoubleToIntAccurate (const double value) throw()
  1012. {
  1013. return roundDoubleToInt (value + 1.5e-8);
  1014. }
  1015. /** Fast floating-point-to-integer conversion.
  1016. This is faster than using the normal c++ cast to convert a float to an int, and
  1017. it will round the value to the nearest integer, rather than rounding it down
  1018. like the normal cast does.
  1019. Note that this routine gets its speed at the expense of some accuracy, and when
  1020. rounding values whose floating point component is exactly 0.5, odd numbers and
  1021. even numbers will be rounded up or down differently.
  1022. */
  1023. inline int roundFloatToInt (const float value) throw()
  1024. {
  1025. union { int asInt[2]; double asDouble; } n;
  1026. n.asDouble = value + 6755399441055744.0;
  1027. #if JUCE_BIG_ENDIAN
  1028. return n.asInt [1];
  1029. #else
  1030. return n.asInt [0];
  1031. #endif
  1032. }
  1033. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  1034. /********* End of inlined file: juce_DataConversions.h *********/
  1035. /********* Start of inlined file: juce_Logger.h *********/
  1036. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1037. #define __JUCE_LOGGER_JUCEHEADER__
  1038. /********* Start of inlined file: juce_String.h *********/
  1039. #ifndef __JUCE_STRING_JUCEHEADER__
  1040. #define __JUCE_STRING_JUCEHEADER__
  1041. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1042. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1043. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1044. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1045. (in the default system encoding) as its internal representation.
  1046. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1047. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1048. literals in the T("abcd") macro, so that it all works nicely either way round.
  1049. */
  1050. #if JUCE_STRINGS_ARE_UNICODE
  1051. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1052. typedef juce_wchar tchar;
  1053. #define juce_tcharToWideChar(c) (c)
  1054. #else
  1055. #define JUCE_T(stringLiteral) (stringLiteral)
  1056. typedef char tchar;
  1057. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1058. #endif
  1059. #if ! JUCE_DONT_DEFINE_MACROS
  1060. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1061. or unicode.
  1062. If you write your string literals in the form T("xyz"), this will either be compiled
  1063. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1064. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1065. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1066. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1067. the juce/src directory) to avoid defining this macro. See the comments in
  1068. juce_withoutMacros.h for more info.
  1069. */
  1070. #define T(stringLiteral) JUCE_T(stringLiteral)
  1071. #endif
  1072. /**
  1073. A set of methods for manipulating characters and character strings, with
  1074. duplicate methods to handle 8-bit and unicode characters.
  1075. These are defined as wrappers around the basic C string handlers, to provide
  1076. a clean, cross-platform layer, (because various platforms differ in the
  1077. range of C library calls that they provide).
  1078. @see String
  1079. */
  1080. class JUCE_API CharacterFunctions
  1081. {
  1082. public:
  1083. static int length (const char* const s) throw();
  1084. static int length (const juce_wchar* const s) throw();
  1085. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1086. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1087. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1088. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1089. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1090. static void append (char* dest, const char* src) throw();
  1091. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1092. static int compare (const char* const s1, const char* const s2) throw();
  1093. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1094. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1095. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1096. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1097. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1098. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1099. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1100. static const char* find (const char* const haystack, const char* const needle) throw();
  1101. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1102. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1103. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1104. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1105. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1106. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1107. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1108. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1109. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1110. static int getIntValue (const char* const s) throw();
  1111. static int getIntValue (const juce_wchar* s) throw();
  1112. static int64 getInt64Value (const char* s) throw();
  1113. static int64 getInt64Value (const juce_wchar* s) throw();
  1114. static double getDoubleValue (const char* const s) throw();
  1115. static double getDoubleValue (const juce_wchar* const s) throw();
  1116. static char toUpperCase (const char character) throw();
  1117. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1118. static void toUpperCase (char* s) throw();
  1119. static void toUpperCase (juce_wchar* s) throw();
  1120. static bool isUpperCase (const char character) throw();
  1121. static bool isUpperCase (const juce_wchar character) throw();
  1122. static char toLowerCase (const char character) throw();
  1123. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1124. static void toLowerCase (char* s) throw();
  1125. static void toLowerCase (juce_wchar* s) throw();
  1126. static bool isLowerCase (const char character) throw();
  1127. static bool isLowerCase (const juce_wchar character) throw();
  1128. static bool isWhitespace (const char character) throw();
  1129. static bool isWhitespace (const juce_wchar character) throw();
  1130. static bool isDigit (const char character) throw();
  1131. static bool isDigit (const juce_wchar character) throw();
  1132. static bool isLetter (const char character) throw();
  1133. static bool isLetter (const juce_wchar character) throw();
  1134. static bool isLetterOrDigit (const char character) throw();
  1135. static bool isLetterOrDigit (const juce_wchar character) throw();
  1136. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1137. hex digit.
  1138. */
  1139. static int getHexDigitValue (const tchar digit) throw();
  1140. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1141. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1142. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1143. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1144. };
  1145. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1146. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1147. /**
  1148. The JUCE String class!
  1149. Using a reference-counted internal representation, these strings are fast
  1150. and efficient, and there are methods to do just about any operation you'll ever
  1151. dream of.
  1152. @see StringArray, StringPairArray
  1153. */
  1154. class JUCE_API String
  1155. {
  1156. public:
  1157. /** Creates an empty string.
  1158. @see empty
  1159. */
  1160. String() throw();
  1161. /** Creates a copy of another string. */
  1162. String (const String& other) throw();
  1163. /** Creates a string from a zero-terminated text string.
  1164. The string is assumed to be stored in the default system encoding.
  1165. */
  1166. String (const char* const text) throw();
  1167. /** Creates a string from an string of characters.
  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 char* const text,
  1172. const int maxChars) throw();
  1173. /** Creates a string from a zero-terminated unicode text string. */
  1174. String (const juce_wchar* const unicodeText) throw();
  1175. /** Creates a string from a unicode text string.
  1176. This will use up the the first maxChars characters of the string (or
  1177. less if the string is actually shorter)
  1178. */
  1179. String (const juce_wchar* const unicodeText,
  1180. const int maxChars) throw();
  1181. /** Creates a string from a single character. */
  1182. static const String charToString (const tchar character) throw();
  1183. /** Destructor. */
  1184. ~String() throw();
  1185. /** This is an empty string that can be used whenever one is needed.
  1186. It's better to use this than String() because it explains what's going on
  1187. and is more efficient.
  1188. */
  1189. static const String empty;
  1190. /** Generates a probably-unique 32-bit hashcode from this string. */
  1191. int hashCode() const throw();
  1192. /** Generates a probably-unique 64-bit hashcode from this string. */
  1193. int64 hashCode64() const throw();
  1194. /** Returns the number of characters in the string. */
  1195. int length() const throw();
  1196. // Assignment and concatenation operators..
  1197. /** Replaces this string's contents with another string. */
  1198. const String& operator= (const tchar* const other) throw();
  1199. /** Replaces this string's contents with another string. */
  1200. const String& operator= (const String& other) throw();
  1201. /** Appends another string at the end of this one. */
  1202. const String& operator+= (const tchar* const textToAppend) throw();
  1203. /** Appends another string at the end of this one. */
  1204. const String& operator+= (const String& stringToAppend) throw();
  1205. /** Appends a character at the end of this string. */
  1206. const String& operator+= (const char characterToAppend) throw();
  1207. /** Appends a character at the end of this string. */
  1208. const String& operator+= (const juce_wchar characterToAppend) throw();
  1209. /** Appends a string at the end of this one.
  1210. @param textToAppend the string to add
  1211. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1212. */
  1213. void append (const tchar* const textToAppend,
  1214. const int maxCharsToTake) throw();
  1215. /** Appends a string at the end of this one.
  1216. @returns the concatenated string
  1217. */
  1218. const String operator+ (const String& stringToAppend) const throw();
  1219. /** Appends a string at the end of this one.
  1220. @returns the concatenated string
  1221. */
  1222. const String operator+ (const tchar* const textToAppend) const throw();
  1223. /** Appends a character at the end of this one.
  1224. @returns the concatenated string
  1225. */
  1226. const String operator+ (const tchar characterToAppend) const throw();
  1227. /** Appends a character at the end of this string. */
  1228. String& operator<< (const char n) throw();
  1229. /** Appends a character at the end of this string. */
  1230. String& operator<< (const juce_wchar n) throw();
  1231. /** Appends another string at the end of this one. */
  1232. String& operator<< (const char* const text) throw();
  1233. /** Appends another string at the end of this one. */
  1234. String& operator<< (const juce_wchar* const text) throw();
  1235. /** Appends another string at the end of this one. */
  1236. String& operator<< (const String& text) throw();
  1237. /** Appends a decimal number at the end of this string. */
  1238. String& operator<< (const short number) throw();
  1239. /** Appends a decimal number at the end of this string. */
  1240. String& operator<< (const int number) throw();
  1241. /** Appends a decimal number at the end of this string. */
  1242. String& operator<< (const unsigned int number) throw();
  1243. /** Appends a decimal number at the end of this string. */
  1244. String& operator<< (const long number) throw();
  1245. /** Appends a decimal number at the end of this string. */
  1246. String& operator<< (const unsigned long number) throw();
  1247. /** Appends a decimal number at the end of this string. */
  1248. String& operator<< (const float number) throw();
  1249. /** Appends a decimal number at the end of this string. */
  1250. String& operator<< (const double number) throw();
  1251. // Comparison methods..
  1252. /** Returns true if the string contains no characters.
  1253. Note that there's also an isNotEmpty() method to help write readable code.
  1254. @see containsNonWhitespaceChars()
  1255. */
  1256. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1257. /** Returns true if the string contains at least one character.
  1258. Note that there's also an isEmpty() method to help write readable code.
  1259. @see containsNonWhitespaceChars()
  1260. */
  1261. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1262. /** Case-sensitive comparison with another string. */
  1263. bool operator== (const String& other) const throw();
  1264. /** Case-sensitive comparison with another string. */
  1265. bool operator== (const tchar* const other) const throw();
  1266. /** Case-sensitive comparison with another string. */
  1267. bool operator!= (const String& other) const throw();
  1268. /** Case-sensitive comparison with another string. */
  1269. bool operator!= (const tchar* const other) const throw();
  1270. /** Case-insensitive comparison with another string. */
  1271. bool equalsIgnoreCase (const String& other) const throw();
  1272. /** Case-insensitive comparison with another string. */
  1273. bool equalsIgnoreCase (const tchar* const other) const throw();
  1274. /** Case-sensitive comparison with another string. */
  1275. bool operator> (const String& other) const throw();
  1276. /** Case-sensitive comparison with another string. */
  1277. bool operator< (const tchar* const other) const throw();
  1278. /** Case-sensitive comparison with another string. */
  1279. bool operator>= (const String& other) const throw();
  1280. /** Case-sensitive comparison with another string. */
  1281. bool operator<= (const tchar* const other) const throw();
  1282. /** Case-sensitive 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 compare (const tchar* const other) const throw();
  1288. /** Case-insensitive comparison with another string.
  1289. @returns 0 if the two strings are identical; negative if this string
  1290. comes before the other one alphabetically, or positive if it
  1291. comes after it.
  1292. */
  1293. int compareIgnoreCase (const tchar* const other) const throw();
  1294. /** Lexicographic comparison with another string.
  1295. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1296. characters, making it good for sorting human-readable strings.
  1297. @returns 0 if the two strings are identical; negative if this string
  1298. comes before the other one alphabetically, or positive if it
  1299. comes after it.
  1300. */
  1301. int compareLexicographically (const tchar* const other) const throw();
  1302. /** Tests whether the string begins with another string.
  1303. Uses a case-sensitive comparison.
  1304. */
  1305. bool startsWith (const tchar* const text) const throw();
  1306. /** Tests whether the string begins with a particular character.
  1307. Uses a case-sensitive comparison.
  1308. */
  1309. bool startsWithChar (const tchar character) const throw();
  1310. /** Tests whether the string begins with another string.
  1311. Uses a case-insensitive comparison.
  1312. */
  1313. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1314. /** Tests whether the string ends with another string.
  1315. Uses a case-sensitive comparison.
  1316. */
  1317. bool endsWith (const tchar* const text) const throw();
  1318. /** Tests whether the string ends with a particular character.
  1319. Uses a case-sensitive comparison.
  1320. */
  1321. bool endsWithChar (const tchar character) const throw();
  1322. /** Tests whether the string ends with another string.
  1323. Uses a case-insensitive comparison.
  1324. */
  1325. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1326. /** Tests whether the string contains another substring.
  1327. Uses a case-sensitive comparison.
  1328. */
  1329. bool contains (const tchar* const text) const throw();
  1330. /** Tests whether the string contains a particular character.
  1331. Uses a case-sensitive comparison.
  1332. */
  1333. bool containsChar (const tchar character) const throw();
  1334. /** Tests whether the string contains another substring.
  1335. Uses a case-insensitive comparison.
  1336. */
  1337. bool containsIgnoreCase (const tchar* const text) 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 indexOfWholeWord, containsWholeWordIgnoreCase
  1342. */
  1343. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1344. /** Tests whether the string contains another substring as a distict word.
  1345. @returns true if the string contains this word, surrounded by
  1346. non-alphanumeric characters
  1347. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1348. */
  1349. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1350. /** Finds an instance of another substring if it exists as a distict word.
  1351. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1352. then this will return the index of the start of the substring. If it isn't
  1353. found, then it will return -1
  1354. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1355. */
  1356. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1357. /** Finds an instance of another substring if it exists as a distict word.
  1358. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1359. then this will return the index of the start of the substring. If it isn't
  1360. found, then it will return -1
  1361. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1362. */
  1363. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1364. /** Looks for any of a set of characters in the string.
  1365. Uses a case-sensitive comparison.
  1366. @returns true if the string contains any of the characters from
  1367. the string that is passed in.
  1368. */
  1369. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1370. /** Looks for a set of characters in the string.
  1371. Uses a case-sensitive comparison.
  1372. @returns true if the all the characters in the string are also found in the
  1373. string that is passed in.
  1374. */
  1375. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1376. /** Returns true if this string contains any non-whitespace characters.
  1377. This will return false if the string contains only whitespace characters, or
  1378. if it's empty.
  1379. It is equivalent to calling "myString.trim().isNotEmpty()".
  1380. */
  1381. bool containsNonWhitespaceChars() const throw();
  1382. /** Returns true if the string matches this simple wildcard expression.
  1383. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1384. This isn't a full-blown regex though! The only wildcard characters supported
  1385. are "*" and "?". It's mainly intended for filename pattern matching.
  1386. */
  1387. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1388. // Substring location methods..
  1389. /** Searches for a character inside this string.
  1390. Uses a case-sensitive comparison.
  1391. @returns the index of the first occurrence of the character in this
  1392. string, or -1 if it's not found.
  1393. */
  1394. int indexOfChar (const tchar characterToLookFor) const throw();
  1395. /** Searches for a character inside this string.
  1396. Uses a case-sensitive comparison.
  1397. @param startIndex the index from which the search should proceed
  1398. @param characterToLookFor the character to look for
  1399. @returns the index of the first occurrence of the character in this
  1400. string, or -1 if it's not found.
  1401. */
  1402. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1403. /** Returns the index of the first character that matches one of the characters
  1404. passed-in to this method.
  1405. This scans the string, beginning from the startIndex supplied, and if it finds
  1406. a character that appears in the string charactersToLookFor, it returns its index.
  1407. If none of these characters are found, it returns -1.
  1408. If ignoreCase is true, the comparison will be case-insensitive.
  1409. @see indexOfChar, lastIndexOfAnyOf
  1410. */
  1411. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1412. const int startIndex = 0,
  1413. const bool ignoreCase = false) const throw();
  1414. /** Searches for a substring within this string.
  1415. Uses a case-sensitive comparison.
  1416. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1417. */
  1418. int indexOf (const tchar* const text) const throw();
  1419. /** Searches for a substring within this string.
  1420. Uses a case-sensitive comparison.
  1421. @param startIndex the index from which the search should proceed
  1422. @param textToLookFor the string to search for
  1423. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1424. */
  1425. int indexOf (const int startIndex,
  1426. const tchar* const textToLookFor) const throw();
  1427. /** Searches for a substring within this string.
  1428. Uses a case-insensitive comparison.
  1429. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1430. */
  1431. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1432. /** Searches for a substring within this string.
  1433. Uses a case-insensitive comparison.
  1434. @param startIndex the index from which the search should proceed
  1435. @param textToLookFor the string to search for
  1436. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1437. */
  1438. int indexOfIgnoreCase (const int startIndex,
  1439. const tchar* const textToLookFor) const throw();
  1440. /** Searches for a character inside this string (working backwards from the end of the string).
  1441. Uses a case-sensitive comparison.
  1442. @returns the index of the last occurrence of the character in this
  1443. string, or -1 if it's not found.
  1444. */
  1445. int lastIndexOfChar (const tchar character) const throw();
  1446. /** Searches for a substring inside this string (working backwards from the end of the string).
  1447. Uses a case-sensitive 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 lastIndexOf (const tchar* const textToLookFor) const throw();
  1452. /** Searches for a substring inside this string (working backwards from the end of the string).
  1453. Uses a case-insensitive comparison.
  1454. @returns the index of the start of the last occurrence of the
  1455. substring within this string, or -1 if it's not found.
  1456. */
  1457. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1458. /** Returns the index of the last character in this string that matches one of the
  1459. characters passed-in to this method.
  1460. This scans the string backwards, starting from its end, and if it finds
  1461. a character that appears in the string charactersToLookFor, it returns its index.
  1462. If none of these characters are found, it returns -1.
  1463. If ignoreCase is true, the comparison will be case-insensitive.
  1464. @see lastIndexOf, indexOfAnyOf
  1465. */
  1466. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1467. const bool ignoreCase = false) const throw();
  1468. // Substring extraction and manipulation methods..
  1469. /** Returns the character at this index in the string.
  1470. No checks are made to see if the index is within a valid range, so be careful!
  1471. */
  1472. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1473. /** Returns a character from the string such that it can also be altered.
  1474. This can be used as a way of easily changing characters in the string.
  1475. Note that the index passed-in is not checked to see whether it's in-range, so
  1476. be careful when using this.
  1477. */
  1478. tchar& operator[] (const int index) throw();
  1479. /** Returns the final character of the string.
  1480. If the string is empty this will return 0.
  1481. */
  1482. tchar getLastCharacter() const throw();
  1483. /** Returns a subsection of the string.
  1484. If the range specified is beyond the limits of the string, as much as
  1485. possible is returned.
  1486. @param startIndex the index of the start of the substring needed
  1487. @param endIndex all characters from startIndex up to (but not including)
  1488. this index are returned
  1489. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1490. */
  1491. const String substring (int startIndex,
  1492. int endIndex) const throw();
  1493. /** Returns a section of the string, starting from a given position.
  1494. @param startIndex the first character to include. If this is beyond the end
  1495. of the string, an empty string is returned. If it is zero or
  1496. less, the whole string is returned.
  1497. @returns the substring from startIndex up to the end of the string
  1498. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1499. */
  1500. const String substring (const int startIndex) const throw();
  1501. /** Returns a version of this string with a number of characters removed
  1502. from the end.
  1503. @param numberToDrop the number of characters to drop from the end of the
  1504. string. If this is greater than the length of the string,
  1505. an empty string will be returned. If zero or less, the
  1506. original string will be returned.
  1507. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1508. */
  1509. const String dropLastCharacters (const int numberToDrop) const throw();
  1510. /** Returns a number of characters from the end of the string.
  1511. This returns the last numCharacters characters from the end of the string. If the
  1512. string is shorter than numCharacters, the whole string is returned.
  1513. @see substring, dropLastCharacters, getLastCharacter
  1514. */
  1515. const String getLastCharacters (const int numCharacters) const throw();
  1516. /** Returns a section of the string starting from a given substring.
  1517. This will search for the first occurrence of the given substring, and
  1518. return the section of the string starting from the point where this is
  1519. found (optionally not including the substring itself).
  1520. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1521. fromFirstOccurrenceOf ("34", false) would return "56".
  1522. If the substring isn't found, the method will return an empty string.
  1523. If ignoreCase is true, the comparison will be case-insensitive.
  1524. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1525. */
  1526. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1527. const bool includeSubStringInResult,
  1528. const bool ignoreCase) const throw();
  1529. /** Returns a section of the string starting from the last occurrence of a given substring.
  1530. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1531. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1532. return the whole of the original string.
  1533. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1534. */
  1535. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1536. const bool includeSubStringInResult,
  1537. const bool ignoreCase) const throw();
  1538. /** Returns the start of this string, up to the first occurrence of a substring.
  1539. This will search for the first occurrence of a given substring, and then
  1540. return a copy of the string, up to the position of this substring,
  1541. optionally including or excluding the substring itself in the result.
  1542. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1543. upTo ("34", true) would return "1234".
  1544. If the substring isn't found, this will return the whole of the original string.
  1545. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1546. */
  1547. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1548. const bool includeSubStringInResult,
  1549. const bool ignoreCase) const throw();
  1550. /** Returns the start of this string, up to the last occurrence of a substring.
  1551. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1552. If the substring isn't found, this will return an empty string.
  1553. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1554. */
  1555. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1556. const bool includeSubStringInResult,
  1557. const bool ignoreCase) const throw();
  1558. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1559. const String trim() const throw();
  1560. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1561. const String trimStart() const throw();
  1562. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1563. const String trimEnd() const throw();
  1564. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1565. Characters are removed from the start of the string until it finds one that is not in the
  1566. specified set, and then it stops.
  1567. @param charactersToTrim the set of characters to remove. This must not be null.
  1568. @see trim, trimStart, trimCharactersAtEnd
  1569. */
  1570. const String trimCharactersAtStart (const tchar* charactersToTrim) const throw();
  1571. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1572. Characters are removed from the end of the string until it finds one that is not in the
  1573. specified set, and then it stops.
  1574. @param charactersToTrim the set of characters to remove. This must not be null.
  1575. @see trim, trimEnd, trimCharactersAtStart
  1576. */
  1577. const String trimCharactersAtEnd (const tchar* charactersToTrim) const throw();
  1578. /** Returns an upper-case version of this string. */
  1579. const String toUpperCase() const throw();
  1580. /** Returns an lower-case version of this string. */
  1581. const String toLowerCase() const throw();
  1582. /** Replaces a sub-section of the string with another string.
  1583. This will return a copy of this string, with a set of characters
  1584. from startIndex to startIndex + numCharsToReplace removed, and with
  1585. a new string inserted in their place.
  1586. Note that this is a const method, and won't alter the string itself.
  1587. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1588. it will be constrained to a valid range.
  1589. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1590. characters will be taken out.
  1591. @param stringToInsert the new string to insert at startIndex after the characters have been
  1592. removed.
  1593. */
  1594. const String replaceSection (int startIndex,
  1595. int numCharactersToReplace,
  1596. const tchar* const stringToInsert) const throw();
  1597. /** Replaces all occurrences of a substring with another string.
  1598. Returns a copy of this string, with any occurrences of stringToReplace
  1599. swapped for stringToInsertInstead.
  1600. Note that this is a const method, and won't alter the string itself.
  1601. */
  1602. const String replace (const tchar* const stringToReplace,
  1603. const tchar* const stringToInsertInstead,
  1604. const bool ignoreCase = false) const throw();
  1605. /** Returns a string with all occurrences of a character replaced with a different one. */
  1606. const String replaceCharacter (const tchar characterToReplace,
  1607. const tchar characterToInsertInstead) const throw();
  1608. /** Replaces a set of characters with another set.
  1609. Returns a string in which each character from charactersToReplace has been replaced
  1610. by the character at the equivalent position in newCharacters (so the two strings
  1611. passed in must be the same length).
  1612. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1613. Note that this is a const method, and won't affect the string itself.
  1614. */
  1615. const String replaceCharacters (const String& charactersToReplace,
  1616. const tchar* const charactersToInsertInstead) const throw();
  1617. /** Returns a version of this string that only retains a fixed set of characters.
  1618. This will return a copy of this string, omitting any characters which are not
  1619. found in the string passed-in.
  1620. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1621. Note that this is a const method, and won't alter the string itself.
  1622. */
  1623. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1624. /** Returns a version of this string with a set of characters removed.
  1625. This will return a copy of this string, omitting any characters which are
  1626. found in the string passed-in.
  1627. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1628. Note that this is a const method, and won't alter the string itself.
  1629. */
  1630. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1631. /** Returns a section from the start of the string that only contains a certain set of characters.
  1632. This returns the leftmost section of the string, up to (and not including) the
  1633. first character that doesn't appear in the string passed in.
  1634. */
  1635. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1636. /** Returns a section from the start of the string that only contains a certain set of characters.
  1637. This returns the leftmost section of the string, up to (and not including) the
  1638. first character that occurs in the string passed in.
  1639. */
  1640. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1641. /** Checks whether the string might be in quotation marks.
  1642. @returns true if the string begins with a quote character (either a double or single quote).
  1643. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1644. @see unquoted, quoted
  1645. */
  1646. bool isQuotedString() const throw();
  1647. /** Removes quotation marks from around the string, (if there are any).
  1648. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1649. at the ends of the string are not affected. If there aren't any quotes, the original string
  1650. is returned.
  1651. Note that this is a const method, and won't alter the string itself.
  1652. @see isQuotedString, quoted
  1653. */
  1654. const String unquoted() const throw();
  1655. /** Adds quotation marks around a string.
  1656. This will return a copy of the string with a quote at the start and end, (but won't
  1657. add the quote if there's already one there, so it's safe to call this on strings that
  1658. may already have quotes around them).
  1659. Note that this is a const method, and won't alter the string itself.
  1660. @param quoteCharacter the character to add at the start and end
  1661. @see isQuotedString, unquoted
  1662. */
  1663. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1664. /** Writes text into this string, using printf style-arguments.
  1665. This will replace the contents of the string with the output of this
  1666. formatted printf.
  1667. Note that using the %s token with a juce string is probably a bad idea, as
  1668. this may expect differect encodings on different platforms.
  1669. @see formatted
  1670. */
  1671. void printf (const tchar* const format, ...) throw();
  1672. /** Returns a string, created using arguments in the style of printf.
  1673. This will return a string which is the result of a sprintf using the
  1674. arguments passed-in.
  1675. Note that using the %s token with a juce string is probably a bad idea, as
  1676. this may expect differect encodings on different platforms.
  1677. @see printf, vprintf
  1678. */
  1679. static const String formatted (const tchar* const format, ...) throw();
  1680. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1681. This will replace the contents of the string with the output of this
  1682. formatted printf. Used by other methods, this is public in case it's
  1683. useful for other purposes where you want to pass a va_list through directly.
  1684. Note that using the %s token with a juce string is probably a bad idea, as
  1685. this may expect differect encodings on different platforms.
  1686. @see printf, formatted
  1687. */
  1688. void vprintf (const tchar* const format, va_list& args) throw();
  1689. /** Creates a string which is a version of a string repeated and joined together.
  1690. @param stringToRepeat the string to repeat
  1691. @param numberOfTimesToRepeat how many times to repeat it
  1692. */
  1693. static const String repeatedString (const tchar* const stringToRepeat,
  1694. int numberOfTimesToRepeat) throw();
  1695. /** Creates a string from data in an unknown format.
  1696. This looks at some binary data and tries to guess whether it's Unicode
  1697. or 8-bit characters, then returns a string that represents it correctly.
  1698. Should be able to handle Unicode endianness correctly, by looking at
  1699. the first two bytes.
  1700. */
  1701. static const String createStringFromData (const void* const data,
  1702. const int size) throw();
  1703. // Numeric conversions..
  1704. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1705. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1706. */
  1707. explicit String (const int decimalInteger) throw();
  1708. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1709. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1710. */
  1711. explicit String (const unsigned int decimalInteger) throw();
  1712. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1713. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1714. */
  1715. explicit String (const short decimalInteger) throw();
  1716. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1717. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1718. */
  1719. explicit String (const unsigned short decimalInteger) throw();
  1720. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1721. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1722. */
  1723. explicit String (const int64 largeIntegerValue) throw();
  1724. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1725. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1726. */
  1727. explicit String (const uint64 largeIntegerValue) throw();
  1728. /** Creates a string representing this floating-point number.
  1729. @param floatValue the value to convert to a string
  1730. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1731. decimal places, and will not use exponent notation. If 0 or
  1732. less, it will use exponent notation if necessary.
  1733. @see getDoubleValue, getIntValue
  1734. */
  1735. explicit String (const float floatValue,
  1736. const int numberOfDecimalPlaces = 0) throw();
  1737. /** Creates a string representing this floating-point number.
  1738. @param doubleValue the value to convert to a string
  1739. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1740. decimal places, and will not use exponent notation. If 0 or
  1741. less, it will use exponent notation if necessary.
  1742. @see getFloatValue, getIntValue
  1743. */
  1744. explicit String (const double doubleValue,
  1745. const int numberOfDecimalPlaces = 0) throw();
  1746. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1747. @returns the value of the string as a 32 bit signed base-10 integer.
  1748. @see getTrailingIntValue, getHexValue32, getHexValue64
  1749. */
  1750. int getIntValue() const throw();
  1751. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1752. @returns the value of the string as a 64 bit signed base-10 integer.
  1753. */
  1754. int64 getLargeIntValue() const throw();
  1755. /** Parses a decimal number from the end of the string.
  1756. This will look for a value at the end of the string.
  1757. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1758. Negative numbers are not handled, so "xyz-5" returns 5.
  1759. @see getIntValue
  1760. */
  1761. int getTrailingIntValue() const throw();
  1762. /** Parses this string as a floating point number.
  1763. @returns the value of the string as a 32-bit floating point value.
  1764. @see getDoubleValue
  1765. */
  1766. float getFloatValue() const throw();
  1767. /** Parses this string as a floating point number.
  1768. @returns the value of the string as a 64-bit floating point value.
  1769. @see getFloatValue
  1770. */
  1771. double getDoubleValue() const throw();
  1772. /** Parses the string as a hexadecimal number.
  1773. Non-hexadecimal characters in the string are ignored.
  1774. If the string contains too many characters, then the lowest significant
  1775. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1776. @returns a 32-bit number which is the value of the string in hex.
  1777. */
  1778. int getHexValue32() const throw();
  1779. /** Parses the string as a hexadecimal number.
  1780. Non-hexadecimal characters in the string are ignored.
  1781. If the string contains too many characters, then the lowest significant
  1782. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1783. @returns a 64-bit number which is the value of the string in hex.
  1784. */
  1785. int64 getHexValue64() const throw();
  1786. /** Creates a string representing this 32-bit value in hexadecimal. */
  1787. static const String toHexString (const int number) throw();
  1788. /** Creates a string representing this 64-bit value in hexadecimal. */
  1789. static const String toHexString (const int64 number) throw();
  1790. /** Creates a string representing this 16-bit value in hexadecimal. */
  1791. static const String toHexString (const short number) throw();
  1792. /** Creates a string containing a hex dump of a block of binary data.
  1793. @param data the binary data to use as input
  1794. @param size how many bytes of data to use
  1795. @param groupSize how many bytes are grouped together before inserting a
  1796. space into the output. e.g. group size 0 has no spaces,
  1797. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1798. like "bea1 c2ff".
  1799. */
  1800. static const String toHexString (const unsigned char* data,
  1801. const int size,
  1802. const int groupSize = 1) throw();
  1803. // Casting to character arrays..
  1804. #if JUCE_STRINGS_ARE_UNICODE
  1805. /** Returns a version of this string using the default 8-bit system encoding.
  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. operator const char*() const throw();
  1811. /** Returns a unicode version of this string.
  1812. Because it returns a reference to the string's internal data, the pointer
  1813. that is returned must not be stored anywhere, as it can be deleted whenever the
  1814. string changes.
  1815. */
  1816. inline operator const juce_wchar*() const throw() { return text->text; }
  1817. #else
  1818. /** Returns a version of this string using the default 8-bit system encoding.
  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. inline operator const char*() const throw() { return text->text; }
  1824. /** Returns a unicode version of this string.
  1825. Because it returns a reference to the string's internal data, the pointer
  1826. that is returned must not be stored anywhere, as it can be deleted whenever the
  1827. string changes.
  1828. */
  1829. operator const juce_wchar*() const throw();
  1830. #endif
  1831. /** Copies the string to a buffer.
  1832. @param destBuffer the place to copy it to
  1833. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1834. not including the tailing zero, so this shouldn't be
  1835. larger than the size of your destination buffer - 1
  1836. */
  1837. void copyToBuffer (char* const destBuffer,
  1838. const int maxCharsToCopy) const throw();
  1839. /** Copies the string to a unicode buffer.
  1840. @param destBuffer the place to copy it to
  1841. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1842. not including the tailing zero, so this shouldn't be
  1843. larger than the size of your destination buffer - 1
  1844. */
  1845. void copyToBuffer (juce_wchar* const destBuffer,
  1846. const int maxCharsToCopy) const throw();
  1847. /** Copies the string to a buffer as UTF-8 characters.
  1848. Returns the number of bytes copied to the buffer, including the terminating null
  1849. character.
  1850. @param destBuffer the place to copy it to; if this is a null pointer,
  1851. the method just returns the number of bytes required
  1852. (including the terminating null character).
  1853. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1854. string won't fit, it'll put in as many as it can while
  1855. still allowing for a terminating null char at the end,
  1856. and will return the number of bytes that were actually
  1857. used. If this value is < 0, no limit is used.
  1858. */
  1859. int copyToUTF8 (uint8* const destBuffer, const int maxBufferSizeBytes = 0x7fffffff) const throw();
  1860. /** Returns a pointer to a UTF-8 version of this string.
  1861. Because it returns a reference to the string's internal data, the pointer
  1862. that is returned must not be stored anywhere, as it can be deleted whenever the
  1863. string changes.
  1864. */
  1865. const char* toUTF8() const throw();
  1866. /** Creates a String from a UTF-8 encoded buffer.
  1867. If the size is < 0, it'll keep reading until it hits a zero.
  1868. */
  1869. static const String fromUTF8 (const uint8* const utf8buffer,
  1870. int bufferSizeBytes = -1) throw();
  1871. /** Increases the string's internally allocated storage.
  1872. Although the string's contents won't be affected by this call, it will
  1873. increase the amount of memory allocated internally for the string to grow into.
  1874. If you're about to make a large number of calls to methods such
  1875. as += or <<, it's more efficient to preallocate enough extra space
  1876. beforehand, so that these methods won't have to keep resizing the string
  1877. to append the extra characters.
  1878. @param numCharsNeeded the number of characters to allocate storage for. If this
  1879. value is less than the currently allocated size, it will
  1880. have no effect.
  1881. */
  1882. void preallocateStorage (const int numCharsNeeded) throw();
  1883. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1884. private:
  1885. struct InternalRefCountedStringHolder
  1886. {
  1887. int refCount;
  1888. int allocatedNumChars;
  1889. #if JUCE_STRINGS_ARE_UNICODE
  1890. wchar_t text[1];
  1891. #else
  1892. char text[1];
  1893. #endif
  1894. };
  1895. InternalRefCountedStringHolder* text;
  1896. static InternalRefCountedStringHolder emptyString;
  1897. // internal constructor that preallocates a certain amount of memory
  1898. String (const int numChars, const int dummyVariable) throw();
  1899. void deleteInternal() throw();
  1900. void createInternal (const int numChars) throw();
  1901. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1902. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1903. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1904. void dupeInternalIfMultiplyReferenced() throw();
  1905. };
  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 char* const string1,
  1911. const String& string2) throw();
  1912. /** Global operator to allow a String to be appended to a string literal.
  1913. This allows the use of expressions such as "abc" + String (x)
  1914. @see String
  1915. */
  1916. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1917. const String& string2) throw();
  1918. #endif // __JUCE_STRING_JUCEHEADER__
  1919. /********* End of inlined file: juce_String.h *********/
  1920. /**
  1921. Acts as an application-wide logging class.
  1922. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1923. method and this will then be used by all calls to writeToLog.
  1924. The logger class also contains methods for writing messages to the debugger's
  1925. output stream.
  1926. @see FileLogger
  1927. */
  1928. class JUCE_API Logger
  1929. {
  1930. public:
  1931. /** Destructor. */
  1932. virtual ~Logger();
  1933. /** Sets the current logging class to use.
  1934. Note that the object passed in won't be deleted when no longer needed.
  1935. A null pointer can be passed-in to disable any logging.
  1936. If deleteOldLogger is set to true, the existing logger will be
  1937. deleted (if there is one).
  1938. */
  1939. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1940. const bool deleteOldLogger = false);
  1941. /** Writes a string to the current logger.
  1942. This will pass the string to the logger's logMessage() method if a logger
  1943. has been set.
  1944. @see logMessage
  1945. */
  1946. static void JUCE_CALLTYPE writeToLog (const String& message);
  1947. /** Writes a message to the standard error stream.
  1948. This can be called directly, or by using the DBG() macro in
  1949. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1950. */
  1951. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1952. /** Writes a message to the standard error stream.
  1953. This can be called directly, or by using the DBG_PRINTF() macro in
  1954. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1955. */
  1956. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1957. protected:
  1958. Logger();
  1959. /** This is overloaded by subclasses to implement custom logging behaviour.
  1960. @see setCurrentLogger
  1961. */
  1962. virtual void logMessage (const String& message) = 0;
  1963. };
  1964. #endif // __JUCE_LOGGER_JUCEHEADER__
  1965. /********* End of inlined file: juce_Logger.h *********/
  1966. END_JUCE_NAMESPACE
  1967. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1968. /********* End of inlined file: juce_StandardHeader.h *********/
  1969. BEGIN_JUCE_NAMESPACE
  1970. #if JUCE_MSVC
  1971. // this is set explicitly in case the app is using a different packing size.
  1972. #pragma pack (push, 8)
  1973. #pragma warning (push)
  1974. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1975. #endif
  1976. #if JUCE_MAC || JUCE_IPHONE
  1977. #pragma align=natural
  1978. #endif
  1979. #define JUCE_PUBLIC_INCLUDES
  1980. // this is where all the class header files get brought in..
  1981. /********* Start of inlined file: juce_core_includes.h *********/
  1982. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1983. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1984. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1985. /********* Start of inlined file: juce_Atomic.h *********/
  1986. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1987. #define __JUCE_ATOMIC_JUCEHEADER__
  1988. // Atomic increment/decrement operations..
  1989. #if (JUCE_MAC || JUCE_IPHONE) && ! DOXYGEN
  1990. #include <libkern/OSAtomic.h>
  1991. static forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1992. static forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1993. static forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1994. static forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1995. #elif JUCE_GCC
  1996. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1997. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1998. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1999. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  2000. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  2001. #else
  2002. /** Increments an integer in a thread-safe way. */
  2003. forcedinline void atomicIncrement (int& variable) throw()
  2004. {
  2005. __asm__ __volatile__ (
  2006. #if JUCE_64BIT
  2007. "lock incl (%%rax)"
  2008. :
  2009. : "a" (&variable)
  2010. : "cc", "memory");
  2011. #else
  2012. "lock incl %0"
  2013. : "=m" (variable)
  2014. : "m" (variable));
  2015. #endif
  2016. }
  2017. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2018. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  2019. {
  2020. int result;
  2021. __asm__ __volatile__ (
  2022. #if JUCE_64BIT
  2023. "lock xaddl %%ebx, (%%rax) \n\
  2024. incl %%ebx"
  2025. : "=b" (result)
  2026. : "a" (&variable), "b" (1)
  2027. : "cc", "memory");
  2028. #else
  2029. "lock xaddl %%eax, (%%ecx) \n\
  2030. incl %%eax"
  2031. : "=a" (result)
  2032. : "c" (&variable), "a" (1)
  2033. : "memory");
  2034. #endif
  2035. return result;
  2036. }
  2037. /** Decrememts an integer in a thread-safe way. */
  2038. forcedinline void atomicDecrement (int& variable) throw()
  2039. {
  2040. __asm__ __volatile__ (
  2041. #if JUCE_64BIT
  2042. "lock decl (%%rax)"
  2043. :
  2044. : "a" (&variable)
  2045. : "cc", "memory");
  2046. #else
  2047. "lock decl %0"
  2048. : "=m" (variable)
  2049. : "m" (variable));
  2050. #endif
  2051. }
  2052. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2053. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  2054. {
  2055. int result;
  2056. __asm__ __volatile__ (
  2057. #if JUCE_64BIT
  2058. "lock xaddl %%ebx, (%%rax) \n\
  2059. decl %%ebx"
  2060. : "=b" (result)
  2061. : "a" (&variable), "b" (-1)
  2062. : "cc", "memory");
  2063. #else
  2064. "lock xaddl %%eax, (%%ecx) \n\
  2065. decl %%eax"
  2066. : "=a" (result)
  2067. : "c" (&variable), "a" (-1)
  2068. : "memory");
  2069. #endif
  2070. return result;
  2071. }
  2072. #endif
  2073. #elif JUCE_USE_INTRINSICS
  2074. #pragma intrinsic (_InterlockedIncrement)
  2075. #pragma intrinsic (_InterlockedDecrement)
  2076. /** Increments an integer in a thread-safe way. */
  2077. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2078. {
  2079. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2080. }
  2081. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2082. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2083. {
  2084. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2085. }
  2086. /** Decrememts an integer in a thread-safe way. */
  2087. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2088. {
  2089. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2090. }
  2091. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2092. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2093. {
  2094. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2095. }
  2096. #else
  2097. /** Increments an integer in a thread-safe way. */
  2098. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2099. {
  2100. __asm {
  2101. mov ecx, dword ptr [variable]
  2102. lock inc dword ptr [ecx]
  2103. }
  2104. }
  2105. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2106. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2107. {
  2108. int result;
  2109. __asm {
  2110. mov ecx, dword ptr [variable]
  2111. mov eax, 1
  2112. lock xadd dword ptr [ecx], eax
  2113. inc eax
  2114. mov result, eax
  2115. }
  2116. return result;
  2117. }
  2118. /** Decrememts an integer in a thread-safe way. */
  2119. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2120. {
  2121. __asm {
  2122. mov ecx, dword ptr [variable]
  2123. lock dec dword ptr [ecx]
  2124. }
  2125. }
  2126. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2127. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2128. {
  2129. int result;
  2130. __asm {
  2131. mov ecx, dword ptr [variable]
  2132. mov eax, -1
  2133. lock xadd dword ptr [ecx], eax
  2134. dec eax
  2135. mov result, eax
  2136. }
  2137. return result;
  2138. }
  2139. #endif
  2140. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2141. /********* End of inlined file: juce_Atomic.h *********/
  2142. #endif
  2143. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2144. #endif
  2145. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2146. /********* Start of inlined file: juce_FileLogger.h *********/
  2147. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2148. #define __JUCE_FILELOGGER_JUCEHEADER__
  2149. /********* Start of inlined file: juce_File.h *********/
  2150. #ifndef __JUCE_FILE_JUCEHEADER__
  2151. #define __JUCE_FILE_JUCEHEADER__
  2152. /********* Start of inlined file: juce_OwnedArray.h *********/
  2153. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2154. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2155. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2156. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2157. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2158. /** The default size of chunk in which arrays increase their storage.
  2159. Used by ArrayAllocationBase and its subclasses.
  2160. */
  2161. const int juceDefaultArrayGranularity = 8;
  2162. /**
  2163. Implements some basic array storage allocation functions.
  2164. This class isn't really for public use - it's used by the other
  2165. array classes, but might come in handy for some purposes.
  2166. @see Array, OwnedArray, ReferenceCountedArray
  2167. */
  2168. template <class ElementType>
  2169. class ArrayAllocationBase
  2170. {
  2171. public:
  2172. /** Creates an empty array.
  2173. @param granularity_ this is the size of increment by which the internal storage
  2174. will be increased.
  2175. */
  2176. ArrayAllocationBase (const int granularity_) throw()
  2177. : elements (0),
  2178. numAllocated (0),
  2179. granularity (granularity_)
  2180. {
  2181. jassert (granularity > 0);
  2182. }
  2183. /** Destructor. */
  2184. ~ArrayAllocationBase()
  2185. {
  2186. delete[] elements;
  2187. }
  2188. /** Changes the amount of storage allocated.
  2189. This will retain any data currently held in the array, and either add or
  2190. remove extra space at the end.
  2191. @param numElements the number of elements that are needed
  2192. */
  2193. void setAllocatedSize (const int numElements) throw()
  2194. {
  2195. if (numAllocated != numElements)
  2196. {
  2197. if (numElements > 0)
  2198. {
  2199. ElementType* const newElements = new ElementType [numElements];
  2200. const int itemsToRetain = jmin (numElements, numAllocated);
  2201. for (int i = 0; i < itemsToRetain; ++i)
  2202. newElements[i] = elements[i];
  2203. delete[] elements;
  2204. elements = newElements;
  2205. }
  2206. else if (elements != 0)
  2207. {
  2208. delete[] elements;
  2209. elements = 0;
  2210. }
  2211. numAllocated = numElements;
  2212. }
  2213. }
  2214. /** Increases the amount of storage allocated if it is less than a given amount.
  2215. This will retain any data currently held in the array, but will add
  2216. extra space at the end to make sure there it's at least as big as the size
  2217. passed in. If it's already bigger, no action is taken.
  2218. @param minNumElements the minimum number of elements that are needed
  2219. */
  2220. void ensureAllocatedSize (int minNumElements) throw()
  2221. {
  2222. if (minNumElements > numAllocated)
  2223. {
  2224. // for arrays with small granularity that get big, start
  2225. // increasing the size in bigger jumps
  2226. if (minNumElements > (granularity << 6))
  2227. {
  2228. minNumElements += (minNumElements / granularity);
  2229. if (minNumElements > (granularity << 8))
  2230. minNumElements += granularity << 6;
  2231. else
  2232. minNumElements += granularity << 5;
  2233. }
  2234. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2235. }
  2236. }
  2237. ElementType* elements;
  2238. int numAllocated, granularity;
  2239. private:
  2240. ArrayAllocationBase (const ArrayAllocationBase&);
  2241. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2242. };
  2243. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2244. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2245. /********* Start of inlined file: juce_ElementComparator.h *********/
  2246. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2247. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2248. /**
  2249. Sorts a range of elements in an array.
  2250. The comparator object that is passed-in must define a public method with the following
  2251. signature:
  2252. @code
  2253. int compareElements (ElementType first, ElementType second);
  2254. @endcode
  2255. ..and this method must return:
  2256. - a value of < 0 if the first comes before the second
  2257. - a value of 0 if the two objects are equivalent
  2258. - a value of > 0 if the second comes before the first
  2259. To improve performance, the compareElements() method can be declared as static or const.
  2260. @param comparator an object which defines a compareElements() method
  2261. @param array the array to sort
  2262. @param firstElement the index of the first element of the range to be sorted
  2263. @param lastElement the index of the last element in the range that needs
  2264. sorting (this is inclusive)
  2265. @param retainOrderOfEquivalentItems if true, the order of items that the
  2266. comparator deems the same will be maintained - this will be
  2267. a slower algorithm than if they are allowed to be moved around.
  2268. @see sortArrayRetainingOrder
  2269. */
  2270. template <class ElementType, class ElementComparator>
  2271. static void sortArray (ElementComparator& comparator,
  2272. ElementType* const array,
  2273. int firstElement,
  2274. int lastElement,
  2275. const bool retainOrderOfEquivalentItems)
  2276. {
  2277. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2278. // avoids getting warning messages about the parameter being unused
  2279. if (lastElement > firstElement)
  2280. {
  2281. if (retainOrderOfEquivalentItems)
  2282. {
  2283. for (int i = firstElement; i < lastElement; ++i)
  2284. {
  2285. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2286. {
  2287. const ElementType temp = array [i];
  2288. array [i] = array[i + 1];
  2289. array [i + 1] = temp;
  2290. if (i > firstElement)
  2291. i -= 2;
  2292. }
  2293. }
  2294. }
  2295. else
  2296. {
  2297. int fromStack[30], toStack[30];
  2298. int stackIndex = 0;
  2299. for (;;)
  2300. {
  2301. const int size = (lastElement - firstElement) + 1;
  2302. if (size <= 8)
  2303. {
  2304. int j = lastElement;
  2305. int maxIndex;
  2306. while (j > firstElement)
  2307. {
  2308. maxIndex = firstElement;
  2309. for (int k = firstElement + 1; k <= j; ++k)
  2310. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2311. maxIndex = k;
  2312. const ElementType temp = array [maxIndex];
  2313. array [maxIndex] = array[j];
  2314. array [j] = temp;
  2315. --j;
  2316. }
  2317. }
  2318. else
  2319. {
  2320. const int mid = firstElement + (size >> 1);
  2321. ElementType temp = array [mid];
  2322. array [mid] = array [firstElement];
  2323. array [firstElement] = temp;
  2324. int i = firstElement;
  2325. int j = lastElement + 1;
  2326. for (;;)
  2327. {
  2328. while (++i <= lastElement
  2329. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2330. {}
  2331. while (--j > firstElement
  2332. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2333. {}
  2334. if (j < i)
  2335. break;
  2336. temp = array[i];
  2337. array[i] = array[j];
  2338. array[j] = temp;
  2339. }
  2340. temp = array [firstElement];
  2341. array [firstElement] = array[j];
  2342. array [j] = temp;
  2343. if (j - 1 - firstElement >= lastElement - i)
  2344. {
  2345. if (firstElement + 1 < j)
  2346. {
  2347. fromStack [stackIndex] = firstElement;
  2348. toStack [stackIndex] = j - 1;
  2349. ++stackIndex;
  2350. }
  2351. if (i < lastElement)
  2352. {
  2353. firstElement = i;
  2354. continue;
  2355. }
  2356. }
  2357. else
  2358. {
  2359. if (i < lastElement)
  2360. {
  2361. fromStack [stackIndex] = i;
  2362. toStack [stackIndex] = lastElement;
  2363. ++stackIndex;
  2364. }
  2365. if (firstElement + 1 < j)
  2366. {
  2367. lastElement = j - 1;
  2368. continue;
  2369. }
  2370. }
  2371. }
  2372. if (--stackIndex < 0)
  2373. break;
  2374. jassert (stackIndex < numElementsInArray (fromStack));
  2375. firstElement = fromStack [stackIndex];
  2376. lastElement = toStack [stackIndex];
  2377. }
  2378. }
  2379. }
  2380. }
  2381. /**
  2382. Searches a sorted array of elements, looking for the index at which a specified value
  2383. should be inserted for it to be in the correct order.
  2384. The comparator object that is passed-in must define a public method with the following
  2385. signature:
  2386. @code
  2387. int compareElements (ElementType first, ElementType second);
  2388. @endcode
  2389. ..and this method must return:
  2390. - a value of < 0 if the first comes before the second
  2391. - a value of 0 if the two objects are equivalent
  2392. - a value of > 0 if the second comes before the first
  2393. To improve performance, the compareElements() method can be declared as static or const.
  2394. @param comparator an object which defines a compareElements() method
  2395. @param array the array to search
  2396. @param newElement the value that is going to be inserted
  2397. @param firstElement the index of the first element to search
  2398. @param lastElement the index of the last element in the range (this is non-inclusive)
  2399. */
  2400. template <class ElementType, class ElementComparator>
  2401. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2402. ElementType* const array,
  2403. const ElementType newElement,
  2404. int firstElement,
  2405. int lastElement)
  2406. {
  2407. jassert (firstElement <= lastElement);
  2408. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2409. // avoids getting warning messages about the parameter being unused
  2410. while (firstElement < lastElement)
  2411. {
  2412. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2413. {
  2414. ++firstElement;
  2415. break;
  2416. }
  2417. else
  2418. {
  2419. const int halfway = (firstElement + lastElement) >> 1;
  2420. if (halfway == firstElement)
  2421. {
  2422. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2423. ++firstElement;
  2424. break;
  2425. }
  2426. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2427. {
  2428. firstElement = halfway;
  2429. }
  2430. else
  2431. {
  2432. lastElement = halfway;
  2433. }
  2434. }
  2435. }
  2436. return firstElement;
  2437. }
  2438. /**
  2439. A simple ElementComparator class that can be used to sort an array of
  2440. integer primitive objects.
  2441. Example: @code
  2442. Array <int> myArray;
  2443. IntegerElementComparator<int> sorter;
  2444. myArray.sort (sorter);
  2445. @endcode
  2446. For floating point values, see the FloatElementComparator class instead.
  2447. @see FloatElementComparator, ElementComparator
  2448. */
  2449. template <class ElementType>
  2450. class IntegerElementComparator
  2451. {
  2452. public:
  2453. static int compareElements (const ElementType first,
  2454. const ElementType second) throw()
  2455. {
  2456. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2457. }
  2458. };
  2459. /**
  2460. A simple ElementComparator class that can be used to sort an array of numeric
  2461. double or floating point primitive objects.
  2462. Example: @code
  2463. Array <double> myArray;
  2464. FloatElementComparator<double> sorter;
  2465. myArray.sort (sorter);
  2466. @endcode
  2467. For integer values, see the IntegerElementComparator class instead.
  2468. @see IntegerElementComparator, ElementComparator
  2469. */
  2470. template <class ElementType>
  2471. class FloatElementComparator
  2472. {
  2473. public:
  2474. static int compareElements (const ElementType first,
  2475. const ElementType second) throw()
  2476. {
  2477. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2478. }
  2479. };
  2480. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2481. /********* End of inlined file: juce_ElementComparator.h *********/
  2482. /********* Start of inlined file: juce_CriticalSection.h *********/
  2483. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2484. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2485. /**
  2486. Prevents multiple threads from accessing shared objects at the same time.
  2487. @see ScopedLock, Thread, InterProcessLock
  2488. */
  2489. class JUCE_API CriticalSection
  2490. {
  2491. public:
  2492. /**
  2493. Creates a CriticalSection object
  2494. */
  2495. CriticalSection() throw();
  2496. /** Destroys a CriticalSection object.
  2497. If the critical section is deleted whilst locked, its subsequent behaviour
  2498. is unpredictable.
  2499. */
  2500. ~CriticalSection() throw();
  2501. /** Locks this critical section.
  2502. If the lock is currently held by another thread, this will wait until it
  2503. becomes free.
  2504. If the lock is already held by the caller thread, the method returns immediately.
  2505. @see exit, ScopedLock
  2506. */
  2507. void enter() const throw();
  2508. /** Attempts to lock this critical section without blocking.
  2509. This method behaves identically to CriticalSection::enter, except that the caller thread
  2510. does not wait if the lock is currently held by another thread but returns false immediately.
  2511. @returns false if the lock is currently held by another thread, true otherwise.
  2512. @see enter
  2513. */
  2514. bool tryEnter() const throw();
  2515. /** Releases the lock.
  2516. If the caller thread hasn't got the lock, this can have unpredictable results.
  2517. If the enter() method has been called multiple times by the thread, each
  2518. call must be matched by a call to exit() before other threads will be allowed
  2519. to take over the lock.
  2520. @see enter, ScopedLock
  2521. */
  2522. void exit() const throw();
  2523. juce_UseDebuggingNewOperator
  2524. private:
  2525. #if JUCE_WIN32
  2526. #if JUCE_64BIT
  2527. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2528. // block of memory here that's big enough to be used internally as a windows critical
  2529. // section object.
  2530. uint8 internal [44];
  2531. #else
  2532. uint8 internal [24];
  2533. #endif
  2534. #else
  2535. mutable pthread_mutex_t internal;
  2536. #endif
  2537. CriticalSection (const CriticalSection&);
  2538. const CriticalSection& operator= (const CriticalSection&);
  2539. };
  2540. /**
  2541. A class that can be used in place of a real CriticalSection object.
  2542. This is currently used by some templated array classes, and should get
  2543. optimised out by the compiler.
  2544. @see Array, OwnedArray, ReferenceCountedArray
  2545. */
  2546. class JUCE_API DummyCriticalSection
  2547. {
  2548. public:
  2549. forcedinline DummyCriticalSection() throw() {}
  2550. forcedinline ~DummyCriticalSection() throw() {}
  2551. forcedinline void enter() const throw() {}
  2552. forcedinline void exit() const throw() {}
  2553. };
  2554. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2555. /********* End of inlined file: juce_CriticalSection.h *********/
  2556. /** An array designed for holding objects.
  2557. This holds a list of pointers to objects, and will automatically
  2558. delete the objects when they are removed from the array, or when the
  2559. array is itself deleted.
  2560. Declare it in the form: OwnedArray<MyObjectClass>
  2561. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2562. After adding objects, they are 'owned' by the array and will be deleted when
  2563. removed or replaced.
  2564. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2565. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2566. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2567. */
  2568. template <class ObjectClass,
  2569. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2570. class OwnedArray
  2571. {
  2572. public:
  2573. /** Creates an empty array.
  2574. @param granularity this is the size of increment by which the internal storage
  2575. used by the array will grow. Only change it from the default if you know the
  2576. array is going to be very big and needs to be able to grow efficiently.
  2577. */
  2578. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2579. : data (granularity),
  2580. numUsed (0)
  2581. {
  2582. }
  2583. /** Deletes the array and also deletes any objects inside it.
  2584. To get rid of the array without deleting its objects, use its
  2585. clear (false) method before deleting it.
  2586. */
  2587. ~OwnedArray()
  2588. {
  2589. clear (true);
  2590. }
  2591. /** Clears the array, optionally deleting the objects inside it first. */
  2592. void clear (const bool deleteObjects = true)
  2593. {
  2594. lock.enter();
  2595. if (deleteObjects)
  2596. {
  2597. while (numUsed > 0)
  2598. delete data.elements [--numUsed];
  2599. }
  2600. data.setAllocatedSize (0);
  2601. numUsed = 0;
  2602. lock.exit();
  2603. }
  2604. /** Returns the number of items currently in the array.
  2605. @see operator[]
  2606. */
  2607. inline int size() const throw()
  2608. {
  2609. return numUsed;
  2610. }
  2611. /** Returns a pointer to the object at this index in the array.
  2612. If the index is out-of-range, this will return a null pointer, (and
  2613. it could be null anyway, because it's ok for the array to hold null
  2614. pointers as well as objects).
  2615. @see getUnchecked
  2616. */
  2617. inline ObjectClass* operator[] (const int index) const throw()
  2618. {
  2619. lock.enter();
  2620. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2621. ? data.elements [index]
  2622. : (ObjectClass*) 0;
  2623. lock.exit();
  2624. return result;
  2625. }
  2626. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2627. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2628. it can be used when you're sure the index if always going to be legal.
  2629. */
  2630. inline ObjectClass* getUnchecked (const int index) const throw()
  2631. {
  2632. lock.enter();
  2633. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2634. ObjectClass* const result = data.elements [index];
  2635. lock.exit();
  2636. return result;
  2637. }
  2638. /** Returns a pointer to the first object in the array.
  2639. This will return a null pointer if the array's empty.
  2640. @see getLast
  2641. */
  2642. inline ObjectClass* getFirst() const throw()
  2643. {
  2644. lock.enter();
  2645. ObjectClass* const result = (numUsed > 0) ? data.elements [0]
  2646. : (ObjectClass*) 0;
  2647. lock.exit();
  2648. return result;
  2649. }
  2650. /** Returns a pointer to the last object in the array.
  2651. This will return a null pointer if the array's empty.
  2652. @see getFirst
  2653. */
  2654. inline ObjectClass* getLast() const throw()
  2655. {
  2656. lock.enter();
  2657. ObjectClass* const result = (numUsed > 0) ? data.elements [numUsed - 1]
  2658. : (ObjectClass*) 0;
  2659. lock.exit();
  2660. return result;
  2661. }
  2662. /** Finds the index of an object which might be in the array.
  2663. @param objectToLookFor the object to look for
  2664. @returns the index at which the object was found, or -1 if it's not found
  2665. */
  2666. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2667. {
  2668. int result = -1;
  2669. lock.enter();
  2670. ObjectClass* const* e = data.elements;
  2671. for (int i = numUsed; --i >= 0;)
  2672. {
  2673. if (objectToLookFor == *e)
  2674. {
  2675. result = (int) (e - data.elements);
  2676. break;
  2677. }
  2678. ++e;
  2679. }
  2680. lock.exit();
  2681. return result;
  2682. }
  2683. /** Returns true if the array contains a specified object.
  2684. @param objectToLookFor the object to look for
  2685. @returns true if the object is in the array
  2686. */
  2687. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2688. {
  2689. lock.enter();
  2690. ObjectClass* const* e = data.elements;
  2691. int i = numUsed;
  2692. while (i >= 4)
  2693. {
  2694. if (objectToLookFor == *e
  2695. || objectToLookFor == *++e
  2696. || objectToLookFor == *++e
  2697. || objectToLookFor == *++e)
  2698. {
  2699. lock.exit();
  2700. return true;
  2701. }
  2702. i -= 4;
  2703. ++e;
  2704. }
  2705. while (i > 0)
  2706. {
  2707. if (objectToLookFor == *e)
  2708. {
  2709. lock.exit();
  2710. return true;
  2711. }
  2712. --i;
  2713. ++e;
  2714. }
  2715. lock.exit();
  2716. return false;
  2717. }
  2718. /** Appends a new object to the end of the array.
  2719. Note that the this object will be deleted by the OwnedArray when it
  2720. is removed, so be careful not to delete it somewhere else.
  2721. Also be careful not to add the same object to the array more than once,
  2722. as this will obviously cause deletion of dangling pointers.
  2723. @param newObject the new object to add to the array
  2724. @see set, insert, addIfNotAlreadyThere, addSorted
  2725. */
  2726. void add (const ObjectClass* const newObject) throw()
  2727. {
  2728. lock.enter();
  2729. data.ensureAllocatedSize (numUsed + 1);
  2730. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2731. lock.exit();
  2732. }
  2733. /** Inserts a new object into the array at the given index.
  2734. Note that the this object will be deleted by the OwnedArray when it
  2735. is removed, so be careful not to delete it somewhere else.
  2736. If the index is less than 0 or greater than the size of the array, the
  2737. element will be added to the end of the array.
  2738. Otherwise, it will be inserted into the array, moving all the later elements
  2739. along to make room.
  2740. Be careful not to add the same object to the array more than once,
  2741. as this will obviously cause deletion of dangling pointers.
  2742. @param indexToInsertAt the index at which the new element should be inserted
  2743. @param newObject the new object to add to the array
  2744. @see add, addSorted, addIfNotAlreadyThere, set
  2745. */
  2746. void insert (int indexToInsertAt,
  2747. const ObjectClass* const newObject) throw()
  2748. {
  2749. if (indexToInsertAt >= 0)
  2750. {
  2751. lock.enter();
  2752. if (indexToInsertAt > numUsed)
  2753. indexToInsertAt = numUsed;
  2754. data.ensureAllocatedSize (numUsed + 1);
  2755. ObjectClass** const e = data.elements + indexToInsertAt;
  2756. const int numToMove = numUsed - indexToInsertAt;
  2757. if (numToMove > 0)
  2758. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2759. *e = const_cast <ObjectClass*> (newObject);
  2760. ++numUsed;
  2761. lock.exit();
  2762. }
  2763. else
  2764. {
  2765. add (newObject);
  2766. }
  2767. }
  2768. /** Appends a new object at the end of the array as long as the array doesn't
  2769. already contain it.
  2770. If the array already contains a matching object, nothing will be done.
  2771. @param newObject the new object to add to the array
  2772. */
  2773. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2774. {
  2775. lock.enter();
  2776. if (! contains (newObject))
  2777. add (newObject);
  2778. lock.exit();
  2779. }
  2780. /** Replaces an object in the array with a different one.
  2781. If the index is less than zero, this method does nothing.
  2782. If the index is beyond the end of the array, the new object is added to the end of the array.
  2783. Be careful not to add the same object to the array more than once,
  2784. as this will obviously cause deletion of dangling pointers.
  2785. @param indexToChange the index whose value you want to change
  2786. @param newObject the new value to set for this index.
  2787. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2788. @see add, insert, remove
  2789. */
  2790. void set (const int indexToChange,
  2791. const ObjectClass* const newObject,
  2792. const bool deleteOldElement = true)
  2793. {
  2794. if (indexToChange >= 0)
  2795. {
  2796. ObjectClass* toDelete = 0;
  2797. lock.enter();
  2798. if (indexToChange < numUsed)
  2799. {
  2800. if (deleteOldElement)
  2801. {
  2802. toDelete = data.elements [indexToChange];
  2803. if (toDelete == newObject)
  2804. toDelete = 0;
  2805. }
  2806. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2807. }
  2808. else
  2809. {
  2810. data.ensureAllocatedSize (numUsed + 1);
  2811. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2812. }
  2813. lock.exit();
  2814. delete toDelete;
  2815. }
  2816. }
  2817. /** Inserts a new object into the array assuming that the array is sorted.
  2818. This will use a comparator to find the position at which the new object
  2819. should go. If the array isn't sorted, the behaviour of this
  2820. method will be unpredictable.
  2821. @param comparator the comparator to use to compare the elements - see the sort method
  2822. for details about this object's structure
  2823. @param newObject the new object to insert to the array
  2824. @see add, sort, indexOfSorted
  2825. */
  2826. template <class ElementComparator>
  2827. void addSorted (ElementComparator& comparator,
  2828. ObjectClass* const newObject) throw()
  2829. {
  2830. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2831. // avoids getting warning messages about the parameter being unused
  2832. lock.enter();
  2833. insert (findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed), newObject);
  2834. lock.exit();
  2835. }
  2836. /** Finds the index of an object in the array, assuming that the array is sorted.
  2837. This will use a comparator to do a binary-chop to find the index of the given
  2838. element, if it exists. If the array isn't sorted, the behaviour of this
  2839. method will be unpredictable.
  2840. @param comparator the comparator to use to compare the elements - see the sort()
  2841. method for details about the form this object should take
  2842. @param objectToLookFor the object to search for
  2843. @returns the index of the element, or -1 if it's not found
  2844. @see addSorted, sort
  2845. */
  2846. template <class ElementComparator>
  2847. int indexOfSorted (ElementComparator& comparator,
  2848. const ObjectClass* const objectToLookFor) const throw()
  2849. {
  2850. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2851. // avoids getting warning messages about the parameter being unused
  2852. lock.enter();
  2853. int start = 0;
  2854. int end = numUsed;
  2855. for (;;)
  2856. {
  2857. if (start >= end)
  2858. {
  2859. lock.exit();
  2860. return -1;
  2861. }
  2862. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  2863. {
  2864. lock.exit();
  2865. return start;
  2866. }
  2867. else
  2868. {
  2869. const int halfway = (start + end) >> 1;
  2870. if (halfway == start)
  2871. {
  2872. lock.exit();
  2873. return -1;
  2874. }
  2875. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  2876. start = halfway;
  2877. else
  2878. end = halfway;
  2879. }
  2880. }
  2881. }
  2882. /** Removes an object from the array.
  2883. This will remove the object at a given index (optionally also
  2884. deleting it) and move back all the subsequent objects to close the gap.
  2885. If the index passed in is out-of-range, nothing will happen.
  2886. @param indexToRemove the index of the element to remove
  2887. @param deleteObject whether to delete the object that is removed
  2888. @see removeObject, removeRange
  2889. */
  2890. void remove (const int indexToRemove,
  2891. const bool deleteObject = true)
  2892. {
  2893. lock.enter();
  2894. ObjectClass* toDelete = 0;
  2895. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2896. {
  2897. ObjectClass** const e = data.elements + indexToRemove;
  2898. if (deleteObject)
  2899. toDelete = *e;
  2900. --numUsed;
  2901. const int numToShift = numUsed - indexToRemove;
  2902. if (numToShift > 0)
  2903. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2904. if ((numUsed << 1) < data.numAllocated)
  2905. minimiseStorageOverheads();
  2906. }
  2907. lock.exit();
  2908. delete toDelete;
  2909. }
  2910. /** Removes a specified object from the array.
  2911. If the item isn't found, no action is taken.
  2912. @param objectToRemove the object to try to remove
  2913. @param deleteObject whether to delete the object (if it's found)
  2914. @see remove, removeRange
  2915. */
  2916. void removeObject (const ObjectClass* const objectToRemove,
  2917. const bool deleteObject = true)
  2918. {
  2919. lock.enter();
  2920. ObjectClass** e = data.elements;
  2921. for (int i = numUsed; --i >= 0;)
  2922. {
  2923. if (objectToRemove == *e)
  2924. {
  2925. remove ((int) (e - data.elements), deleteObject);
  2926. break;
  2927. }
  2928. ++e;
  2929. }
  2930. lock.exit();
  2931. }
  2932. /** Removes a range of objects from the array.
  2933. This will remove a set of objects, starting from the given index,
  2934. and move any subsequent elements down to close the gap.
  2935. If the range extends beyond the bounds of the array, it will
  2936. be safely clipped to the size of the array.
  2937. @param startIndex the index of the first object to remove
  2938. @param numberToRemove how many objects should be removed
  2939. @param deleteObjects whether to delete the objects that get removed
  2940. @see remove, removeObject
  2941. */
  2942. void removeRange (int startIndex,
  2943. const int numberToRemove,
  2944. const bool deleteObjects = true)
  2945. {
  2946. lock.enter();
  2947. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2948. startIndex = jlimit (0, numUsed, startIndex);
  2949. if (endIndex > startIndex)
  2950. {
  2951. if (deleteObjects)
  2952. {
  2953. for (int i = startIndex; i < endIndex; ++i)
  2954. {
  2955. delete data.elements [i];
  2956. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2957. }
  2958. }
  2959. const int rangeSize = endIndex - startIndex;
  2960. ObjectClass** e = data.elements + startIndex;
  2961. int numToShift = numUsed - endIndex;
  2962. numUsed -= rangeSize;
  2963. while (--numToShift >= 0)
  2964. {
  2965. *e = e [rangeSize];
  2966. ++e;
  2967. }
  2968. if ((numUsed << 1) < data.numAllocated)
  2969. minimiseStorageOverheads();
  2970. }
  2971. lock.exit();
  2972. }
  2973. /** Removes the last n objects from the array.
  2974. @param howManyToRemove how many objects to remove from the end of the array
  2975. @param deleteObjects whether to also delete the objects that are removed
  2976. @see remove, removeObject, removeRange
  2977. */
  2978. void removeLast (int howManyToRemove = 1,
  2979. const bool deleteObjects = true)
  2980. {
  2981. lock.enter();
  2982. if (howManyToRemove >= numUsed)
  2983. {
  2984. clear (deleteObjects);
  2985. }
  2986. else
  2987. {
  2988. while (--howManyToRemove >= 0)
  2989. remove (numUsed - 1, deleteObjects);
  2990. }
  2991. lock.exit();
  2992. }
  2993. /** Swaps a pair of objects in the array.
  2994. If either of the indexes passed in is out-of-range, nothing will happen,
  2995. otherwise the two objects at these positions will be exchanged.
  2996. */
  2997. void swap (const int index1,
  2998. const int index2) throw()
  2999. {
  3000. lock.enter();
  3001. if (((unsigned int) index1) < (unsigned int) numUsed
  3002. && ((unsigned int) index2) < (unsigned int) numUsed)
  3003. {
  3004. swapVariables (data.elements [index1],
  3005. data.elements [index2]);
  3006. }
  3007. lock.exit();
  3008. }
  3009. /** Moves one of the objects to a different position.
  3010. This will move the object to a specified index, shuffling along
  3011. any intervening elements as required.
  3012. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3013. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3014. @param currentIndex the index of the object to be moved. If this isn't a
  3015. valid index, then nothing will be done
  3016. @param newIndex the index at which you'd like this object to end up. If this
  3017. is less than zero, it will be moved to the end of the array
  3018. */
  3019. void move (const int currentIndex,
  3020. int newIndex) throw()
  3021. {
  3022. if (currentIndex != newIndex)
  3023. {
  3024. lock.enter();
  3025. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3026. {
  3027. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3028. newIndex = numUsed - 1;
  3029. ObjectClass* const value = data.elements [currentIndex];
  3030. if (newIndex > currentIndex)
  3031. {
  3032. memmove (data.elements + currentIndex,
  3033. data.elements + currentIndex + 1,
  3034. (newIndex - currentIndex) * sizeof (ObjectClass*));
  3035. }
  3036. else
  3037. {
  3038. memmove (data.elements + newIndex + 1,
  3039. data.elements + newIndex,
  3040. (currentIndex - newIndex) * sizeof (ObjectClass*));
  3041. }
  3042. data.elements [newIndex] = value;
  3043. }
  3044. lock.exit();
  3045. }
  3046. }
  3047. /** This swaps the contents of this array with those of another array.
  3048. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3049. because it just swaps their internal pointers.
  3050. */
  3051. template <class OtherArrayType>
  3052. void swapWithArray (OtherArrayType& otherArray) throw()
  3053. {
  3054. lock.enter();
  3055. otherArray.lock.enter();
  3056. swapVariables <int> (numUsed, otherArray.numUsed);
  3057. swapVariables <ObjectClass**> (data.elements, otherArray.data.elements);
  3058. swapVariables <int> (data.numAllocated, otherArray.data.numAllocated);
  3059. otherArray.lock.exit();
  3060. lock.exit();
  3061. }
  3062. /** Reduces the amount of storage being used by the array.
  3063. Arrays typically allocate slightly more storage than they need, and after
  3064. removing elements, they may have quite a lot of unused space allocated.
  3065. This method will reduce the amount of allocated storage to a minimum.
  3066. */
  3067. void minimiseStorageOverheads() throw()
  3068. {
  3069. lock.enter();
  3070. if (numUsed == 0)
  3071. {
  3072. data.setAllocatedSize (0);
  3073. }
  3074. else
  3075. {
  3076. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  3077. if (newAllocation < data.numAllocated)
  3078. data.setAllocatedSize (newAllocation);
  3079. }
  3080. lock.exit();
  3081. }
  3082. /** Increases the array's internal storage to hold a minimum number of elements.
  3083. Calling this before adding a large known number of elements means that
  3084. the array won't have to keep dynamically resizing itself as the elements
  3085. are added, and it'll therefore be more efficient.
  3086. */
  3087. void ensureStorageAllocated (const int minNumElements) throw()
  3088. {
  3089. data.ensureAllocatedSize (minNumElements);
  3090. }
  3091. /** Sorts the elements in the array.
  3092. This will use a comparator object to sort the elements into order. The object
  3093. passed must have a method of the form:
  3094. @code
  3095. int compareElements (ElementType first, ElementType second);
  3096. @endcode
  3097. ..and this method must return:
  3098. - a value of < 0 if the first comes before the second
  3099. - a value of 0 if the two objects are equivalent
  3100. - a value of > 0 if the second comes before the first
  3101. To improve performance, the compareElements() method can be declared as static or const.
  3102. @param comparator the comparator to use for comparing elements.
  3103. @param retainOrderOfEquivalentItems if this is true, then items
  3104. which the comparator says are equivalent will be
  3105. kept in the order in which they currently appear
  3106. in the array. This is slower to perform, but may
  3107. be important in some cases. If it's false, a faster
  3108. algorithm is used, but equivalent elements may be
  3109. rearranged.
  3110. @see sortArray, indexOfSorted
  3111. */
  3112. template <class ElementComparator>
  3113. void sort (ElementComparator& comparator,
  3114. const bool retainOrderOfEquivalentItems = false) const throw()
  3115. {
  3116. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3117. // avoids getting warning messages about the parameter being unused
  3118. lock.enter();
  3119. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3120. lock.exit();
  3121. }
  3122. /** Locks the array's CriticalSection.
  3123. Of course if the type of section used is a DummyCriticalSection, this won't
  3124. have any effect.
  3125. @see unlockArray
  3126. */
  3127. void lockArray() const throw()
  3128. {
  3129. lock.enter();
  3130. }
  3131. /** Unlocks the array's CriticalSection.
  3132. Of course if the type of section used is a DummyCriticalSection, this won't
  3133. have any effect.
  3134. @see lockArray
  3135. */
  3136. void unlockArray() const throw()
  3137. {
  3138. lock.exit();
  3139. }
  3140. juce_UseDebuggingNewOperator
  3141. private:
  3142. ArrayAllocationBase <ObjectClass*> data;
  3143. int numUsed;
  3144. TypeOfCriticalSectionToUse lock;
  3145. // disallow copy constructor and assignment
  3146. OwnedArray (const OwnedArray&);
  3147. const OwnedArray& operator= (const OwnedArray&);
  3148. };
  3149. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3150. /********* End of inlined file: juce_OwnedArray.h *********/
  3151. /********* Start of inlined file: juce_Time.h *********/
  3152. #ifndef __JUCE_TIME_JUCEHEADER__
  3153. #define __JUCE_TIME_JUCEHEADER__
  3154. /********* Start of inlined file: juce_RelativeTime.h *********/
  3155. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3156. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3157. /** A relative measure of time.
  3158. The time is stored as a number of seconds, at double-precision floating
  3159. point accuracy, and may be positive or negative.
  3160. If you need an absolute time, (i.e. a date + time), see the Time class.
  3161. */
  3162. class JUCE_API RelativeTime
  3163. {
  3164. public:
  3165. /** Creates a RelativeTime.
  3166. @param seconds the number of seconds, which may be +ve or -ve.
  3167. @see milliseconds, minutes, hours, days, weeks
  3168. */
  3169. explicit RelativeTime (const double seconds = 0.0) throw();
  3170. /** Copies another relative time. */
  3171. RelativeTime (const RelativeTime& other) throw();
  3172. /** Copies another relative time. */
  3173. const RelativeTime& operator= (const RelativeTime& other) throw();
  3174. /** Destructor. */
  3175. ~RelativeTime() throw();
  3176. /** Creates a new RelativeTime object representing a number of milliseconds.
  3177. @see minutes, hours, days, weeks
  3178. */
  3179. static const RelativeTime milliseconds (const int milliseconds) throw();
  3180. /** Creates a new RelativeTime object representing a number of milliseconds.
  3181. @see minutes, hours, days, weeks
  3182. */
  3183. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3184. /** Creates a new RelativeTime object representing a number of minutes.
  3185. @see milliseconds, hours, days, weeks
  3186. */
  3187. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3188. /** Creates a new RelativeTime object representing a number of hours.
  3189. @see milliseconds, minutes, days, weeks
  3190. */
  3191. static const RelativeTime hours (const double numberOfHours) throw();
  3192. /** Creates a new RelativeTime object representing a number of days.
  3193. @see milliseconds, minutes, hours, weeks
  3194. */
  3195. static const RelativeTime days (const double numberOfDays) throw();
  3196. /** Creates a new RelativeTime object representing a number of weeks.
  3197. @see milliseconds, minutes, hours, days
  3198. */
  3199. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3200. /** Returns the number of milliseconds this time represents.
  3201. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3202. */
  3203. int64 inMilliseconds() const throw();
  3204. /** Returns the number of seconds this time represents.
  3205. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3206. */
  3207. double inSeconds() const throw() { return seconds; }
  3208. /** Returns the number of minutes this time represents.
  3209. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3210. */
  3211. double inMinutes() const throw();
  3212. /** Returns the number of hours this time represents.
  3213. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3214. */
  3215. double inHours() const throw();
  3216. /** Returns the number of days this time represents.
  3217. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3218. */
  3219. double inDays() const throw();
  3220. /** Returns the number of weeks this time represents.
  3221. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3222. */
  3223. double inWeeks() const throw();
  3224. /** Returns a readable textual description of the time.
  3225. The exact format of the string returned will depend on
  3226. the magnitude of the time - e.g.
  3227. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3228. so that only the two most significant units are printed.
  3229. The returnValueForZeroTime value is the result that is returned if the
  3230. length is zero. Depending on your application you might want to use this
  3231. to return something more relevant like "empty" or "0 secs", etc.
  3232. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3233. */
  3234. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) 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. /** Compares two RelativeTimes. */
  3242. bool operator< (const RelativeTime& other) const throw();
  3243. /** Compares two RelativeTimes. */
  3244. bool operator>= (const RelativeTime& other) const throw();
  3245. /** Compares two RelativeTimes. */
  3246. bool operator<= (const RelativeTime& other) const throw();
  3247. /** Adds another RelativeTime to this one and returns the result. */
  3248. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3249. /** Subtracts another RelativeTime from this one and returns the result. */
  3250. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3251. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3252. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3253. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3254. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3255. /** Adds another RelativeTime to this one. */
  3256. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3257. /** Subtracts another RelativeTime from this one. */
  3258. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3259. /** Adds a number of seconds to this time. */
  3260. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3261. /** Subtracts a number of seconds from this time. */
  3262. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3263. juce_UseDebuggingNewOperator
  3264. private:
  3265. double seconds;
  3266. };
  3267. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3268. /********* End of inlined file: juce_RelativeTime.h *********/
  3269. /**
  3270. Holds an absolute date and time.
  3271. Internally, the time is stored at millisecond precision.
  3272. @see RelativeTime
  3273. */
  3274. class JUCE_API Time
  3275. {
  3276. public:
  3277. /** Creates a Time object.
  3278. This default constructor creates a time of 1st January 1970, (which is
  3279. represented internally as 0ms).
  3280. To create a time object representing the current time, use getCurrentTime().
  3281. @see getCurrentTime
  3282. */
  3283. Time() throw();
  3284. /** Creates a copy of another Time object. */
  3285. Time (const Time& other) throw();
  3286. /** Creates a time based on a number of milliseconds.
  3287. The internal millisecond count is set to 0 (1st January 1970). To create a
  3288. time object set to the current time, use getCurrentTime().
  3289. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3290. 'epoch' (midnight Jan 1st 1970).
  3291. @see getCurrentTime, currentTimeMillis
  3292. */
  3293. Time (const int64 millisecondsSinceEpoch) throw();
  3294. /** Creates a time from a set of date components.
  3295. The timezone is assumed to be whatever the system is using as its locale.
  3296. @param year the year, in 4-digit format, e.g. 2004
  3297. @param month the month, in the range 0 to 11
  3298. @param day the day of the month, in the range 1 to 31
  3299. @param hours hours in 24-hour clock format, 0 to 23
  3300. @param minutes minutes 0 to 59
  3301. @param seconds seconds 0 to 59
  3302. @param milliseconds milliseconds 0 to 999
  3303. @param useLocalTime if true, encode using the current machine's local time; if
  3304. false, it will always work in GMT.
  3305. */
  3306. Time (const int year,
  3307. const int month,
  3308. const int day,
  3309. const int hours,
  3310. const int minutes,
  3311. const int seconds = 0,
  3312. const int milliseconds = 0,
  3313. const bool useLocalTime = true) throw();
  3314. /** Destructor. */
  3315. ~Time() throw();
  3316. /** Copies this time from another one. */
  3317. const Time& operator= (const Time& other) throw();
  3318. /** Returns a Time object that is set to the current system time.
  3319. @see currentTimeMillis
  3320. */
  3321. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3322. /** Returns the time as a number of milliseconds.
  3323. @returns the number of milliseconds this Time object represents, since
  3324. midnight jan 1st 1970.
  3325. @see getMilliseconds
  3326. */
  3327. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3328. /** Returns the year.
  3329. A 4-digit format is used, e.g. 2004.
  3330. */
  3331. int getYear() const throw();
  3332. /** Returns the number of the month.
  3333. The value returned is in the range 0 to 11.
  3334. @see getMonthName
  3335. */
  3336. int getMonth() const throw();
  3337. /** Returns the name of the month.
  3338. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3339. it'll return the long form, e.g. "January"
  3340. @see getMonth
  3341. */
  3342. const String getMonthName (const bool threeLetterVersion) const throw();
  3343. /** Returns the day of the month.
  3344. The value returned is in the range 1 to 31.
  3345. */
  3346. int getDayOfMonth() const throw();
  3347. /** Returns the number of the day of the week.
  3348. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3349. */
  3350. int getDayOfWeek() const throw();
  3351. /** Returns the name of the weekday.
  3352. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3353. false, it'll return the full version, e.g. "Tuesday".
  3354. */
  3355. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3356. /** Returns the number of hours since midnight.
  3357. This is in 24-hour clock format, in the range 0 to 23.
  3358. @see getHoursInAmPmFormat, isAfternoon
  3359. */
  3360. int getHours() const throw();
  3361. /** Returns true if the time is in the afternoon.
  3362. So it returns true for "PM", false for "AM".
  3363. @see getHoursInAmPmFormat, getHours
  3364. */
  3365. bool isAfternoon() const throw();
  3366. /** Returns the hours in 12-hour clock format.
  3367. This will return a value 1 to 12 - use isAfternoon() to find out
  3368. whether this is in the afternoon or morning.
  3369. @see getHours, isAfternoon
  3370. */
  3371. int getHoursInAmPmFormat() const throw();
  3372. /** Returns the number of minutes, 0 to 59. */
  3373. int getMinutes() const throw();
  3374. /** Returns the number of seconds, 0 to 59. */
  3375. int getSeconds() const throw();
  3376. /** Returns the number of milliseconds, 0 to 999.
  3377. Unlike toMilliseconds(), this just returns the position within the
  3378. current second rather than the total number since the epoch.
  3379. @see toMilliseconds
  3380. */
  3381. int getMilliseconds() const throw();
  3382. /** Returns true if the local timezone uses a daylight saving correction. */
  3383. bool isDaylightSavingTime() const throw();
  3384. /** Returns a 3-character string to indicate the local timezone. */
  3385. const String getTimeZone() const throw();
  3386. /** Quick way of getting a string version of a date and time.
  3387. For a more powerful way of formatting the date and time, see the formatted() method.
  3388. @param includeDate whether to include the date in the string
  3389. @param includeTime whether to include the time in the string
  3390. @param includeSeconds if the time is being included, this provides an option not to include
  3391. the seconds in it
  3392. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3393. hour notation.
  3394. @see formatted
  3395. */
  3396. const String toString (const bool includeDate,
  3397. const bool includeTime,
  3398. const bool includeSeconds = true,
  3399. const bool use24HourClock = false) const throw();
  3400. /** Converts this date/time to a string with a user-defined format.
  3401. This uses the C strftime() function to format this time as a string. To save you
  3402. looking it up, these are the escape codes that strftime uses (other codes might
  3403. work on some platforms and not others, but these are the common ones):
  3404. %a is replaced by the locale's abbreviated weekday name.
  3405. %A is replaced by the locale's full weekday name.
  3406. %b is replaced by the locale's abbreviated month name.
  3407. %B is replaced by the locale's full month name.
  3408. %c is replaced by the locale's appropriate date and time representation.
  3409. %d is replaced by the day of the month as a decimal number [01,31].
  3410. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3411. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3412. %j is replaced by the day of the year as a decimal number [001,366].
  3413. %m is replaced by the month as a decimal number [01,12].
  3414. %M is replaced by the minute as a decimal number [00,59].
  3415. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3416. %S is replaced by the second as a decimal number [00,61].
  3417. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3418. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3419. %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.
  3420. %x is replaced by the locale's appropriate date representation.
  3421. %X is replaced by the locale's appropriate time representation.
  3422. %y is replaced by the year without century as a decimal number [00,99].
  3423. %Y is replaced by the year with century as a decimal number.
  3424. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3425. %% is replaced by %.
  3426. @see toString
  3427. */
  3428. const String formatted (const tchar* const format) const throw();
  3429. /** Adds a RelativeTime to this time and returns the result. */
  3430. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3431. /** Subtracts a RelativeTime from this time and returns the result. */
  3432. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3433. /** Returns the relative time difference between this time and another one. */
  3434. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (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. /** Compares two Time objects. */
  3442. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3443. /** Compares two Time objects. */
  3444. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3445. /** Compares two Time objects. */
  3446. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3447. /** Tries to set the computer's clock.
  3448. @returns true if this succeeds, although depending on the system, the
  3449. application might not have sufficient privileges to do this.
  3450. */
  3451. bool setSystemTimeToThisTime() const throw();
  3452. /** Returns the name of a day of the week.
  3453. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3454. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3455. false, it'll return the full version, e.g. "Tuesday".
  3456. */
  3457. static const String getWeekdayName (int dayNumber,
  3458. const bool threeLetterVersion) throw();
  3459. /** Returns the name of one of the months.
  3460. @param monthNumber the month, 0 to 11
  3461. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3462. it'll return the long form, e.g. "January"
  3463. */
  3464. static const String getMonthName (int monthNumber,
  3465. const bool threeLetterVersion) throw();
  3466. // Static methods for getting system timers directly..
  3467. /** Returns the current system time.
  3468. Returns the number of milliseconds since midnight jan 1st 1970.
  3469. Should be accurate to within a few millisecs, depending on platform,
  3470. hardware, etc.
  3471. */
  3472. static int64 currentTimeMillis() throw();
  3473. /** Returns the number of millisecs since system startup.
  3474. Should be accurate to within a few millisecs, depending on platform,
  3475. hardware, etc.
  3476. @see getApproximateMillisecondCounter
  3477. */
  3478. static uint32 getMillisecondCounter() throw();
  3479. /** Returns the number of millisecs since system startup.
  3480. Same as getMillisecondCounter(), but returns a more accurate value, using
  3481. the high-res timer.
  3482. @see getMillisecondCounter
  3483. */
  3484. static double getMillisecondCounterHiRes() throw();
  3485. /** Waits until the getMillisecondCounter() reaches a given value.
  3486. This will make the thread sleep as efficiently as it can while it's waiting.
  3487. */
  3488. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3489. /** Less-accurate but faster version of getMillisecondCounter().
  3490. This will return the last value that getMillisecondCounter() returned, so doesn't
  3491. need to make a system call, but is less accurate - it shouldn't be more than
  3492. 100ms away from the correct time, though, so is still accurate enough for a
  3493. lot of purposes.
  3494. @see getMillisecondCounter
  3495. */
  3496. static uint32 getApproximateMillisecondCounter() throw();
  3497. // High-resolution timers..
  3498. /** Returns the current high-resolution counter's tick-count.
  3499. This is a similar idea to getMillisecondCounter(), but with a higher
  3500. resolution.
  3501. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3502. secondsToHighResolutionTicks
  3503. */
  3504. static int64 getHighResolutionTicks() throw();
  3505. /** Returns the resolution of the high-resolution counter in ticks per second.
  3506. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3507. secondsToHighResolutionTicks
  3508. */
  3509. static int64 getHighResolutionTicksPerSecond() throw();
  3510. /** Converts a number of high-resolution ticks into seconds.
  3511. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3512. secondsToHighResolutionTicks
  3513. */
  3514. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3515. /** Converts a number seconds into high-resolution ticks.
  3516. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3517. highResolutionTicksToSeconds
  3518. */
  3519. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3520. private:
  3521. int64 millisSinceEpoch;
  3522. };
  3523. #endif // __JUCE_TIME_JUCEHEADER__
  3524. /********* End of inlined file: juce_Time.h *********/
  3525. /********* Start of inlined file: juce_StringArray.h *********/
  3526. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3527. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3528. /********* Start of inlined file: juce_VoidArray.h *********/
  3529. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3530. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3531. /********* Start of inlined file: juce_Array.h *********/
  3532. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3533. #define __JUCE_ARRAY_JUCEHEADER__
  3534. /**
  3535. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3536. Examples of arrays are: Array<int> or Array<MyClass*>
  3537. Note that when holding pointers to objects, the array doesn't take any ownership
  3538. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3539. If you're using a class or struct as the element type, it must be
  3540. capable of being copied or moved with a straightforward memcpy, rather than
  3541. needing construction and destruction code.
  3542. For holding lists of strings, use the specialised class StringArray.
  3543. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3544. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3545. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3546. */
  3547. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3548. class Array
  3549. {
  3550. public:
  3551. /** Creates an empty array.
  3552. @param granularity this is the size of increment by which the internal storage
  3553. used by the array will grow. Only change it from the default if you know the
  3554. array is going to be very big and needs to be able to grow efficiently.
  3555. */
  3556. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3557. : data (granularity),
  3558. numUsed (0)
  3559. {
  3560. }
  3561. /** Creates a copy of another array.
  3562. @param other the array to copy
  3563. */
  3564. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3565. : data (other.data.granularity)
  3566. {
  3567. other.lockArray();
  3568. numUsed = other.numUsed;
  3569. data.setAllocatedSize (other.numUsed);
  3570. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  3571. other.unlockArray();
  3572. }
  3573. /** Initalises from a null-terminated C array of values.
  3574. @param values the array to copy from
  3575. */
  3576. Array (const ElementType* values) throw()
  3577. : data (juceDefaultArrayGranularity),
  3578. numUsed (0)
  3579. {
  3580. while (*values != 0)
  3581. add (*values++);
  3582. }
  3583. /** Initalises from a C array of values.
  3584. @param values the array to copy from
  3585. @param numValues the number of values in the array
  3586. */
  3587. Array (const ElementType* values, int numValues) throw()
  3588. : data (juceDefaultArrayGranularity),
  3589. numUsed (numValues)
  3590. {
  3591. data.setAllocatedSize (numValues);
  3592. memcpy (data.elements, values, numValues * sizeof (ElementType));
  3593. }
  3594. /** Destructor. */
  3595. ~Array() throw()
  3596. {
  3597. }
  3598. /** Copies another array.
  3599. @param other the array to copy
  3600. */
  3601. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3602. {
  3603. if (this != &other)
  3604. {
  3605. other.lockArray();
  3606. lock.enter();
  3607. data.granularity = other.data.granularity;
  3608. data.ensureAllocatedSize (other.size());
  3609. numUsed = other.numUsed;
  3610. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  3611. minimiseStorageOverheads();
  3612. lock.exit();
  3613. other.unlockArray();
  3614. }
  3615. return *this;
  3616. }
  3617. /** Compares this array to another one.
  3618. Two arrays are considered equal if they both contain the same set of
  3619. elements, in the same order.
  3620. @param other the other array to compare with
  3621. */
  3622. template <class OtherArrayType>
  3623. bool operator== (const OtherArrayType& other) const throw()
  3624. {
  3625. lock.enter();
  3626. if (numUsed != other.numUsed)
  3627. {
  3628. lock.exit();
  3629. return false;
  3630. }
  3631. for (int i = numUsed; --i >= 0;)
  3632. {
  3633. if (data.elements [i] != other.data.elements [i])
  3634. {
  3635. lock.exit();
  3636. return false;
  3637. }
  3638. }
  3639. lock.exit();
  3640. return true;
  3641. }
  3642. /** Compares this array to another one.
  3643. Two arrays are considered equal if they both contain the same set of
  3644. elements, in the same order.
  3645. @param other the other array to compare with
  3646. */
  3647. template <class OtherArrayType>
  3648. bool operator!= (const OtherArrayType& other) const throw()
  3649. {
  3650. return ! operator== (other);
  3651. }
  3652. /** Removes all elements from the array.
  3653. This will remove all the elements, and free any storage that the array is
  3654. using. To clear the array without freeing the storage, use the clearQuick()
  3655. method instead.
  3656. @see clearQuick
  3657. */
  3658. void clear() throw()
  3659. {
  3660. lock.enter();
  3661. data.setAllocatedSize (0);
  3662. numUsed = 0;
  3663. lock.exit();
  3664. }
  3665. /** Removes all elements from the array without freeing the array's allocated storage.
  3666. @see clear
  3667. */
  3668. void clearQuick() throw()
  3669. {
  3670. lock.enter();
  3671. numUsed = 0;
  3672. lock.exit();
  3673. }
  3674. /** Returns the current number of elements in the array.
  3675. */
  3676. inline int size() const throw()
  3677. {
  3678. return numUsed;
  3679. }
  3680. /** Returns one of the elements in the array.
  3681. If the index passed in is beyond the range of valid elements, this
  3682. will return zero.
  3683. If you're certain that the index will always be a valid element, you
  3684. can call getUnchecked() instead, which is faster.
  3685. @param index the index of the element being requested (0 is the first element in the array)
  3686. @see getUnchecked, getFirst, getLast
  3687. */
  3688. inline ElementType operator[] (const int index) const throw()
  3689. {
  3690. lock.enter();
  3691. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3692. ? data.elements [index]
  3693. : ElementType();
  3694. lock.exit();
  3695. return result;
  3696. }
  3697. /** Returns one of the elements in the array, without checking the index passed in.
  3698. Unlike the operator[] method, this will try to return an element without
  3699. checking that the index is within the bounds of the array, so should only
  3700. be used when you're confident that it will always be a valid index.
  3701. @param index the index of the element being requested (0 is the first element in the array)
  3702. @see operator[], getFirst, getLast
  3703. */
  3704. inline ElementType getUnchecked (const int index) const throw()
  3705. {
  3706. lock.enter();
  3707. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3708. const ElementType result = data.elements [index];
  3709. lock.exit();
  3710. return result;
  3711. }
  3712. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3713. This is like getUnchecked, but returns a direct reference to the element, so that
  3714. you can alter it directly. Obviously this can be dangerous, so only use it when
  3715. absolutely necessary.
  3716. @param index the index of the element being requested (0 is the first element in the array)
  3717. @see operator[], getFirst, getLast
  3718. */
  3719. inline ElementType& getReference (const int index) const throw()
  3720. {
  3721. lock.enter();
  3722. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3723. ElementType& result = data.elements [index];
  3724. lock.exit();
  3725. return result;
  3726. }
  3727. /** Returns the first element in the array, or 0 if the array is empty.
  3728. @see operator[], getUnchecked, getLast
  3729. */
  3730. inline ElementType getFirst() const throw()
  3731. {
  3732. lock.enter();
  3733. const ElementType result = (numUsed > 0) ? data.elements [0]
  3734. : ElementType();
  3735. lock.exit();
  3736. return result;
  3737. }
  3738. /** Returns the last element in the array, or 0 if the array is empty.
  3739. @see operator[], getUnchecked, getFirst
  3740. */
  3741. inline ElementType getLast() const throw()
  3742. {
  3743. lock.enter();
  3744. const ElementType result = (numUsed > 0) ? data.elements [numUsed - 1]
  3745. : ElementType();
  3746. lock.exit();
  3747. return result;
  3748. }
  3749. /** Finds the index of the first element which matches the value passed in.
  3750. This will search the array for the given object, and return the index
  3751. of its first occurrence. If the object isn't found, the method will return -1.
  3752. @param elementToLookFor the value or object to look for
  3753. @returns the index of the object, or -1 if it's not found
  3754. */
  3755. int indexOf (const ElementType elementToLookFor) const throw()
  3756. {
  3757. int result = -1;
  3758. lock.enter();
  3759. const ElementType* e = data.elements;
  3760. for (int i = numUsed; --i >= 0;)
  3761. {
  3762. if (elementToLookFor == *e)
  3763. {
  3764. result = (int) (e - data.elements);
  3765. break;
  3766. }
  3767. ++e;
  3768. }
  3769. lock.exit();
  3770. return result;
  3771. }
  3772. /** Returns true if the array contains at least one occurrence of an object.
  3773. @param elementToLookFor the value or object to look for
  3774. @returns true if the item is found
  3775. */
  3776. bool contains (const ElementType elementToLookFor) const throw()
  3777. {
  3778. lock.enter();
  3779. const ElementType* e = data.elements;
  3780. int num = numUsed;
  3781. while (num >= 4)
  3782. {
  3783. if (*e == elementToLookFor
  3784. || *++e == elementToLookFor
  3785. || *++e == elementToLookFor
  3786. || *++e == elementToLookFor)
  3787. {
  3788. lock.exit();
  3789. return true;
  3790. }
  3791. num -= 4;
  3792. ++e;
  3793. }
  3794. while (num > 0)
  3795. {
  3796. if (elementToLookFor == *e)
  3797. {
  3798. lock.exit();
  3799. return true;
  3800. }
  3801. --num;
  3802. ++e;
  3803. }
  3804. lock.exit();
  3805. return false;
  3806. }
  3807. /** Appends a new element at the end of the array.
  3808. @param newElement the new object to add to the array
  3809. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3810. */
  3811. void add (const ElementType newElement) throw()
  3812. {
  3813. lock.enter();
  3814. data.ensureAllocatedSize (numUsed + 1);
  3815. data.elements [numUsed++] = newElement;
  3816. lock.exit();
  3817. }
  3818. /** Inserts a new element into the array at a given position.
  3819. If the index is less than 0 or greater than the size of the array, the
  3820. element will be added to the end of the array.
  3821. Otherwise, it will be inserted into the array, moving all the later elements
  3822. along to make room.
  3823. @param indexToInsertAt the index at which the new element should be
  3824. inserted (pass in -1 to add it to the end)
  3825. @param newElement the new object to add to the array
  3826. @see add, addSorted, set
  3827. */
  3828. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3829. {
  3830. lock.enter();
  3831. data.ensureAllocatedSize (numUsed + 1);
  3832. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3833. {
  3834. ElementType* const insertPos = data.elements + indexToInsertAt;
  3835. const int numberToMove = numUsed - indexToInsertAt;
  3836. if (numberToMove > 0)
  3837. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3838. *insertPos = newElement;
  3839. ++numUsed;
  3840. }
  3841. else
  3842. {
  3843. data.elements [numUsed++] = newElement;
  3844. }
  3845. lock.exit();
  3846. }
  3847. /** Inserts multiple copies of an element into the array at a given position.
  3848. If the index is less than 0 or greater than the size of the array, the
  3849. element will be added to the end of the array.
  3850. Otherwise, it will be inserted into the array, moving all the later elements
  3851. along to make room.
  3852. @param indexToInsertAt the index at which the new element should be inserted
  3853. @param newElement the new object to add to the array
  3854. @param numberOfTimesToInsertIt how many copies of the value to insert
  3855. @see insert, add, addSorted, set
  3856. */
  3857. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3858. int numberOfTimesToInsertIt) throw()
  3859. {
  3860. if (numberOfTimesToInsertIt > 0)
  3861. {
  3862. lock.enter();
  3863. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3864. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3865. {
  3866. ElementType* insertPos = data.elements + indexToInsertAt;
  3867. const int numberToMove = numUsed - indexToInsertAt;
  3868. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3869. numUsed += numberOfTimesToInsertIt;
  3870. while (--numberOfTimesToInsertIt >= 0)
  3871. *insertPos++ = newElement;
  3872. }
  3873. else
  3874. {
  3875. while (--numberOfTimesToInsertIt >= 0)
  3876. data.elements [numUsed++] = newElement;
  3877. }
  3878. lock.exit();
  3879. }
  3880. }
  3881. /** Inserts an array of values into this array at a given position.
  3882. If the index is less than 0 or greater than the size of the array, the
  3883. new elements will be added to the end of the array.
  3884. Otherwise, they will be inserted into the array, moving all the later elements
  3885. along to make room.
  3886. @param indexToInsertAt the index at which the first new element should be inserted
  3887. @param newElements the new values to add to the array
  3888. @param numberOfElements how many items are in the array
  3889. @see insert, add, addSorted, set
  3890. */
  3891. void insertArray (int indexToInsertAt,
  3892. const ElementType* newElements,
  3893. int numberOfElements) throw()
  3894. {
  3895. if (numberOfElements > 0)
  3896. {
  3897. lock.enter();
  3898. data.ensureAllocatedSize (numUsed + numberOfElements);
  3899. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3900. {
  3901. ElementType* insertPos = data.elements + indexToInsertAt;
  3902. const int numberToMove = numUsed - indexToInsertAt;
  3903. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3904. numUsed += numberOfElements;
  3905. while (--numberOfElements >= 0)
  3906. *insertPos++ = *newElements++;
  3907. }
  3908. else
  3909. {
  3910. while (--numberOfElements >= 0)
  3911. data.elements [numUsed++] = *newElements++;
  3912. }
  3913. lock.exit();
  3914. }
  3915. }
  3916. /** Appends a new element at the end of the array as long as the array doesn't
  3917. already contain it.
  3918. If the array already contains an element that matches the one passed in, nothing
  3919. will be done.
  3920. @param newElement the new object to add to the array
  3921. */
  3922. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3923. {
  3924. lock.enter();
  3925. if (! contains (newElement))
  3926. add (newElement);
  3927. lock.exit();
  3928. }
  3929. /** Replaces an element with a new value.
  3930. If the index is less than zero, this method does nothing.
  3931. If the index is beyond the end of the array, the item is added to the end of the array.
  3932. @param indexToChange the index whose value you want to change
  3933. @param newValue the new value to set for this index.
  3934. @see add, insert
  3935. */
  3936. void set (const int indexToChange,
  3937. const ElementType newValue) throw()
  3938. {
  3939. jassert (indexToChange >= 0);
  3940. if (indexToChange >= 0)
  3941. {
  3942. lock.enter();
  3943. if (indexToChange < numUsed)
  3944. {
  3945. data.elements [indexToChange] = newValue;
  3946. }
  3947. else
  3948. {
  3949. data.ensureAllocatedSize (numUsed + 1);
  3950. data.elements [numUsed++] = newValue;
  3951. }
  3952. lock.exit();
  3953. }
  3954. }
  3955. /** Replaces an element with a new value without doing any bounds-checking.
  3956. This just sets a value directly in the array's internal storage, so you'd
  3957. better make sure it's in range!
  3958. @param indexToChange the index whose value you want to change
  3959. @param newValue the new value to set for this index.
  3960. @see set, getUnchecked
  3961. */
  3962. void setUnchecked (const int indexToChange,
  3963. const ElementType newValue) throw()
  3964. {
  3965. lock.enter();
  3966. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3967. data.elements [indexToChange] = newValue;
  3968. lock.exit();
  3969. }
  3970. /** Adds elements from an array to the end of this array.
  3971. @param elementsToAdd the array of elements to add
  3972. @param numElementsToAdd how many elements are in this other array
  3973. @see add
  3974. */
  3975. void addArray (const ElementType* elementsToAdd,
  3976. int numElementsToAdd) throw()
  3977. {
  3978. lock.enter();
  3979. if (numElementsToAdd > 0)
  3980. {
  3981. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3982. while (--numElementsToAdd >= 0)
  3983. data.elements [numUsed++] = *elementsToAdd++;
  3984. }
  3985. lock.exit();
  3986. }
  3987. /** This swaps the contents of this array with those of another array.
  3988. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3989. because it just swaps their internal pointers.
  3990. */
  3991. template <class OtherArrayType>
  3992. void swapWithArray (OtherArrayType& otherArray) throw()
  3993. {
  3994. lock.enter();
  3995. otherArray.lock.enter();
  3996. swapVariables <int> (numUsed, otherArray.numUsed);
  3997. swapVariables <ElementType*> (data.elements, otherArray.data.elements);
  3998. swapVariables <int> (data.numAllocated, otherArray.data.numAllocated);
  3999. otherArray.lock.exit();
  4000. lock.exit();
  4001. }
  4002. /** Adds elements from another array to the end of this array.
  4003. @param arrayToAddFrom the array from which to copy the elements
  4004. @param startIndex the first element of the other array to start copying from
  4005. @param numElementsToAdd how many elements to add from the other array. If this
  4006. value is negative or greater than the number of available elements,
  4007. all available elements will be copied.
  4008. @see add
  4009. */
  4010. template <class OtherArrayType>
  4011. void addArray (const OtherArrayType& arrayToAddFrom,
  4012. int startIndex = 0,
  4013. int numElementsToAdd = -1) throw()
  4014. {
  4015. arrayToAddFrom.lockArray();
  4016. lock.enter();
  4017. jassert (this != &arrayToAddFrom);
  4018. if (startIndex < 0)
  4019. {
  4020. jassertfalse
  4021. startIndex = 0;
  4022. }
  4023. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  4024. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  4025. addArray ((const ElementType*) (arrayToAddFrom.data.elements + startIndex), numElementsToAdd);
  4026. lock.exit();
  4027. arrayToAddFrom.unlockArray();
  4028. }
  4029. /** Inserts a new element into the array, assuming that the array is sorted.
  4030. This will use a comparator to find the position at which the new element
  4031. should go. If the array isn't sorted, the behaviour of this
  4032. method will be unpredictable.
  4033. @param comparator the comparator to use to compare the elements - see the sort()
  4034. method for details about the form this object should take
  4035. @param newElement the new element to insert to the array
  4036. @see add, sort
  4037. */
  4038. template <class ElementComparator>
  4039. void addSorted (ElementComparator& comparator,
  4040. const ElementType newElement) throw()
  4041. {
  4042. lock.enter();
  4043. insert (findInsertIndexInSortedArray (comparator, data.elements, newElement, 0, numUsed), newElement);
  4044. lock.exit();
  4045. }
  4046. /** Finds the index of an element in the array, assuming that the array is sorted.
  4047. This will use a comparator to do a binary-chop to find the index of the given
  4048. element, if it exists. If the array isn't sorted, the behaviour of this
  4049. method will be unpredictable.
  4050. @param comparator the comparator to use to compare the elements - see the sort()
  4051. method for details about the form this object should take
  4052. @param elementToLookFor the element to search for
  4053. @returns the index of the element, or -1 if it's not found
  4054. @see addSorted, sort
  4055. */
  4056. template <class ElementComparator>
  4057. int indexOfSorted (ElementComparator& comparator,
  4058. const ElementType elementToLookFor) const throw()
  4059. {
  4060. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4061. // avoids getting warning messages about the parameter being unused
  4062. lock.enter();
  4063. int start = 0;
  4064. int end = numUsed;
  4065. for (;;)
  4066. {
  4067. if (start >= end)
  4068. {
  4069. lock.exit();
  4070. return -1;
  4071. }
  4072. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  4073. {
  4074. lock.exit();
  4075. return start;
  4076. }
  4077. else
  4078. {
  4079. const int halfway = (start + end) >> 1;
  4080. if (halfway == start)
  4081. {
  4082. lock.exit();
  4083. return -1;
  4084. }
  4085. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  4086. start = halfway;
  4087. else
  4088. end = halfway;
  4089. }
  4090. }
  4091. }
  4092. /** Removes an element from the array.
  4093. This will remove the element at a given index, and move back
  4094. all the subsequent elements to close the gap.
  4095. If the index passed in is out-of-range, nothing will happen.
  4096. @param indexToRemove the index of the element to remove
  4097. @returns the element that has been removed
  4098. @see removeValue, removeRange
  4099. */
  4100. ElementType remove (const int indexToRemove) throw()
  4101. {
  4102. lock.enter();
  4103. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4104. {
  4105. --numUsed;
  4106. ElementType* const e = data.elements + indexToRemove;
  4107. ElementType const removed = *e;
  4108. const int numberToShift = numUsed - indexToRemove;
  4109. if (numberToShift > 0)
  4110. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4111. if ((numUsed << 1) < data.numAllocated)
  4112. minimiseStorageOverheads();
  4113. lock.exit();
  4114. return removed;
  4115. }
  4116. else
  4117. {
  4118. lock.exit();
  4119. return ElementType();
  4120. }
  4121. }
  4122. /** Removes an item from the array.
  4123. This will remove the first occurrence of the given element from the array.
  4124. If the item isn't found, no action is taken.
  4125. @param valueToRemove the object to try to remove
  4126. @see remove, removeRange
  4127. */
  4128. void removeValue (const ElementType valueToRemove) throw()
  4129. {
  4130. lock.enter();
  4131. ElementType* e = data.elements;
  4132. for (int i = numUsed; --i >= 0;)
  4133. {
  4134. if (valueToRemove == *e)
  4135. {
  4136. remove ((int) (e - data.elements));
  4137. break;
  4138. }
  4139. ++e;
  4140. }
  4141. lock.exit();
  4142. }
  4143. /** Removes a range of elements from the array.
  4144. This will remove a set of elements, starting from the given index,
  4145. and move subsequent elements down to close the gap.
  4146. If the range extends beyond the bounds of the array, it will
  4147. be safely clipped to the size of the array.
  4148. @param startIndex the index of the first element to remove
  4149. @param numberToRemove how many elements should be removed
  4150. @see remove, removeValue
  4151. */
  4152. void removeRange (int startIndex,
  4153. const int numberToRemove) throw()
  4154. {
  4155. lock.enter();
  4156. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4157. startIndex = jlimit (0, numUsed, startIndex);
  4158. if (endIndex > startIndex)
  4159. {
  4160. const int rangeSize = endIndex - startIndex;
  4161. ElementType* e = data.elements + startIndex;
  4162. int numToShift = numUsed - endIndex;
  4163. numUsed -= rangeSize;
  4164. while (--numToShift >= 0)
  4165. {
  4166. *e = e [rangeSize];
  4167. ++e;
  4168. }
  4169. if ((numUsed << 1) < data.numAllocated)
  4170. minimiseStorageOverheads();
  4171. }
  4172. lock.exit();
  4173. }
  4174. /** Removes the last n elements from the array.
  4175. @param howManyToRemove how many elements to remove from the end of the array
  4176. @see remove, removeValue, removeRange
  4177. */
  4178. void removeLast (const int howManyToRemove = 1) throw()
  4179. {
  4180. lock.enter();
  4181. numUsed = jmax (0, numUsed - howManyToRemove);
  4182. if ((numUsed << 1) < data.numAllocated)
  4183. minimiseStorageOverheads();
  4184. lock.exit();
  4185. }
  4186. /** Removes any elements which are also in another array.
  4187. @param otherArray the other array in which to look for elements to remove
  4188. @see removeValuesNotIn, remove, removeValue, removeRange
  4189. */
  4190. template <class OtherArrayType>
  4191. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4192. {
  4193. otherArray.lockArray();
  4194. lock.enter();
  4195. if (this == &otherArray)
  4196. {
  4197. clear();
  4198. }
  4199. else
  4200. {
  4201. if (otherArray.size() > 0)
  4202. {
  4203. for (int i = numUsed; --i >= 0;)
  4204. if (otherArray.contains (data.elements [i]))
  4205. remove (i);
  4206. }
  4207. }
  4208. lock.exit();
  4209. otherArray.unlockArray();
  4210. }
  4211. /** Removes any elements which are not found in another array.
  4212. Only elements which occur in this other array will be retained.
  4213. @param otherArray the array in which to look for elements NOT to remove
  4214. @see removeValuesIn, remove, removeValue, removeRange
  4215. */
  4216. template <class OtherArrayType>
  4217. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4218. {
  4219. otherArray.lockArray();
  4220. lock.enter();
  4221. if (this != &otherArray)
  4222. {
  4223. if (otherArray.size() <= 0)
  4224. {
  4225. clear();
  4226. }
  4227. else
  4228. {
  4229. for (int i = numUsed; --i >= 0;)
  4230. if (! otherArray.contains (data.elements [i]))
  4231. remove (i);
  4232. }
  4233. }
  4234. lock.exit();
  4235. otherArray.unlockArray();
  4236. }
  4237. /** Swaps over two elements in the array.
  4238. This swaps over the elements found at the two indexes passed in.
  4239. If either index is out-of-range, this method will do nothing.
  4240. @param index1 index of one of the elements to swap
  4241. @param index2 index of the other element to swap
  4242. */
  4243. void swap (const int index1,
  4244. const int index2) throw()
  4245. {
  4246. lock.enter();
  4247. if (((unsigned int) index1) < (unsigned int) numUsed
  4248. && ((unsigned int) index2) < (unsigned int) numUsed)
  4249. {
  4250. swapVariables (data.elements [index1],
  4251. data.elements [index2]);
  4252. }
  4253. lock.exit();
  4254. }
  4255. /** Moves one of the values to a different position.
  4256. This will move the value to a specified index, shuffling along
  4257. any intervening elements as required.
  4258. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4259. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4260. @param currentIndex the index of the value to be moved. If this isn't a
  4261. valid index, then nothing will be done
  4262. @param newIndex the index at which you'd like this value to end up. If this
  4263. is less than zero, the value will be moved to the end
  4264. of the array
  4265. */
  4266. void move (const int currentIndex,
  4267. int newIndex) throw()
  4268. {
  4269. if (currentIndex != newIndex)
  4270. {
  4271. lock.enter();
  4272. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4273. {
  4274. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4275. newIndex = numUsed - 1;
  4276. const ElementType value = data.elements [currentIndex];
  4277. if (newIndex > currentIndex)
  4278. {
  4279. memmove (data.elements + currentIndex,
  4280. data.elements + currentIndex + 1,
  4281. (newIndex - currentIndex) * sizeof (ElementType));
  4282. }
  4283. else
  4284. {
  4285. memmove (data.elements + newIndex + 1,
  4286. data.elements + newIndex,
  4287. (currentIndex - newIndex) * sizeof (ElementType));
  4288. }
  4289. data.elements [newIndex] = value;
  4290. }
  4291. lock.exit();
  4292. }
  4293. }
  4294. /** Reduces the amount of storage being used by the array.
  4295. Arrays typically allocate slightly more storage than they need, and after
  4296. removing elements, they may have quite a lot of unused space allocated.
  4297. This method will reduce the amount of allocated storage to a minimum.
  4298. */
  4299. void minimiseStorageOverheads() throw()
  4300. {
  4301. lock.enter();
  4302. if (numUsed == 0)
  4303. {
  4304. data.setAllocatedSize (0);
  4305. }
  4306. else
  4307. {
  4308. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  4309. if (newAllocation < data.numAllocated)
  4310. data.setAllocatedSize (newAllocation);
  4311. }
  4312. lock.exit();
  4313. }
  4314. /** Increases the array's internal storage to hold a minimum number of elements.
  4315. Calling this before adding a large known number of elements means that
  4316. the array won't have to keep dynamically resizing itself as the elements
  4317. are added, and it'll therefore be more efficient.
  4318. */
  4319. void ensureStorageAllocated (const int minNumElements) throw()
  4320. {
  4321. data.ensureAllocatedSize (minNumElements);
  4322. }
  4323. /** Sorts the elements in the array.
  4324. This will use a comparator object to sort the elements into order. The object
  4325. passed must have a method of the form:
  4326. @code
  4327. int compareElements (ElementType first, ElementType second);
  4328. @endcode
  4329. ..and this method must return:
  4330. - a value of < 0 if the first comes before the second
  4331. - a value of 0 if the two objects are equivalent
  4332. - a value of > 0 if the second comes before the first
  4333. To improve performance, the compareElements() method can be declared as static or const.
  4334. @param comparator the comparator to use for comparing elements.
  4335. @param retainOrderOfEquivalentItems if this is true, then items
  4336. which the comparator says are equivalent will be
  4337. kept in the order in which they currently appear
  4338. in the array. This is slower to perform, but may
  4339. be important in some cases. If it's false, a faster
  4340. algorithm is used, but equivalent elements may be
  4341. rearranged.
  4342. @see addSorted, indexOfSorted, sortArray
  4343. */
  4344. template <class ElementComparator>
  4345. void sort (ElementComparator& comparator,
  4346. const bool retainOrderOfEquivalentItems = false) const throw()
  4347. {
  4348. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4349. // avoids getting warning messages about the parameter being unused
  4350. lock.enter();
  4351. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4352. lock.exit();
  4353. }
  4354. /** Locks the array's CriticalSection.
  4355. Of course if the type of section used is a DummyCriticalSection, this won't
  4356. have any effect.
  4357. @see unlockArray
  4358. */
  4359. void lockArray() const throw()
  4360. {
  4361. lock.enter();
  4362. }
  4363. /** Unlocks the array's CriticalSection.
  4364. Of course if the type of section used is a DummyCriticalSection, this won't
  4365. have any effect.
  4366. @see lockArray
  4367. */
  4368. void unlockArray() const throw()
  4369. {
  4370. lock.exit();
  4371. }
  4372. juce_UseDebuggingNewOperator
  4373. private:
  4374. ArrayAllocationBase <ElementType> data;
  4375. int numUsed;
  4376. TypeOfCriticalSectionToUse lock;
  4377. };
  4378. #endif // __JUCE_ARRAY_JUCEHEADER__
  4379. /********* End of inlined file: juce_Array.h *********/
  4380. /**
  4381. A typedef for an Array of void*'s.
  4382. VoidArrays are used in various places throughout the library instead of
  4383. more strongly-typed arrays, to keep code-size low.
  4384. */
  4385. typedef Array <void*> VoidArray;
  4386. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4387. /********* End of inlined file: juce_VoidArray.h *********/
  4388. #ifndef DOXYGEN
  4389. // (used in StringArray::appendNumbersToDuplicates)
  4390. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4391. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4392. #endif
  4393. /**
  4394. A special array for holding a list of strings.
  4395. @see String, StringPairArray
  4396. */
  4397. class JUCE_API StringArray
  4398. {
  4399. public:
  4400. /** Creates an empty string array */
  4401. StringArray() throw();
  4402. /** Creates a copy of another string array */
  4403. StringArray (const StringArray& other) throw();
  4404. /** Creates a copy of an array of string literals.
  4405. @param strings an array of strings to add. Null pointers in the array will be
  4406. treated as empty strings
  4407. @param numberOfStrings how many items there are in the array
  4408. */
  4409. StringArray (const juce_wchar** const strings,
  4410. const int numberOfStrings) throw();
  4411. /** Creates a copy of an array of string literals.
  4412. @param strings an array of strings to add. Null pointers in the array will be
  4413. treated as empty strings
  4414. @param numberOfStrings how many items there are in the array
  4415. */
  4416. StringArray (const char** const strings,
  4417. const int numberOfStrings) throw();
  4418. /** Creates a copy of a null-terminated array of string literals.
  4419. Each item from the array passed-in is added, until it encounters a null pointer,
  4420. at which point it stops.
  4421. */
  4422. StringArray (const juce_wchar** const strings) throw();
  4423. /** Creates a copy of a null-terminated array of string literals.
  4424. Each item from the array passed-in is added, until it encounters a null pointer,
  4425. at which point it stops.
  4426. */
  4427. StringArray (const char** const strings) throw();
  4428. /** Destructor. */
  4429. virtual ~StringArray() throw();
  4430. /** Copies the contents of another string array into this one */
  4431. const StringArray& operator= (const StringArray& other) throw();
  4432. /** Compares two arrays.
  4433. Comparisons are case-sensitive.
  4434. @returns true only if the other array contains exactly the same strings in the same order
  4435. */
  4436. bool operator== (const StringArray& other) const throw();
  4437. /** Compares two arrays.
  4438. Comparisons are case-sensitive.
  4439. @returns false if the other array contains exactly the same strings in the same order
  4440. */
  4441. bool operator!= (const StringArray& other) const throw();
  4442. /** Returns the number of strings in the array */
  4443. inline int size() const throw() { return strings.size(); };
  4444. /** Returns one of the strings from the array.
  4445. If the index is out-of-range, an empty string is returned.
  4446. Obviously the reference returned shouldn't be stored for later use, as the
  4447. string it refers to may disappear when the array changes.
  4448. */
  4449. const String& operator[] (const int index) const throw();
  4450. /** Searches for a string in the array.
  4451. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4452. @returns true if the string is found inside the array
  4453. */
  4454. bool contains (const String& stringToLookFor,
  4455. const bool ignoreCase = false) const throw();
  4456. /** Searches for a string in the array.
  4457. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4458. @param stringToLookFor the string to try to find
  4459. @param ignoreCase whether the comparison should be case-insensitive
  4460. @param startIndex the first index to start searching from
  4461. @returns the index of the first occurrence of the string in this array,
  4462. or -1 if it isn't found.
  4463. */
  4464. int indexOf (const String& stringToLookFor,
  4465. const bool ignoreCase = false,
  4466. int startIndex = 0) const throw();
  4467. /** Appends a string at the end of the array. */
  4468. void add (const String& stringToAdd) throw();
  4469. /** Inserts a string into the array.
  4470. This will insert a string into the array at the given index, moving
  4471. up the other elements to make room for it.
  4472. If the index is less than zero or greater than the size of the array,
  4473. the new string will be added to the end of the array.
  4474. */
  4475. void insert (const int index,
  4476. const String& stringToAdd) throw();
  4477. /** Adds a string to the array as long as it's not already in there.
  4478. The search can optionally be case-insensitive.
  4479. */
  4480. void addIfNotAlreadyThere (const String& stringToAdd,
  4481. const bool ignoreCase = false) throw();
  4482. /** Replaces one of the strings in the array with another one.
  4483. If the index is higher than the array's size, the new string will be
  4484. added to the end of the array; if it's less than zero nothing happens.
  4485. */
  4486. void set (const int index,
  4487. const String& newString) throw();
  4488. /** Appends some strings from another array to the end of this one.
  4489. @param other the array to add
  4490. @param startIndex the first element of the other array to add
  4491. @param numElementsToAdd the maximum number of elements to add (if this is
  4492. less than zero, they are all added)
  4493. */
  4494. void addArray (const StringArray& other,
  4495. int startIndex = 0,
  4496. int numElementsToAdd = -1) throw();
  4497. /** Breaks up a string into tokens and adds them to this array.
  4498. This will tokenise the given string using whitespace characters as the
  4499. token delimiters, and will add these tokens to the end of the array.
  4500. @returns the number of tokens added
  4501. */
  4502. int addTokens (const tchar* const stringToTokenise,
  4503. const bool preserveQuotedStrings) throw();
  4504. /** Breaks up a string into tokens and adds them to this array.
  4505. This will tokenise the given string (using the string passed in to define the
  4506. token delimiters), and will add these tokens to the end of the array.
  4507. @param stringToTokenise the string to tokenise
  4508. @param breakCharacters a string of characters, any of which will be considered
  4509. to be a token delimiter.
  4510. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4511. which are treated as quotes. Any text occurring
  4512. between quotes is not broken up into tokens.
  4513. @returns the number of tokens added
  4514. */
  4515. int addTokens (const tchar* const stringToTokenise,
  4516. const tchar* breakCharacters,
  4517. const tchar* quoteCharacters) throw();
  4518. /** Breaks up a string into lines and adds them to this array.
  4519. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4520. to the array. Line-break characters are omitted from the strings that are added to
  4521. the array.
  4522. */
  4523. int addLines (const tchar* stringToBreakUp) throw();
  4524. /** Removes all elements from the array. */
  4525. void clear() throw();
  4526. /** Removes a string from the array.
  4527. If the index is out-of-range, no action will be taken.
  4528. */
  4529. void remove (const int index) throw();
  4530. /** Finds a string in the array and removes it.
  4531. This will remove the first occurrence of the given string from the array. The
  4532. comparison may be case-insensitive depending on the ignoreCase parameter.
  4533. */
  4534. void removeString (const String& stringToRemove,
  4535. const bool ignoreCase = false) throw();
  4536. /** Removes any duplicated elements from the array.
  4537. If any string appears in the array more than once, only the first occurrence of
  4538. it will be retained.
  4539. @param ignoreCase whether to use a case-insensitive comparison
  4540. */
  4541. void removeDuplicates (const bool ignoreCase) throw();
  4542. /** Removes empty strings from the array.
  4543. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4544. characters will also be removed
  4545. */
  4546. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4547. /** Moves one of the strings to a different position.
  4548. This will move the string to a specified index, shuffling along
  4549. any intervening elements as required.
  4550. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4551. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4552. @param currentIndex the index of the value to be moved. If this isn't a
  4553. valid index, then nothing will be done
  4554. @param newIndex the index at which you'd like this value to end up. If this
  4555. is less than zero, the value will be moved to the end
  4556. of the array
  4557. */
  4558. void move (const int currentIndex, int newIndex) throw();
  4559. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4560. void trim() throw();
  4561. /** Adds numbers to the strings in the array, to make each string unique.
  4562. This will add numbers to the ends of groups of similar strings.
  4563. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4564. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4565. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4566. also has a number appended to it.
  4567. @param preNumberString when adding a number, this string is added before the number
  4568. @param postNumberString this string is appended after any numbers that are added
  4569. */
  4570. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4571. const bool appendNumberToFirstInstance,
  4572. const tchar* const preNumberString = defaultPreNumberString,
  4573. const tchar* const postNumberString = defaultPostNumberString) throw();
  4574. /** Joins the strings in the array together into one string.
  4575. This will join a range of elements from the array into a string, separating
  4576. them with a given string.
  4577. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4578. @param separatorString the string to insert between all the strings
  4579. @param startIndex the first element to join
  4580. @param numberOfElements how many elements to join together. If this is less
  4581. than zero, all available elements will be used.
  4582. */
  4583. const String joinIntoString (const String& separatorString,
  4584. int startIndex = 0,
  4585. int numberOfElements = -1) const throw();
  4586. /** Sorts the array into alphabetical order.
  4587. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4588. */
  4589. void sort (const bool ignoreCase) throw();
  4590. /** Reduces the amount of storage being used by the array.
  4591. Arrays typically allocate slightly more storage than they need, and after
  4592. removing elements, they may have quite a lot of unused space allocated.
  4593. This method will reduce the amount of allocated storage to a minimum.
  4594. */
  4595. void minimiseStorageOverheads() throw();
  4596. juce_UseDebuggingNewOperator
  4597. private:
  4598. VoidArray strings;
  4599. };
  4600. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4601. /********* End of inlined file: juce_StringArray.h *********/
  4602. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4603. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4604. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4605. /**
  4606. A class to hold a resizable block of raw data.
  4607. */
  4608. class JUCE_API MemoryBlock
  4609. {
  4610. public:
  4611. /** Create an uninitialised block with 0 size. */
  4612. MemoryBlock() throw();
  4613. /** Creates a memory block with a given initial size.
  4614. @param initialSize the size of block to create
  4615. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4616. */
  4617. MemoryBlock (const int initialSize,
  4618. const bool initialiseToZero = false) throw();
  4619. /** Creates a copy of another memory block. */
  4620. MemoryBlock (const MemoryBlock& other) throw();
  4621. /** Creates a memory block using a copy of a block of data.
  4622. @param dataToInitialiseFrom some data to copy into this block
  4623. @param sizeInBytes how much space to use
  4624. */
  4625. MemoryBlock (const void* const dataToInitialiseFrom,
  4626. const int sizeInBytes) throw();
  4627. /** Destructor. */
  4628. ~MemoryBlock() throw();
  4629. /** Copies another memory block onto this one.
  4630. This block will be resized and copied to exactly match the other one.
  4631. */
  4632. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4633. /** Compares two memory blocks.
  4634. @returns true only if the two blocks are the same size and have identical contents.
  4635. */
  4636. bool operator== (const MemoryBlock& other) const throw();
  4637. /** Compares two memory blocks.
  4638. @returns true if the two blocks are different sizes or have different contents.
  4639. */
  4640. bool operator!= (const MemoryBlock& other) const throw();
  4641. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4642. Note that the pointer returned will probably become invalid when the
  4643. block is resized.
  4644. */
  4645. template <class DataType>
  4646. operator DataType*() const throw() { return (DataType*) data; }
  4647. /** Returns a void pointer to the data.
  4648. Note that the pointer returned will probably become invalid when the
  4649. block is resized.
  4650. */
  4651. void* getData() const throw() { return data; }
  4652. /** Returns a byte from the memory block.
  4653. This returns a reference, so you can also use it to set a byte.
  4654. */
  4655. char& operator[] (const int offset) const throw() { return data [offset]; }
  4656. /** Returns the block's current allocated size, in bytes. */
  4657. int getSize() const throw() { return size; }
  4658. /** Resizes the memory block.
  4659. This will try to keep as much of the block's current content as it can,
  4660. and can optionally be made to clear any new space that gets allocated at
  4661. the end of the block.
  4662. @param newSize the new desired size for the block
  4663. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4664. whether to clear the new section or just leave it
  4665. uninitialised
  4666. @see ensureSize
  4667. */
  4668. void setSize (const int newSize,
  4669. const bool initialiseNewSpaceToZero = false) throw();
  4670. /** Increases the block's size only if it's smaller than a given size.
  4671. @param minimumSize if the block is already bigger than this size, no action
  4672. will be taken; otherwise it will be increased to this size
  4673. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4674. whether to clear the new section or just leave it
  4675. uninitialised
  4676. @see setSize
  4677. */
  4678. void ensureSize (const int minimumSize,
  4679. const bool initialiseNewSpaceToZero = false) throw();
  4680. /** Fills the entire memory block with a repeated byte value.
  4681. This is handy for clearing a block of memory to zero.
  4682. */
  4683. void fillWith (const uint8 valueToUse) throw();
  4684. /** Adds another block of data to the end of this one.
  4685. This block's size will be increased accordingly.
  4686. */
  4687. void append (const void* const data,
  4688. const int numBytes) throw();
  4689. /** Copies data into this MemoryBlock from a memory address.
  4690. @param srcData the memory location of the data to copy into this block
  4691. @param destinationOffset the offset in this block at which the data being copied should begin
  4692. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4693. it will be clipped so not to do anything nasty)
  4694. */
  4695. void copyFrom (const void* srcData,
  4696. int destinationOffset,
  4697. int numBytes) throw();
  4698. /** Copies data from this MemoryBlock to a memory address.
  4699. @param destData the memory location to write to
  4700. @param sourceOffset the offset within this block from which the copied data will be read
  4701. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4702. zeros will be used for that portion of the data)
  4703. */
  4704. void copyTo (void* destData,
  4705. int sourceOffset,
  4706. int numBytes) const throw();
  4707. /** Chops out a section of the block.
  4708. This will remove a section of the memory block and close the gap around it,
  4709. shifting any subsequent data downwards and reducing the size of the block.
  4710. If the range specified goes beyond the size of the block, it will be clipped.
  4711. */
  4712. void removeSection (int startByte, int numBytesToRemove) throw();
  4713. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4714. characters in the system's default encoding. */
  4715. const String toString() const throw();
  4716. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4717. The block will be resized to the number of valid bytes read from the string.
  4718. Non-hex characters in the string will be ignored.
  4719. @see String::toHexString()
  4720. */
  4721. void loadFromHexString (const String& sourceHexString) throw();
  4722. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4723. void setBitRange (int bitRangeStart,
  4724. int numBits,
  4725. int binaryNumberToApply) throw();
  4726. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4727. int getBitRange (int bitRangeStart,
  4728. int numBitsToRead) const throw();
  4729. /** Returns a string of characters that represent the binary contents of this block.
  4730. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4731. of simple non-extended characters, e.g. for storage in XML.
  4732. @see fromBase64Encoding
  4733. */
  4734. const String toBase64Encoding() const throw();
  4735. /** Takes a string of encoded characters and turns it into binary data.
  4736. The string passed in must have been created by to64BitEncoding(), and this
  4737. block will be resized to recreate the original data block.
  4738. @see toBase64Encoding
  4739. */
  4740. bool fromBase64Encoding (const String& encodedString) throw();
  4741. juce_UseDebuggingNewOperator
  4742. private:
  4743. char* data;
  4744. int size;
  4745. };
  4746. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4747. /********* End of inlined file: juce_MemoryBlock.h *********/
  4748. class FileInputStream;
  4749. class FileOutputStream;
  4750. /**
  4751. Represents a local file or directory.
  4752. This class encapsulates the absolute pathname of a file or directory, and
  4753. has methods for finding out about the file and changing its properties.
  4754. To read or write to the file, there are methods for returning an input or
  4755. output stream.
  4756. @see FileInputStream, FileOutputStream
  4757. */
  4758. class JUCE_API File
  4759. {
  4760. public:
  4761. /** Creates an (invalid) file object.
  4762. The file is initially set to an empty path, so getFullPath() will return
  4763. an empty string, and comparing the file to File::nonexistent will return
  4764. true.
  4765. You can use its operator= method to point it at a proper file.
  4766. */
  4767. File() throw() {}
  4768. /** Creates a file from an absolute path.
  4769. If the path supplied is a relative path, it is taken to be relative
  4770. to the current working directory (see File::getCurrentWorkingDirectory()),
  4771. but this isn't a recommended way of creating a file, because you
  4772. never know what the CWD is going to be.
  4773. On the Mac/Linux, the path can include "~" notation for referring to
  4774. user home directories.
  4775. */
  4776. File (const String& path) throw();
  4777. /** Creates a copy of another file object. */
  4778. File (const File& other) throw();
  4779. /** Destructor. */
  4780. ~File() throw() {}
  4781. /** Sets the file based on an absolute pathname.
  4782. If the path supplied is a relative path, it is taken to be relative
  4783. to the current working directory (see File::getCurrentWorkingDirectory()),
  4784. but this isn't a recommended way of creating a file, because you
  4785. never know what the CWD is going to be.
  4786. On the Mac/Linux, the path can include "~" notation for referring to
  4787. user home directories.
  4788. */
  4789. const File& operator= (const String& newFilePath) throw();
  4790. /** Copies from another file object. */
  4791. const File& operator= (const File& otherFile) throw();
  4792. /** This static constant is used for referring to an 'invalid' file. */
  4793. static const File nonexistent;
  4794. /** Checks whether the file actually exists.
  4795. @returns true if the file exists, either as a file or a directory.
  4796. @see existsAsFile, isDirectory
  4797. */
  4798. bool exists() const throw();
  4799. /** Checks whether the file exists and is a file rather than a directory.
  4800. @returns true only if this is a real file, false if it's a directory
  4801. or doesn't exist
  4802. @see exists, isDirectory
  4803. */
  4804. bool existsAsFile() const throw();
  4805. /** Checks whether the file is a directory that exists.
  4806. @returns true only if the file is a directory which actually exists, so
  4807. false if it's a file or doesn't exist at all
  4808. @see exists, existsAsFile
  4809. */
  4810. bool isDirectory() const throw();
  4811. /** Returns the size of the file in bytes.
  4812. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4813. */
  4814. int64 getSize() const throw();
  4815. /** Utility function to convert a file size in bytes to a neat string description.
  4816. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4817. 2000000 would produce "2 MB", etc.
  4818. */
  4819. static const String descriptionOfSizeInBytes (const int64 bytes);
  4820. /** Returns the complete, absolute path of this file.
  4821. This includes the filename and all its parent folders. On Windows it'll
  4822. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4823. path starting from the root folder.
  4824. If you just want the file's name, you should use getFileName() or
  4825. getFileNameWithoutExtension().
  4826. @see getFileName, getRelativePathFrom
  4827. */
  4828. const String& getFullPathName() const throw() { return fullPath; }
  4829. /** Returns the last section of the pathname.
  4830. Returns just the final part of the path - e.g. if the whole path
  4831. is "/moose/fish/foo.txt" this will return "foo.txt".
  4832. For a directory, it returns the final part of the path - e.g. for the
  4833. directory "/moose/fish" it'll return "fish".
  4834. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4835. "/moose/.fish", it'll return ".fish"
  4836. @see getFullPathName, getFileNameWithoutExtension
  4837. */
  4838. const String getFileName() const throw();
  4839. /** Creates a relative path that refers to a file relatively to a given directory.
  4840. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4841. would return "../../foo.txt".
  4842. If it's not possible to navigate from one file to the other, an absolute
  4843. path is returned. If the paths are invalid, an empty string may also be
  4844. returned.
  4845. @param directoryToBeRelativeTo the directory which the resultant string will
  4846. be relative to. If this is actually a file rather than
  4847. a directory, its parent directory will be used instead.
  4848. If it doesn't exist, it's assumed to be a directory.
  4849. @see getChildFile, isAbsolutePath
  4850. */
  4851. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4852. /** Returns the file's extension.
  4853. Returns the file extension of this file, also including the dot.
  4854. e.g. "/moose/fish/foo.txt" would return ".txt"
  4855. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4856. */
  4857. const String getFileExtension() const throw();
  4858. /** Checks whether the file has a given extension.
  4859. @param extensionToTest the extension to look for - it doesn't matter whether or
  4860. not this string has a dot at the start, so ".wav" and "wav"
  4861. will have the same effect. The comparison used is
  4862. case-insensitve.
  4863. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4864. */
  4865. bool hasFileExtension (const String& extensionToTest) const throw();
  4866. /** Returns a version of this file with a different file extension.
  4867. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4868. @param newExtension the new extension, either with or without a dot at the start (this
  4869. doesn't make any difference). To get remove a file's extension altogether,
  4870. pass an empty string into this function.
  4871. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4872. */
  4873. const File withFileExtension (const String& newExtension) const throw();
  4874. /** Returns the last part of the filename, without its file extension.
  4875. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4876. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4877. */
  4878. const String getFileNameWithoutExtension() const throw();
  4879. /** Returns a 32-bit hash-code that identifies this file.
  4880. This is based on the filename. Obviously it's possible, although unlikely, that
  4881. two files will have the same hash-code.
  4882. */
  4883. int hashCode() const throw();
  4884. /** Returns a 64-bit hash-code that identifies this file.
  4885. This is based on the filename. Obviously it's possible, although unlikely, that
  4886. two files will have the same hash-code.
  4887. */
  4888. int64 hashCode64() const throw();
  4889. /** Returns a file based on a relative path.
  4890. This will find a child file or directory of the current object.
  4891. e.g.
  4892. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4893. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4894. If the string is actually an absolute path, it will be treated as such, e.g.
  4895. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4896. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4897. */
  4898. const File getChildFile (String relativePath) const throw();
  4899. /** Returns a file which is in the same directory as this one.
  4900. This is equivalent to getParentDirectory().getChildFile (name).
  4901. @see getChildFile, getParentDirectory
  4902. */
  4903. const File getSiblingFile (const String& siblingFileName) const throw();
  4904. /** Returns the directory that contains this file or directory.
  4905. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4906. */
  4907. const File getParentDirectory() const throw();
  4908. /** Checks whether a file is somewhere inside a directory.
  4909. Returns true if this file is somewhere inside a subdirectory of the directory
  4910. that is passed in. Neither file actually has to exist, because the function
  4911. just checks the paths for similarities.
  4912. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4913. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4914. */
  4915. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4916. /** Chooses a filename relative to this one that doesn't already exist.
  4917. If this file is a directory, this will return a child file of this
  4918. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4919. it finds one that isn't already there.
  4920. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4921. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4922. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4923. @param prefix the string to use for the filename before the number
  4924. @param suffix the string to add to the filename after the number
  4925. @param putNumbersInBrackets if true, this will create filenames in the
  4926. format "prefix(number)suffix", if false, it will leave the
  4927. brackets out.
  4928. */
  4929. const File getNonexistentChildFile (const String& prefix,
  4930. const String& suffix,
  4931. bool putNumbersInBrackets = true) const throw();
  4932. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4933. If this file doesn't exist, this will just return itself, otherwise it
  4934. will return an appropriate sibling that doesn't exist, e.g. if a file
  4935. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4936. @param putNumbersInBrackets whether to add brackets around the numbers that
  4937. get appended to the new filename.
  4938. */
  4939. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4940. /** Compares the pathnames for two files. */
  4941. bool operator== (const File& otherFile) const throw();
  4942. /** Compares the pathnames for two files. */
  4943. bool operator!= (const File& otherFile) const throw();
  4944. /** Checks whether a file can be created or written to.
  4945. @returns true if it's possible to create and write to this file. If the file
  4946. doesn't already exist, this will check its parent directory to
  4947. see if writing is allowed.
  4948. @see setReadOnly
  4949. */
  4950. bool hasWriteAccess() const throw();
  4951. /** Changes the write-permission of a file or directory.
  4952. @param shouldBeReadOnly whether to add or remove write-permission
  4953. @param applyRecursively if the file is a directory and this is true, it will
  4954. recurse through all the subfolders changing the permissions
  4955. of all files
  4956. @returns true if it manages to change the file's permissions.
  4957. @see hasWriteAccess
  4958. */
  4959. bool setReadOnly (const bool shouldBeReadOnly,
  4960. const bool applyRecursively = false) const throw();
  4961. /** Returns true if this file is a hidden or system file.
  4962. The criteria for deciding whether a file is hidden are platform-dependent.
  4963. */
  4964. bool isHidden() const throw();
  4965. /** If this file is a link, this returns the file that it points to.
  4966. If this file isn't actually link, it'll just return itself.
  4967. */
  4968. const File getLinkedTarget() const throw();
  4969. /** Returns the last modification time of this file.
  4970. @returns the time, or an invalid time if the file doesn't exist.
  4971. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4972. */
  4973. const Time getLastModificationTime() const throw();
  4974. /** Returns the last time this file was accessed.
  4975. @returns the time, or an invalid time if the file doesn't exist.
  4976. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4977. */
  4978. const Time getLastAccessTime() const throw();
  4979. /** Returns the time that this file was created.
  4980. @returns the time, or an invalid time if the file doesn't exist.
  4981. @see getLastModificationTime, getLastAccessTime
  4982. */
  4983. const Time getCreationTime() const throw();
  4984. /** Changes the modification 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 getLastModificationTime, setLastAccessTime, setCreationTime
  4988. */
  4989. bool setLastModificationTime (const Time& newTime) const throw();
  4990. /** Changes the last-access time 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 getLastAccessTime, setLastModificationTime, setCreationTime
  4994. */
  4995. bool setLastAccessTime (const Time& newTime) const throw();
  4996. /** Changes the creation date for this file.
  4997. @param newTime the time to apply to the file
  4998. @returns true if it manages to change the file's time.
  4999. @see getCreationTime, setLastModificationTime, setLastAccessTime
  5000. */
  5001. bool setCreationTime (const Time& newTime) const throw();
  5002. /** If possible, this will try to create a version string for the given file.
  5003. The OS may be able to look at the file and give a version for it - e.g. with
  5004. executables, bundles, dlls, etc. If no version is available, this will
  5005. return an empty string.
  5006. */
  5007. const String getVersion() const throw();
  5008. /** Creates an empty file if it doesn't already exist.
  5009. If the file that this object refers to doesn't exist, this will create a file
  5010. of zero size.
  5011. If it already exists or is a directory, this method will do nothing.
  5012. @returns true if the file has been created (or if it already existed).
  5013. @see createDirectory
  5014. */
  5015. bool create() const throw();
  5016. /** Creates a new directory for this filename.
  5017. This will try to create the file as a directory, and fill also create
  5018. any parent directories it needs in order to complete the operation.
  5019. @returns true if the directory has been created successfully, (or if it
  5020. already existed beforehand).
  5021. @see create
  5022. */
  5023. bool createDirectory() const throw();
  5024. /** Deletes a file.
  5025. If this file is actually a directory, it may not be deleted correctly if it
  5026. contains files. See deleteRecursively() as a better way of deleting directories.
  5027. @returns true if the file has been successfully deleted (or if it didn't exist to
  5028. begin with).
  5029. @see deleteRecursively
  5030. */
  5031. bool deleteFile() const throw();
  5032. /** Deletes a file or directory and all its subdirectories.
  5033. If this file is a directory, this will try to delete it and all its subfolders. If
  5034. it's just a file, it will just try to delete the file.
  5035. @returns true if the file and all its subfolders have been successfully deleted
  5036. (or if it didn't exist to begin with).
  5037. @see deleteFile
  5038. */
  5039. bool deleteRecursively() const throw();
  5040. /** Moves this file or folder to the trash.
  5041. @returns true if the operation succeeded. It could fail if the trash is full, or
  5042. if the file is write-protected, so you should check the return value
  5043. and act appropriately.
  5044. */
  5045. bool moveToTrash() const throw();
  5046. /** Moves or renames a file.
  5047. Tries to move a file to a different location.
  5048. If the target file already exists, this will attempt to delete it first, and
  5049. will fail if this can't be done.
  5050. Note that the destination file isn't the directory to put it in, it's the actual
  5051. filename that you want the new file to have.
  5052. @returns true if the operation succeeds
  5053. */
  5054. bool moveFileTo (const File& targetLocation) const throw();
  5055. /** Copies a file.
  5056. Tries to copy a file to a different location.
  5057. If the target file already exists, this will attempt to delete it first, and
  5058. will fail if this can't be done.
  5059. @returns true if the operation succeeds
  5060. */
  5061. bool copyFileTo (const File& targetLocation) const throw();
  5062. /** Copies a directory.
  5063. Tries to copy an entire directory, recursively.
  5064. If this file isn't a directory or if any target files can't be created, this
  5065. will return false.
  5066. @param newDirectory the directory that this one should be copied to. Note that this
  5067. is the name of the actual directory to create, not the directory
  5068. into which the new one should be placed, so there must be enough
  5069. write privileges to create it if it doesn't exist. Any files inside
  5070. it will be overwritten by similarly named ones that are copied.
  5071. */
  5072. bool copyDirectoryTo (const File& newDirectory) const throw();
  5073. /** Used in file searching, to specify whether to return files, directories, or both.
  5074. */
  5075. enum TypesOfFileToFind
  5076. {
  5077. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5078. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5079. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5080. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5081. };
  5082. /** Searches inside a directory for files matching a wildcard pattern.
  5083. Assuming that this file is a directory, this method will search it
  5084. for either files or subdirectories whose names match a filename pattern.
  5085. @param results an array to which File objects will be added for the
  5086. files that the search comes up with
  5087. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5088. return files, directories, or both. If the ignoreHiddenFiles flag
  5089. is also added to this value, hidden files won't be returned
  5090. @param searchRecursively if true, all subdirectories will be recursed into to do
  5091. an exhaustive search
  5092. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5093. @returns the number of results that have been found
  5094. @see getNumberOfChildFiles, DirectoryIterator
  5095. */
  5096. int findChildFiles (OwnedArray<File>& results,
  5097. const int whatToLookFor,
  5098. const bool searchRecursively,
  5099. const String& wildCardPattern = JUCE_T("*")) const throw();
  5100. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5101. Assuming that this file is a directory, this method will search it
  5102. for either files or subdirectories whose names match a filename pattern,
  5103. and will return the number of matches found.
  5104. This isn't a recursive call, and will only search this directory, not
  5105. its children.
  5106. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5107. count files, directories, or both. If the ignoreHiddenFiles flag
  5108. is also added to this value, hidden files won't be counted
  5109. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5110. @returns the number of matches found
  5111. @see findChildFiles, DirectoryIterator
  5112. */
  5113. int getNumberOfChildFiles (const int whatToLookFor,
  5114. const String& wildCardPattern = JUCE_T("*")) const throw();
  5115. /** Returns true if this file is a directory that contains one or more subdirectories.
  5116. @see isDirectory, findChildFiles
  5117. */
  5118. bool containsSubDirectories() const throw();
  5119. /** Creates a stream to read from this file.
  5120. @returns a stream that will read from this file (initially positioned at the
  5121. start of the file), or 0 if the file can't be opened for some reason
  5122. @see createOutputStream, loadFileAsData
  5123. */
  5124. FileInputStream* createInputStream() const throw();
  5125. /** Creates a stream to write to this file.
  5126. If the file exists, the stream that is returned will be positioned ready for
  5127. writing at the end of the file, so you might want to use deleteFile() first
  5128. to write to an empty file.
  5129. @returns a stream that will write to this file (initially positioned at the
  5130. end of the file), or 0 if the file can't be opened for some reason
  5131. @see createInputStream, printf, appendData, appendText
  5132. */
  5133. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5134. /** Loads a file's contents into memory as a block of binary data.
  5135. Of course, trying to load a very large file into memory will blow up, so
  5136. it's better to check first.
  5137. @param result the data block to which the file's contents should be appended - note
  5138. that if the memory block might already contain some data, you
  5139. might want to clear it first
  5140. @returns true if the file could all be read into memory
  5141. */
  5142. bool loadFileAsData (MemoryBlock& result) const throw();
  5143. /** Reads a file into memory as a string.
  5144. Attempts to load the entire file as a zero-terminated string.
  5145. This makes use of InputStream::readEntireStreamAsString, which should
  5146. automatically cope with unicode/acsii file formats.
  5147. */
  5148. const String loadFileAsString() const throw();
  5149. /** Writes text to the end of the file.
  5150. This will try to do a printf to the file.
  5151. @returns false if it can't write to the file for some reason
  5152. */
  5153. bool printf (const tchar* format, ...) const throw();
  5154. /** Appends a block of binary data to the end of the file.
  5155. This will try to write the given buffer to the end of the file.
  5156. @returns false if it can't write to the file for some reason
  5157. */
  5158. bool appendData (const void* const dataToAppend,
  5159. const int numberOfBytes) const throw();
  5160. /** Replaces this file's contents with a given block of data.
  5161. This will delete the file and replace it with the given data.
  5162. A nice feature of this method is that it's safe - instead of deleting
  5163. the file first and then re-writing it, it creates a new temporary file,
  5164. writes the data to that, and then moves the new file to replace the existing
  5165. file. This means that if the power gets pulled out or something crashes,
  5166. you're a lot less likely to end up with an empty file..
  5167. Returns true if the operation succeeds, or false if it fails.
  5168. @see appendText
  5169. */
  5170. bool replaceWithData (const void* const dataToWrite,
  5171. const int numberOfBytes) const throw();
  5172. /** Appends a string to the end of the file.
  5173. This will try to append a text string to the file, as either 16-bit unicode
  5174. or 8-bit characters in the default system encoding.
  5175. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5176. the endianness of the file.
  5177. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5178. @see replaceWithText
  5179. */
  5180. bool appendText (const String& textToAppend,
  5181. const bool asUnicode = false,
  5182. const bool writeUnicodeHeaderBytes = false) const throw();
  5183. /** Replaces this file's contents with a given text string.
  5184. This will delete the file and replace it with the given text.
  5185. A nice feature of this method is that it's safe - instead of deleting
  5186. the file first and then re-writing it, it creates a new temporary file,
  5187. writes the text to that, and then moves the new file to replace the existing
  5188. file. This means that if the power gets pulled out or something crashes,
  5189. you're a lot less likely to end up with an empty file..
  5190. For an explanation of the parameters here, see the appendText() method.
  5191. Returns true if the operation succeeds, or false if it fails.
  5192. @see appendText
  5193. */
  5194. bool replaceWithText (const String& textToWrite,
  5195. const bool asUnicode = false,
  5196. const bool writeUnicodeHeaderBytes = false) const throw();
  5197. /** Creates a set of files to represent each file root.
  5198. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5199. to which ones are available. On the Mac/Linux, this will probably
  5200. just add a single entry for "/".
  5201. */
  5202. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5203. /** Finds the name of the drive on which this file lives.
  5204. @returns the volume label of the drive, or an empty string if this isn't possible
  5205. */
  5206. const String getVolumeLabel() const throw();
  5207. /** Returns the serial number of the volume on which this file lives.
  5208. @returns the serial number, or zero if there's a problem doing this
  5209. */
  5210. int getVolumeSerialNumber() const throw();
  5211. /** Returns the number of bytes free on the drive that this file lives on.
  5212. @returns the number of bytes free, or 0 if there's a problem finding this out
  5213. @see getVolumeTotalSize
  5214. */
  5215. int64 getBytesFreeOnVolume() const throw();
  5216. /** Returns the total size of the drive that contains this file.
  5217. @returns the total number of bytes that the volume can hold
  5218. @see getBytesFreeOnVolume
  5219. */
  5220. int64 getVolumeTotalSize() const throw();
  5221. /** Returns true if this file is on a CD or DVD drive. */
  5222. bool isOnCDRomDrive() const throw();
  5223. /** Returns true if this file is on a hard disk.
  5224. This will fail if it's a network drive, but will still be true for
  5225. removable hard-disks.
  5226. */
  5227. bool isOnHardDisk() const throw();
  5228. /** Returns true if this file is on a removable disk drive.
  5229. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5230. */
  5231. bool isOnRemovableDrive() const throw();
  5232. /** Launches the file as a process.
  5233. - if the file is executable, this will run it.
  5234. - if it's a document of some kind, it will launch the document with its
  5235. default viewer application.
  5236. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5237. @see revealToUser
  5238. */
  5239. bool startAsProcess (const String& parameters = String::empty) const throw();
  5240. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  5241. @see startAsProcess
  5242. */
  5243. void revealToUser() const throw();
  5244. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5245. */
  5246. enum SpecialLocationType
  5247. {
  5248. /** The user's home folder. This is the same as using File ("~"). */
  5249. userHomeDirectory,
  5250. /** The user's default documents folder. On Windows, this might be the user's
  5251. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5252. doesn't tend to have one of these, so it might just return their home folder.
  5253. */
  5254. userDocumentsDirectory,
  5255. /** The folder that contains the user's desktop objects. */
  5256. userDesktopDirectory,
  5257. /** The folder in which applications store their persistent user-specific settings.
  5258. On Windows, this might be "\Documents and Settings\username\Application Data".
  5259. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5260. always create your own sub-folder to put them in, to avoid making a mess.
  5261. */
  5262. userApplicationDataDirectory,
  5263. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5264. of the computer, rather than just the current user.
  5265. On the Mac it'll be "/Library", on Windows, it could be something like
  5266. "\Documents and Settings\All Users\Application Data".
  5267. Depending on the setup, this folder may be read-only.
  5268. */
  5269. commonApplicationDataDirectory,
  5270. /** The folder that should be used for temporary files.
  5271. Always delete them when you're finished, to keep the user's computer tidy!
  5272. */
  5273. tempDirectory,
  5274. /** Returns this application's executable file.
  5275. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5276. host app.
  5277. On the mac this will return the unix binary, not the package folder - see
  5278. currentApplicationFile for that.
  5279. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  5280. file link, invokedExecutableFile will return the name of the link.
  5281. */
  5282. currentExecutableFile,
  5283. /** Returns this application's location.
  5284. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5285. host app.
  5286. On the mac this will return the package folder (if it's in one), not the unix binary
  5287. that's inside it - compare with currentExecutableFile.
  5288. */
  5289. currentApplicationFile,
  5290. /** Returns the file that was invoked to launch this executable.
  5291. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  5292. will return the name of the link that was used, whereas currentExecutableFile will return
  5293. the actual location of the target executable.
  5294. */
  5295. invokedExecutableFile,
  5296. /** The directory in which applications normally get installed.
  5297. So on windows, this would be something like "c:\program files", on the
  5298. Mac "/Applications", or "/usr" on linux.
  5299. */
  5300. globalApplicationsDirectory,
  5301. /** The most likely place where a user might store their music files.
  5302. */
  5303. userMusicDirectory,
  5304. /** The most likely place where a user might store their movie files.
  5305. */
  5306. userMoviesDirectory,
  5307. };
  5308. /** Finds the location of a special type of file or directory, such as a home folder or
  5309. documents folder.
  5310. @see SpecialLocationType
  5311. */
  5312. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5313. /** Returns a temporary file in the system's temp directory.
  5314. This will try to return the name of a non-existent temp file.
  5315. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5316. */
  5317. static const File createTempFile (const String& fileNameEnding) throw();
  5318. /** Returns the current working directory.
  5319. @see setAsCurrentWorkingDirectory
  5320. */
  5321. static const File getCurrentWorkingDirectory() throw();
  5322. /** Sets the current working directory to be this file.
  5323. For this to work the file must point to a valid directory.
  5324. @returns true if the current directory has been changed.
  5325. @see getCurrentWorkingDirectory
  5326. */
  5327. bool setAsCurrentWorkingDirectory() const throw();
  5328. /** The system-specific file separator character.
  5329. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5330. */
  5331. static const tchar separator;
  5332. /** The system-specific file separator character, as a string.
  5333. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5334. */
  5335. static const tchar* separatorString;
  5336. /** Removes illegal characters from a filename.
  5337. This will return a copy of the given string after removing characters
  5338. that are not allowed in a legal filename, and possibly shortening the
  5339. string if it's too long.
  5340. Because this will remove slashes, don't use it on an absolute pathname.
  5341. @see createLegalPathName
  5342. */
  5343. static const String createLegalFileName (const String& fileNameToFix) throw();
  5344. /** Removes illegal characters from a pathname.
  5345. Similar to createLegalFileName(), but this won't remove slashes, so can
  5346. be used on a complete pathname.
  5347. @see createLegalFileName
  5348. */
  5349. static const String createLegalPathName (const String& pathNameToFix) throw();
  5350. /** Indicates whether filenames are case-sensitive on the current operating system.
  5351. */
  5352. static bool areFileNamesCaseSensitive();
  5353. /** Returns true if the string seems to be a fully-specified absolute path.
  5354. */
  5355. static bool isAbsolutePath (const String& path) throw();
  5356. juce_UseDebuggingNewOperator
  5357. private:
  5358. String fullPath;
  5359. // internal way of contructing a file without checking the path
  5360. friend class DirectoryIterator;
  5361. File (const String&, int) throw();
  5362. const String getPathUpToLastSlash() const throw();
  5363. };
  5364. #endif // __JUCE_FILE_JUCEHEADER__
  5365. /********* End of inlined file: juce_File.h *********/
  5366. /**
  5367. A simple implemenation of a Logger that writes to a file.
  5368. @see Logger
  5369. */
  5370. class JUCE_API FileLogger : public Logger
  5371. {
  5372. public:
  5373. /** Creates a FileLogger for a given file.
  5374. @param fileToWriteTo the file that to use - new messages will be appended
  5375. to the file. If the file doesn't exist, it will be created,
  5376. along with any parent directories that are needed.
  5377. @param welcomeMessage when opened, the logger will write a header to the log, along
  5378. with the current date and time, and this welcome message
  5379. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5380. but is larger than this number of bytes, then the start of the
  5381. file will be truncated to keep the size down. This prevents a log
  5382. file getting ridiculously large over time. The file will be truncated
  5383. at a new-line boundary. If this value is less than zero, no size limit
  5384. will be imposed; if it's zero, the file will always be deleted. Note that
  5385. the size is only checked once when this object is created - any logging
  5386. that is done later will be appended without any checking
  5387. */
  5388. FileLogger (const File& fileToWriteTo,
  5389. const String& welcomeMessage,
  5390. const int maxInitialFileSizeBytes = 128 * 1024);
  5391. /** Destructor. */
  5392. ~FileLogger();
  5393. void logMessage (const String& message);
  5394. /** Helper function to create a log file in the correct place for this platform.
  5395. On Windows this will return a logger with a path such as:
  5396. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5397. On the Mac it'll create something like:
  5398. ~/Library/Logs/[logFileName]
  5399. The method might return 0 if the file can't be created for some reason.
  5400. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5401. it's best to use the something like the name of your application here.
  5402. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5403. call it "log.txt" because if it goes in a directory with logs
  5404. from other applications (as it will do on the Mac) then no-one
  5405. will know which one is yours!
  5406. @param welcomeMessage a message that will be written to the log when it's opened.
  5407. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5408. */
  5409. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5410. const String& logFileName,
  5411. const String& welcomeMessage,
  5412. const int maxInitialFileSizeBytes = 128 * 1024);
  5413. juce_UseDebuggingNewOperator
  5414. private:
  5415. File logFile;
  5416. CriticalSection logLock;
  5417. FileOutputStream* logStream;
  5418. void trimFileSize (int maxFileSizeBytes) const;
  5419. FileLogger (const FileLogger&);
  5420. const FileLogger& operator= (const FileLogger&);
  5421. };
  5422. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5423. /********* End of inlined file: juce_FileLogger.h *********/
  5424. #endif
  5425. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5426. /********* Start of inlined file: juce_Initialisation.h *********/
  5427. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5428. #define __JUCE_INITIALISATION_JUCEHEADER__
  5429. /** Initialises Juce's GUI classes.
  5430. If you're embedding Juce into an application that uses its own event-loop rather
  5431. than using the START_JUCE_APPLICATION macro, call this function before making any
  5432. Juce calls, to make sure things are initialised correctly.
  5433. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5434. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5435. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5436. */
  5437. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5438. /** Clears up any static data being used by Juce's GUI classes.
  5439. If you're embedding Juce into an application that uses its own event-loop rather
  5440. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5441. code to clean up any juce objects that might be lying around.
  5442. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5443. */
  5444. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5445. /** Initialises the core parts of Juce.
  5446. If you're embedding Juce into either a command-line program, call this function
  5447. at the start of your main() function to make sure that Juce is initialised correctly.
  5448. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5449. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5450. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5451. */
  5452. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5453. /** Clears up any static data being used by Juce's non-gui core classes.
  5454. If you're embedding Juce into either a command-line program, call this function
  5455. at the end of your main() function if you want to make sure any Juce objects are
  5456. cleaned up correctly.
  5457. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5458. */
  5459. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5460. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5461. /********* End of inlined file: juce_Initialisation.h *********/
  5462. #endif
  5463. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5464. #endif
  5465. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5466. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  5467. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5468. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5469. /**
  5470. A collection of miscellaneous platform-specific utilities.
  5471. */
  5472. class JUCE_API PlatformUtilities
  5473. {
  5474. public:
  5475. /** Plays the operating system's default alert 'beep' sound. */
  5476. static void beep();
  5477. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  5478. const String& emailSubject,
  5479. const String& bodyText,
  5480. const StringArray& filesToAttach);
  5481. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  5482. /** MAC ONLY - Turns a Core CF String into a juce one. */
  5483. static const String cfStringToJuceString (CFStringRef cfString);
  5484. /** MAC ONLY - Turns a juce string into a Core CF one. */
  5485. static CFStringRef juceStringToCFString (const String& s);
  5486. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  5487. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  5488. /** MAC ONLY - Turns an FSRef into a juce string path. */
  5489. static const String makePathFromFSRef (FSRef* file);
  5490. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  5491. their precomposed equivalents.
  5492. */
  5493. static const String convertToPrecomposedUnicode (const String& s);
  5494. /** MAC ONLY - Gets the type of a file from the file's resources. */
  5495. static OSType getTypeOfFile (const String& filename);
  5496. /** MAC ONLY - Returns true if this file is actually a bundle. */
  5497. static bool isBundle (const String& filename);
  5498. /** MAC ONLY - Adds an item to the dock */
  5499. static void addItemToDock (const File& file);
  5500. /** MAC ONLY - Returns the current OS version number.
  5501. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  5502. */
  5503. static int getOSXMinorVersionNumber() throw();
  5504. #endif
  5505. #if JUCE_WINDOWS || DOXYGEN
  5506. // Some registry helper functions:
  5507. /** WIN32 ONLY - Returns a string from the registry.
  5508. The path is a string for the entire path of a value in the registry,
  5509. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  5510. */
  5511. static const String getRegistryValue (const String& regValuePath,
  5512. const String& defaultValue = String::empty);
  5513. /** WIN32 ONLY - Sets a registry value as a string.
  5514. This will take care of creating any groups needed to get to the given
  5515. registry value.
  5516. */
  5517. static void setRegistryValue (const String& regValuePath,
  5518. const String& value);
  5519. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  5520. static bool registryValueExists (const String& regValuePath);
  5521. /** WIN32 ONLY - Deletes a registry value. */
  5522. static void deleteRegistryValue (const String& regValuePath);
  5523. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  5524. static void deleteRegistryKey (const String& regKeyPath);
  5525. /** WIN32 ONLY - Creates a file association in the registry.
  5526. This lets you set the exe that should be launched by a given file extension.
  5527. @param fileExtension the file extension to associate, including the
  5528. initial dot, e.g. ".txt"
  5529. @param symbolicDescription a space-free short token to identify the file type
  5530. @param fullDescription a human-readable description of the file type
  5531. @param targetExecutable the executable that should be launched
  5532. @param iconResourceNumber the icon that gets displayed for the file type will be
  5533. found by looking up this resource number in the
  5534. executable. Pass 0 here to not use an icon
  5535. */
  5536. static void registerFileAssociation (const String& fileExtension,
  5537. const String& symbolicDescription,
  5538. const String& fullDescription,
  5539. const File& targetExecutable,
  5540. int iconResourceNumber);
  5541. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  5542. In a normal Juce application this will be set to the module handle
  5543. of the application executable.
  5544. If you're writing a DLL using Juce and plan to use any Juce messaging or
  5545. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  5546. to set the correct module handle in your DllMain() function, because
  5547. the win32 system relies on the correct instance handle when opening windows.
  5548. */
  5549. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  5550. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  5551. @see getCurrentModuleInstanceHandle()
  5552. */
  5553. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  5554. /** WIN32 ONLY - Gets the command-line params as a string.
  5555. This is needed to avoid unicode problems with the argc type params.
  5556. */
  5557. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  5558. #endif
  5559. /** Clears the floating point unit's flags.
  5560. Only has an effect under win32, currently.
  5561. */
  5562. static void fpuReset();
  5563. #if JUCE_LINUX || JUCE_WINDOWS
  5564. /** Loads a dynamically-linked library into the process's address space.
  5565. @param pathOrFilename the platform-dependent name and search path
  5566. @returns a handle which can be used by getProcedureEntryPoint(), or
  5567. zero if it fails.
  5568. @see freeDynamicLibrary, getProcedureEntryPoint
  5569. */
  5570. static void* loadDynamicLibrary (const String& pathOrFilename);
  5571. /** Frees a dynamically-linked library.
  5572. @param libraryHandle a handle created by loadDynamicLibrary
  5573. @see loadDynamicLibrary, getProcedureEntryPoint
  5574. */
  5575. static void freeDynamicLibrary (void* libraryHandle);
  5576. /** Finds a procedure call in a dynamically-linked library.
  5577. @param libraryHandle a library handle returned by loadDynamicLibrary
  5578. @param procedureName the name of the procedure call to try to load
  5579. @returns a pointer to the function if found, or 0 if it fails
  5580. @see loadDynamicLibrary
  5581. */
  5582. static void* getProcedureEntryPoint (void* libraryHandle,
  5583. const String& procedureName);
  5584. #endif
  5585. #if JUCE_LINUX || DOXYGEN
  5586. #endif
  5587. };
  5588. #if JUCE_MAC || JUCE_IPHONE
  5589. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  5590. using RAII.
  5591. */
  5592. class ScopedAutoReleasePool
  5593. {
  5594. public:
  5595. ScopedAutoReleasePool();
  5596. ~ScopedAutoReleasePool();
  5597. private:
  5598. void* pool;
  5599. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  5600. const ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  5601. };
  5602. #endif
  5603. #if JUCE_MAC
  5604. /**
  5605. A wrapper class for picking up events from an Apple IR remote control device.
  5606. To use it, just create a subclass of this class, implementing the buttonPressed()
  5607. callback, then call start() and stop() to start or stop receiving events.
  5608. */
  5609. class JUCE_API AppleRemoteDevice
  5610. {
  5611. public:
  5612. AppleRemoteDevice();
  5613. virtual ~AppleRemoteDevice();
  5614. /** The set of buttons that may be pressed.
  5615. @see buttonPressed
  5616. */
  5617. enum ButtonType
  5618. {
  5619. menuButton = 0, /**< The menu button (if it's held for a short time). */
  5620. playButton, /**< The play button. */
  5621. plusButton, /**< The plus or volume-up button. */
  5622. minusButton, /**< The minus or volume-down button. */
  5623. rightButton, /**< The right button (if it's held for a short time). */
  5624. leftButton, /**< The left button (if it's held for a short time). */
  5625. rightButton_Long, /**< The right button (if it's held for a long time). */
  5626. leftButton_Long, /**< The menu button (if it's held for a long time). */
  5627. menuButton_Long, /**< The menu button (if it's held for a long time). */
  5628. playButtonSleepMode,
  5629. switched
  5630. };
  5631. /** Override this method to receive the callback about a button press.
  5632. The callback will happen on the application's message thread.
  5633. Some buttons trigger matching up and down events, in which the isDown parameter
  5634. will be true and then false. Others only send a single event when the
  5635. button is pressed.
  5636. */
  5637. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  5638. /** Starts the device running and responding to events.
  5639. Returns true if it managed to open the device.
  5640. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  5641. and will not be available to any other part of the system. If
  5642. false, it will be shared with other apps.
  5643. @see stop
  5644. */
  5645. bool start (const bool inExclusiveMode) throw();
  5646. /** Stops the device running.
  5647. @see start
  5648. */
  5649. void stop() throw();
  5650. /** Returns true if the device has been started successfully.
  5651. */
  5652. bool isActive() const throw();
  5653. /** Returns the ID number of the remote, if it has sent one.
  5654. */
  5655. int getRemoteId() const throw() { return remoteId; }
  5656. juce_UseDebuggingNewOperator
  5657. /** @internal */
  5658. void handleCallbackInternal();
  5659. private:
  5660. void* device;
  5661. void* queue;
  5662. int remoteId;
  5663. bool open (const bool openInExclusiveMode) throw();
  5664. AppleRemoteDevice (const AppleRemoteDevice&);
  5665. const AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  5666. };
  5667. #endif
  5668. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5669. /********* End of inlined file: juce_PlatformUtilities.h *********/
  5670. #endif
  5671. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5672. #endif
  5673. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5674. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  5675. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5676. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5677. /** A timer for measuring performance of code and dumping the results to a file.
  5678. e.g. @code
  5679. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  5680. for (;;)
  5681. {
  5682. pc.start();
  5683. doSomethingFishy();
  5684. pc.stop();
  5685. }
  5686. @endcode
  5687. In this example, the time of each period between calling start/stop will be
  5688. measured and averaged over 50 runs, and the results printed to a file
  5689. every 50 times round the loop.
  5690. */
  5691. class JUCE_API PerformanceCounter
  5692. {
  5693. public:
  5694. /** Creates a PerformanceCounter object.
  5695. @param counterName the name used when printing out the statistics
  5696. @param runsPerPrintout the number of start/stop iterations before calling
  5697. printStatistics()
  5698. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  5699. the results are just written to the debugger output
  5700. */
  5701. PerformanceCounter (const String& counterName,
  5702. int runsPerPrintout = 100,
  5703. const File& loggingFile = File::nonexistent);
  5704. /** Destructor. */
  5705. ~PerformanceCounter();
  5706. /** Starts timing.
  5707. @see stop
  5708. */
  5709. void start();
  5710. /** Stops timing and prints out the results.
  5711. The number of iterations before doing a printout of the
  5712. results is set in the constructor.
  5713. @see start
  5714. */
  5715. void stop();
  5716. /** Dumps the current metrics to the debugger output and to a file.
  5717. As well as using Logger::outputDebugString to print the results,
  5718. this will write then to the file specified in the constructor (if
  5719. this was valid).
  5720. */
  5721. void printStatistics();
  5722. juce_UseDebuggingNewOperator
  5723. private:
  5724. String name;
  5725. int numRuns, runsPerPrint;
  5726. double totalTime;
  5727. int64 started;
  5728. File outputFile;
  5729. };
  5730. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5731. /********* End of inlined file: juce_PerformanceCounter.h *********/
  5732. #endif
  5733. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5734. #endif
  5735. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5736. /********* Start of inlined file: juce_Singleton.h *********/
  5737. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5738. #define __JUCE_SINGLETON_JUCEHEADER__
  5739. /********* Start of inlined file: juce_ScopedLock.h *********/
  5740. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5741. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5742. /**
  5743. Automatically locks and unlocks a CriticalSection object.
  5744. Use one of these as a local variable to control access to a CriticalSection.
  5745. e.g. @code
  5746. CriticalSection myCriticalSection;
  5747. for (;;)
  5748. {
  5749. const ScopedLock myScopedLock (myCriticalSection);
  5750. // myCriticalSection is now locked
  5751. ...do some stuff...
  5752. // myCriticalSection gets unlocked here.
  5753. }
  5754. @endcode
  5755. @see CriticalSection, ScopedUnlock
  5756. */
  5757. class JUCE_API ScopedLock
  5758. {
  5759. public:
  5760. /** Creates a ScopedLock.
  5761. As soon as it is created, this will lock the CriticalSection, and
  5762. when the ScopedLock object is deleted, the CriticalSection will
  5763. be unlocked.
  5764. Make sure this object is created and deleted by the same thread,
  5765. otherwise there are no guarantees what will happen! Best just to use it
  5766. as a local stack object, rather than creating one with the new() operator.
  5767. */
  5768. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5769. /** Destructor.
  5770. The CriticalSection will be unlocked when the destructor is called.
  5771. Make sure this object is created and deleted by the same thread,
  5772. otherwise there are no guarantees what will happen!
  5773. */
  5774. inline ~ScopedLock() throw() { lock_.exit(); }
  5775. private:
  5776. const CriticalSection& lock_;
  5777. ScopedLock (const ScopedLock&);
  5778. const ScopedLock& operator= (const ScopedLock&);
  5779. };
  5780. /**
  5781. Automatically unlocks and re-locks a CriticalSection object.
  5782. This is the reverse of a ScopedLock object - instead of locking the critical
  5783. section for the lifetime of this object, it unlocks it.
  5784. Make sure you don't try to unlock critical sections that aren't actually locked!
  5785. e.g. @code
  5786. CriticalSection myCriticalSection;
  5787. for (;;)
  5788. {
  5789. const ScopedLock myScopedLock (myCriticalSection);
  5790. // myCriticalSection is now locked
  5791. ... do some stuff with it locked ..
  5792. while (xyz)
  5793. {
  5794. ... do some stuff with it locked ..
  5795. const ScopedUnlock unlocker (myCriticalSection);
  5796. // myCriticalSection is now unlocked for the remainder of this block,
  5797. // and re-locked at the end.
  5798. ...do some stuff with it unlocked ...
  5799. }
  5800. // myCriticalSection gets unlocked here.
  5801. }
  5802. @endcode
  5803. @see CriticalSection, ScopedLock
  5804. */
  5805. class ScopedUnlock
  5806. {
  5807. public:
  5808. /** Creates a ScopedUnlock.
  5809. As soon as it is created, this will unlock the CriticalSection, and
  5810. when the ScopedLock object is deleted, the CriticalSection will
  5811. be re-locked.
  5812. Make sure this object is created and deleted by the same thread,
  5813. otherwise there are no guarantees what will happen! Best just to use it
  5814. as a local stack object, rather than creating one with the new() operator.
  5815. */
  5816. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5817. /** Destructor.
  5818. The CriticalSection will be unlocked when the destructor is called.
  5819. Make sure this object is created and deleted by the same thread,
  5820. otherwise there are no guarantees what will happen!
  5821. */
  5822. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5823. private:
  5824. const CriticalSection& lock_;
  5825. ScopedUnlock (const ScopedLock&);
  5826. const ScopedUnlock& operator= (const ScopedUnlock&);
  5827. };
  5828. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5829. /********* End of inlined file: juce_ScopedLock.h *********/
  5830. /**
  5831. Macro to declare member variables and methods for a singleton class.
  5832. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  5833. to the class's definition.
  5834. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5835. implementation code.
  5836. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  5837. destructor, in case it is deleted by other means than deleteInstance()
  5838. Clients can then call the static method MyClass::getInstance() to get a pointer
  5839. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  5840. no instance currently exists.
  5841. e.g. @code
  5842. class MySingleton
  5843. {
  5844. public:
  5845. MySingleton()
  5846. {
  5847. }
  5848. ~MySingleton()
  5849. {
  5850. // this ensures that no dangling pointers are left when the
  5851. // singleton is deleted.
  5852. clearSingletonInstance();
  5853. }
  5854. juce_DeclareSingleton (MySingleton, false)
  5855. };
  5856. juce_ImplementSingleton (MySingleton)
  5857. // example of usage:
  5858. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5859. ...
  5860. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5861. @endcode
  5862. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  5863. than once during the process's lifetime - i.e. after you've created and deleted the
  5864. object, getInstance() will refuse to create another one. This can be useful to stop
  5865. objects being accidentally re-created during your app's shutdown code.
  5866. If you know that your object will only be created and deleted by a single thread, you
  5867. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5868. of this one.
  5869. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5870. */
  5871. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  5872. \
  5873. static classname* _singletonInstance; \
  5874. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5875. \
  5876. static classname* getInstance() \
  5877. { \
  5878. if (_singletonInstance == 0) \
  5879. {\
  5880. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5881. \
  5882. if (_singletonInstance == 0) \
  5883. { \
  5884. static bool alreadyInside = false; \
  5885. static bool createdOnceAlready = false; \
  5886. \
  5887. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  5888. jassert (! problem); \
  5889. if (! problem) \
  5890. { \
  5891. createdOnceAlready = true; \
  5892. alreadyInside = true; \
  5893. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5894. alreadyInside = false; \
  5895. \
  5896. _singletonInstance = newObject; \
  5897. } \
  5898. } \
  5899. } \
  5900. \
  5901. return _singletonInstance; \
  5902. } \
  5903. \
  5904. static inline classname* getInstanceWithoutCreating() throw() \
  5905. { \
  5906. return _singletonInstance; \
  5907. } \
  5908. \
  5909. static void deleteInstance() \
  5910. { \
  5911. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5912. if (_singletonInstance != 0) \
  5913. { \
  5914. classname* const old = _singletonInstance; \
  5915. _singletonInstance = 0; \
  5916. delete old; \
  5917. } \
  5918. } \
  5919. \
  5920. void clearSingletonInstance() throw() \
  5921. { \
  5922. if (_singletonInstance == this) \
  5923. _singletonInstance = 0; \
  5924. }
  5925. /** This is a counterpart to the juce_DeclareSingleton macro.
  5926. After adding the juce_DeclareSingleton to the class definition, this macro has
  5927. to be used in the cpp file.
  5928. */
  5929. #define juce_ImplementSingleton(classname) \
  5930. \
  5931. classname* classname::_singletonInstance = 0; \
  5932. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5933. /**
  5934. Macro to declare member variables and methods for a singleton class.
  5935. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5936. section to make access to it thread-safe. If you know that your object will
  5937. only ever be created or deleted by a single thread, then this is a
  5938. more efficient version to use.
  5939. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  5940. than once during the process's lifetime - i.e. after you've created and deleted the
  5941. object, getInstance() will refuse to create another one. This can be useful to stop
  5942. objects being accidentally re-created during your app's shutdown code.
  5943. See the documentation for juce_DeclareSingleton for more information about
  5944. how to use it, the only difference being that you have to use
  5945. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5946. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5947. */
  5948. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  5949. \
  5950. static classname* _singletonInstance; \
  5951. \
  5952. static classname* getInstance() \
  5953. { \
  5954. if (_singletonInstance == 0) \
  5955. { \
  5956. static bool alreadyInside = false; \
  5957. static bool createdOnceAlready = false; \
  5958. \
  5959. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  5960. jassert (! problem); \
  5961. if (! problem) \
  5962. { \
  5963. createdOnceAlready = true; \
  5964. alreadyInside = true; \
  5965. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5966. alreadyInside = false; \
  5967. \
  5968. _singletonInstance = newObject; \
  5969. } \
  5970. } \
  5971. \
  5972. return _singletonInstance; \
  5973. } \
  5974. \
  5975. static inline classname* getInstanceWithoutCreating() throw() \
  5976. { \
  5977. return _singletonInstance; \
  5978. } \
  5979. \
  5980. static void deleteInstance() \
  5981. { \
  5982. if (_singletonInstance != 0) \
  5983. { \
  5984. classname* const old = _singletonInstance; \
  5985. _singletonInstance = 0; \
  5986. delete old; \
  5987. } \
  5988. } \
  5989. \
  5990. void clearSingletonInstance() throw() \
  5991. { \
  5992. if (_singletonInstance == this) \
  5993. _singletonInstance = 0; \
  5994. }
  5995. /**
  5996. Macro to declare member variables and methods for a singleton class.
  5997. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5998. for recursion or repeated instantiation. It's intended for use as a lightweight
  5999. version of a singleton, where you're using it in very straightforward
  6000. circumstances and don't need the extra checking.
  6001. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  6002. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  6003. See the documentation for juce_DeclareSingleton for more information about
  6004. how to use it, the only difference being that you have to use
  6005. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  6006. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  6007. */
  6008. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  6009. \
  6010. static classname* _singletonInstance; \
  6011. \
  6012. static classname* getInstance() \
  6013. { \
  6014. if (_singletonInstance == 0) \
  6015. _singletonInstance = new classname(); \
  6016. \
  6017. return _singletonInstance; \
  6018. } \
  6019. \
  6020. static inline classname* getInstanceWithoutCreating() throw() \
  6021. { \
  6022. return _singletonInstance; \
  6023. } \
  6024. \
  6025. static void deleteInstance() \
  6026. { \
  6027. if (_singletonInstance != 0) \
  6028. { \
  6029. classname* const old = _singletonInstance; \
  6030. _singletonInstance = 0; \
  6031. delete old; \
  6032. } \
  6033. } \
  6034. \
  6035. void clearSingletonInstance() throw() \
  6036. { \
  6037. if (_singletonInstance == this) \
  6038. _singletonInstance = 0; \
  6039. }
  6040. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  6041. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  6042. to the class definition, this macro has to be used somewhere in the cpp file.
  6043. */
  6044. #define juce_ImplementSingleton_SingleThreaded(classname) \
  6045. \
  6046. classname* classname::_singletonInstance = 0;
  6047. #endif // __JUCE_SINGLETON_JUCEHEADER__
  6048. /********* End of inlined file: juce_Singleton.h *********/
  6049. #endif
  6050. #ifndef __JUCE_RANDOM_JUCEHEADER__
  6051. /********* Start of inlined file: juce_Random.h *********/
  6052. #ifndef __JUCE_RANDOM_JUCEHEADER__
  6053. #define __JUCE_RANDOM_JUCEHEADER__
  6054. /********* Start of inlined file: juce_BitArray.h *********/
  6055. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6056. #define __JUCE_BITARRAY_JUCEHEADER__
  6057. class MemoryBlock;
  6058. /**
  6059. An array of on/off bits, also usable to store large binary integers.
  6060. A BitArray acts like an arbitrarily large integer whose bits can be set or
  6061. cleared, and some basic mathematical operations can be done on the number as
  6062. a whole.
  6063. */
  6064. class JUCE_API BitArray
  6065. {
  6066. public:
  6067. /** Creates an empty BitArray */
  6068. BitArray() throw();
  6069. /** Creates a BitArray containing an integer value in its low bits.
  6070. The low 32 bits of the array are initialised with this value.
  6071. */
  6072. BitArray (const unsigned int value) throw();
  6073. /** Creates a BitArray containing an integer value in its low bits.
  6074. The low 32 bits of the array are initialised with the absolute value
  6075. passed in, and its sign is set to reflect the sign of the number.
  6076. */
  6077. BitArray (const int value) throw();
  6078. /** Creates a BitArray containing an integer value in its low bits.
  6079. The low 64 bits of the array are initialised with the absolute value
  6080. passed in, and its sign is set to reflect the sign of the number.
  6081. */
  6082. BitArray (int64 value) throw();
  6083. /** Creates a copy of another BitArray. */
  6084. BitArray (const BitArray& other) throw();
  6085. /** Destructor. */
  6086. ~BitArray() throw();
  6087. /** Copies another BitArray onto this one. */
  6088. const BitArray& operator= (const BitArray& other) throw();
  6089. /** Two arrays are the same if the same bits are set. */
  6090. bool operator== (const BitArray& other) const throw();
  6091. /** Two arrays are the same if the same bits are set. */
  6092. bool operator!= (const BitArray& other) const throw();
  6093. /** Clears all bits in the BitArray to 0. */
  6094. void clear() throw();
  6095. /** Clears a particular bit in the array. */
  6096. void clearBit (const int bitNumber) throw();
  6097. /** Sets a specified bit to 1.
  6098. If the bit number is high, this will grow the array to accomodate it.
  6099. */
  6100. void setBit (const int bitNumber) throw();
  6101. /** Sets or clears a specified bit. */
  6102. void setBit (const int bitNumber,
  6103. const bool shouldBeSet) throw();
  6104. /** Sets a range of bits to be either on or off.
  6105. @param startBit the first bit to change
  6106. @param numBits the number of bits to change
  6107. @param shouldBeSet whether to turn these bits on or off
  6108. */
  6109. void setRange (int startBit,
  6110. int numBits,
  6111. const bool shouldBeSet) throw();
  6112. /** Inserts a bit an a given position, shifting up any bits above it. */
  6113. void insertBit (const int bitNumber,
  6114. const bool shouldBeSet) throw();
  6115. /** Returns the value of a specified bit in the array.
  6116. If the index is out-of-range, the result will be false.
  6117. */
  6118. bool operator[] (const int bit) const throw();
  6119. /** Returns true if no bits are set. */
  6120. bool isEmpty() const throw();
  6121. /** Returns a range of bits in the array as a new BitArray.
  6122. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  6123. @see getBitRangeAsInt
  6124. */
  6125. const BitArray getBitRange (int startBit, int numBits) const throw();
  6126. /** Returns a range of bits in the array as an integer value.
  6127. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  6128. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  6129. getBitRange().
  6130. */
  6131. int getBitRangeAsInt (int startBit, int numBits) const throw();
  6132. /** Sets a range of bits in the array based on an integer value.
  6133. Copies the given integer into the array, starting at startBit,
  6134. and only using up to numBits of the available bits.
  6135. */
  6136. void setBitRangeAsInt (int startBit, int numBits,
  6137. unsigned int valueToSet) throw();
  6138. /** Performs a bitwise OR with another BitArray.
  6139. The result ends up in this array.
  6140. */
  6141. void orWith (const BitArray& other) throw();
  6142. /** Performs a bitwise AND with another BitArray.
  6143. The result ends up in this array.
  6144. */
  6145. void andWith (const BitArray& other) throw();
  6146. /** Performs a bitwise XOR with another BitArray.
  6147. The result ends up in this array.
  6148. */
  6149. void xorWith (const BitArray& other) throw();
  6150. /** Adds another BitArray's value to this one.
  6151. Treating the two arrays as large positive integers, this
  6152. adds them up and puts the result in this array.
  6153. */
  6154. void add (const BitArray& other) throw();
  6155. /** Subtracts another BitArray's value from this one.
  6156. Treating the two arrays as large positive integers, this
  6157. subtracts them and puts the result in this array.
  6158. Note that if the result should be negative, this won't be
  6159. handled correctly.
  6160. */
  6161. void subtract (const BitArray& other) throw();
  6162. /** Multiplies another BitArray's value with this one.
  6163. Treating the two arrays as large positive integers, this
  6164. multiplies them and puts the result in this array.
  6165. */
  6166. void multiplyBy (const BitArray& other) throw();
  6167. /** Divides another BitArray's value into this one and also produces a remainder.
  6168. Treating the two arrays as large positive integers, this
  6169. divides this value by the other, leaving the quotient in this
  6170. array, and the remainder is copied into the other BitArray passed in.
  6171. */
  6172. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  6173. /** Returns the largest value that will divide both this value and the one
  6174. passed-in.
  6175. */
  6176. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  6177. /** Performs a modulo operation on this value.
  6178. The result is stored in this value.
  6179. */
  6180. void modulo (const BitArray& divisor) throw();
  6181. /** Performs a combined exponent and modulo operation.
  6182. This BitArray's value becomes (this ^ exponent) % modulus.
  6183. */
  6184. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  6185. /** Performs an inverse modulo on the value.
  6186. i.e. the result is (this ^ -1) mod (modulus).
  6187. */
  6188. void inverseModulo (const BitArray& modulus) throw();
  6189. /** Shifts a section of bits left or right.
  6190. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  6191. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  6192. */
  6193. void shiftBits (int howManyBitsLeft,
  6194. int startBit = 0) throw();
  6195. /** Does a signed comparison of two BitArrays.
  6196. Return values are:
  6197. - 0 if the numbers are the same
  6198. - < 0 if this number is smaller than the other
  6199. - > 0 if this number is bigger than the other
  6200. */
  6201. int compare (const BitArray& other) const throw();
  6202. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  6203. Return values are:
  6204. - 0 if the numbers are the same
  6205. - < 0 if this number is smaller than the other
  6206. - > 0 if this number is bigger than the other
  6207. */
  6208. int compareAbsolute (const BitArray& other) const throw();
  6209. /** Returns true if the value is less than zero.
  6210. @see setNegative, negate
  6211. */
  6212. bool isNegative() const throw();
  6213. /** Changes the sign of the number to be positive or negative.
  6214. @see isNegative, negate
  6215. */
  6216. void setNegative (const bool shouldBeNegative) throw();
  6217. /** Inverts the sign of the number.
  6218. @see isNegative, setNegative
  6219. */
  6220. void negate() throw();
  6221. /** Counts the total number of set bits in the array. */
  6222. int countNumberOfSetBits() const throw();
  6223. /** Looks for the index of the next set bit after a given starting point.
  6224. searches from startIndex (inclusive) upwards for the first set bit,
  6225. and returns its index.
  6226. If no set bits are found, it returns -1.
  6227. */
  6228. int findNextSetBit (int startIndex = 0) const throw();
  6229. /** Looks for the index of the next clear bit after a given starting point.
  6230. searches from startIndex (inclusive) upwards for the first clear bit,
  6231. and returns its index.
  6232. */
  6233. int findNextClearBit (int startIndex = 0) const throw();
  6234. /** Returns the index of the highest set bit in the array.
  6235. If the array is empty, this will return -1.
  6236. */
  6237. int getHighestBit() const throw();
  6238. /** Converts the array to a number string.
  6239. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  6240. If minuimumNumCharacters is greater than 0, the returned string will be
  6241. padded with leading zeros to reach at least that length.
  6242. */
  6243. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  6244. /** Converts a number string to an array.
  6245. Any non-valid characters will be ignored.
  6246. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  6247. */
  6248. void parseString (const String& text,
  6249. const int base) throw();
  6250. /** Turns the array into a block of binary data.
  6251. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  6252. of the array, and so on.
  6253. @see loadFromMemoryBlock
  6254. */
  6255. const MemoryBlock toMemoryBlock() const throw();
  6256. /** Copies a block of raw data onto this array.
  6257. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  6258. of the array, and so on.
  6259. @see toMemoryBlock
  6260. */
  6261. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  6262. juce_UseDebuggingNewOperator
  6263. private:
  6264. void ensureSize (const int numVals) throw();
  6265. unsigned int* values;
  6266. int numValues, highestBit;
  6267. bool negative;
  6268. };
  6269. #endif // __JUCE_BITARRAY_JUCEHEADER__
  6270. /********* End of inlined file: juce_BitArray.h *********/
  6271. /**
  6272. A simple pseudo-random number generator.
  6273. */
  6274. class JUCE_API Random
  6275. {
  6276. public:
  6277. /** Creates a Random object based on a seed value.
  6278. For a given seed value, the subsequent numbers generated by this object
  6279. will be predictable, so a good idea is to set this value based
  6280. on the time, e.g.
  6281. new Random (Time::currentTimeMillis())
  6282. */
  6283. Random (const int64 seedValue) throw();
  6284. /** Destructor. */
  6285. ~Random() throw();
  6286. /** Returns the next random 32 bit integer.
  6287. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  6288. */
  6289. int nextInt() throw();
  6290. /** Returns the next random number, limited to a given range.
  6291. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  6292. */
  6293. int nextInt (const int maxValue) throw();
  6294. /** Returns the next 64-bit random number.
  6295. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  6296. */
  6297. int64 nextInt64() throw();
  6298. /** Returns the next random floating-point number.
  6299. @returns a random value in the range 0 to 1.0
  6300. */
  6301. float nextFloat() throw();
  6302. /** Returns the next random floating-point number.
  6303. @returns a random value in the range 0 to 1.0
  6304. */
  6305. double nextDouble() throw();
  6306. /** Returns the next random boolean value.
  6307. */
  6308. bool nextBool() throw();
  6309. /** Returns a BitArray containing a random number.
  6310. @returns a random value in the range 0 to (maximumValue - 1).
  6311. */
  6312. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  6313. /** Sets a range of bits in a BitArray to random values. */
  6314. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  6315. /** To avoid the overhead of having to create a new Random object whenever
  6316. you need a number, this is a shared application-wide object that
  6317. can be used.
  6318. It's not thread-safe though, so threads should use their own Random object.
  6319. */
  6320. static Random& getSystemRandom() throw();
  6321. /** Resets this Random object to a given seed value. */
  6322. void setSeed (const int64 newSeed) throw();
  6323. /** Reseeds this generator using a value generated from various semi-random system
  6324. properties like the current time, etc.
  6325. Because this function convolves the time with the last seed value, calling
  6326. it repeatedly will increase the randomness of the final result.
  6327. */
  6328. void setSeedRandomly();
  6329. juce_UseDebuggingNewOperator
  6330. private:
  6331. int64 seed;
  6332. };
  6333. #endif // __JUCE_RANDOM_JUCEHEADER__
  6334. /********* End of inlined file: juce_Random.h *********/
  6335. #endif
  6336. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  6337. #endif
  6338. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6339. /********* Start of inlined file: juce_SystemStats.h *********/
  6340. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6341. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  6342. /**
  6343. Contains methods for finding out about the current hardware and OS configuration.
  6344. */
  6345. class JUCE_API SystemStats
  6346. {
  6347. public:
  6348. /** Returns the current version of JUCE,
  6349. (just in case you didn't already know at compile-time.)
  6350. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  6351. */
  6352. static const String getJUCEVersion() throw();
  6353. /** The set of possible results of the getOperatingSystemType() method.
  6354. */
  6355. enum OperatingSystemType
  6356. {
  6357. UnknownOS = 0,
  6358. MacOSX = 0x1000,
  6359. Linux = 0x2000,
  6360. Win95 = 0x4001,
  6361. Win98 = 0x4002,
  6362. WinNT351 = 0x4103,
  6363. WinNT40 = 0x4104,
  6364. Win2000 = 0x4105,
  6365. WinXP = 0x4106,
  6366. WinVista = 0x4107,
  6367. Windows7 = 0x4108,
  6368. Windows = 0x4000, /**< To test whether any version of Windows is running,
  6369. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  6370. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  6371. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  6372. };
  6373. /** Returns the type of operating system we're running on.
  6374. @returns one of the values from the OperatingSystemType enum.
  6375. @see getOperatingSystemName
  6376. */
  6377. static OperatingSystemType getOperatingSystemType() throw();
  6378. /** Returns the name of the type of operating system we're running on.
  6379. @returns a string describing the OS type.
  6380. @see getOperatingSystemType
  6381. */
  6382. static const String getOperatingSystemName() throw();
  6383. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  6384. */
  6385. static bool isOperatingSystem64Bit() throw();
  6386. // CPU and memory information..
  6387. /** Returns the approximate CPU speed.
  6388. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6389. what year you're reading this...)
  6390. */
  6391. static int getCpuSpeedInMegaherz() throw();
  6392. /** Returns a string to indicate the CPU vendor.
  6393. Might not be known on some systems.
  6394. */
  6395. static const String getCpuVendor() throw();
  6396. /** Checks whether Intel MMX instructions are available. */
  6397. static bool hasMMX() throw();
  6398. /** Checks whether Intel SSE instructions are available. */
  6399. static bool hasSSE() throw();
  6400. /** Checks whether Intel SSE2 instructions are available. */
  6401. static bool hasSSE2() throw();
  6402. /** Checks whether AMD 3DNOW instructions are available. */
  6403. static bool has3DNow() throw();
  6404. /** Returns the number of CPUs.
  6405. */
  6406. static int getNumCpus() throw();
  6407. /** Returns a clock-cycle tick counter, if available.
  6408. If the machine can do it, this will return a tick-count
  6409. where each tick is one cpu clock cycle - used for profiling
  6410. code.
  6411. @returns the tick count, or zero if not available.
  6412. */
  6413. static int64 getClockCycleCounter() throw();
  6414. /** Finds out how much RAM is in the machine.
  6415. @returns the approximate number of megabytes of memory, or zero if
  6416. something goes wrong when finding out.
  6417. */
  6418. static int getMemorySizeInMegabytes() throw();
  6419. /** Returns the system page-size.
  6420. This is only used by programmers with beards.
  6421. */
  6422. static int getPageSize() throw();
  6423. /** Returns a list of MAC addresses found on this machine.
  6424. @param addresses an array into which the MAC addresses should be copied
  6425. @param maxNum the number of elements in this array
  6426. @param littleEndian the endianness of the numbers to return. If this is true,
  6427. the least-significant byte of each number is the first byte
  6428. of the mac address. If false, the least significant byte is
  6429. the last number. Note that the default values of this parameter
  6430. are different on Mac/PC to avoid breaking old software that was
  6431. written before this parameter was added (when the two systems
  6432. defaulted to using different endiannesses). In newer
  6433. software you probably want to specify an explicit value
  6434. for this.
  6435. @returns the number of MAC addresses that were found
  6436. */
  6437. static int getMACAddresses (int64* addresses, int maxNum,
  6438. #if JUCE_MAC
  6439. const bool littleEndian = true) throw();
  6440. #else
  6441. const bool littleEndian = false) throw();
  6442. #endif
  6443. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6444. static void initialiseStats() throw();
  6445. };
  6446. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6447. /********* End of inlined file: juce_SystemStats.h *********/
  6448. #endif
  6449. #ifndef __JUCE_TIME_JUCEHEADER__
  6450. #endif
  6451. #ifndef __JUCE_UUID_JUCEHEADER__
  6452. /********* Start of inlined file: juce_Uuid.h *********/
  6453. #ifndef __JUCE_UUID_JUCEHEADER__
  6454. #define __JUCE_UUID_JUCEHEADER__
  6455. /**
  6456. A universally unique 128-bit identifier.
  6457. This class generates very random unique numbers based on the system time
  6458. and MAC addresses if any are available. It's extremely unlikely that two identical
  6459. UUIDs would ever be created by chance.
  6460. The class includes methods for saving the ID as a string or as raw binary data.
  6461. */
  6462. class JUCE_API Uuid
  6463. {
  6464. public:
  6465. /** Creates a new unique ID. */
  6466. Uuid();
  6467. /** Destructor. */
  6468. ~Uuid() throw();
  6469. /** Creates a copy of another UUID. */
  6470. Uuid (const Uuid& other);
  6471. /** Copies another UUID. */
  6472. Uuid& operator= (const Uuid& other);
  6473. /** Returns true if the ID is zero. */
  6474. bool isNull() const throw();
  6475. /** Compares two UUIDs. */
  6476. bool operator== (const Uuid& other) const;
  6477. /** Compares two UUIDs. */
  6478. bool operator!= (const Uuid& other) const;
  6479. /** Returns a stringified version of this UUID.
  6480. A Uuid object can later be reconstructed from this string using operator= or
  6481. the constructor that takes a string parameter.
  6482. @returns a 32 character hex string.
  6483. */
  6484. const String toString() const;
  6485. /** Creates an ID from an encoded string version.
  6486. @see toString
  6487. */
  6488. Uuid (const String& uuidString);
  6489. /** Copies from a stringified UUID.
  6490. The string passed in should be one that was created with the toString() method.
  6491. */
  6492. Uuid& operator= (const String& uuidString);
  6493. /** Returns a pointer to the internal binary representation of the ID.
  6494. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  6495. the constructor or operator= method that takes an array of uint8s.
  6496. */
  6497. const uint8* getRawData() const throw() { return value.asBytes; }
  6498. /** Creates a UUID from a 16-byte array.
  6499. @see getRawData
  6500. */
  6501. Uuid (const uint8* const rawData);
  6502. /** Sets this UUID from 16-bytes of raw data. */
  6503. Uuid& operator= (const uint8* const rawData);
  6504. juce_UseDebuggingNewOperator
  6505. private:
  6506. union
  6507. {
  6508. uint8 asBytes [16];
  6509. int asInt[4];
  6510. int64 asInt64[2];
  6511. } value;
  6512. };
  6513. #endif // __JUCE_UUID_JUCEHEADER__
  6514. /********* End of inlined file: juce_Uuid.h *********/
  6515. #endif
  6516. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  6517. #endif
  6518. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  6519. #endif
  6520. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  6521. #endif
  6522. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6523. #endif
  6524. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6525. #endif
  6526. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6527. /********* Start of inlined file: juce_Variant.h *********/
  6528. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6529. #define __JUCE_VARIANT_JUCEHEADER__
  6530. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  6531. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6532. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6533. /**
  6534. Adds reference-counting to an object.
  6535. To add reference-counting to a class, derive it from this class, and
  6536. use the ReferenceCountedObjectPtr class to point to it.
  6537. e.g. @code
  6538. class MyClass : public ReferenceCountedObject
  6539. {
  6540. void foo();
  6541. // This is a neat way of declaring a typedef for a pointer class,
  6542. // rather than typing out the full templated name each time..
  6543. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  6544. };
  6545. MyClass::Ptr p = new MyClass();
  6546. MyClass::Ptr p2 = p;
  6547. p = 0;
  6548. p2->foo();
  6549. @endcode
  6550. Once a new ReferenceCountedObject has been assigned to a pointer, be
  6551. careful not to delete the object manually.
  6552. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  6553. */
  6554. class JUCE_API ReferenceCountedObject
  6555. {
  6556. public:
  6557. /** Increments the object's reference count.
  6558. This is done automatically by the smart pointer, but is public just
  6559. in case it's needed for nefarious purposes.
  6560. */
  6561. inline void incReferenceCount() throw()
  6562. {
  6563. atomicIncrement (refCounts);
  6564. jassert (refCounts > 0);
  6565. }
  6566. /** Decreases the object's reference count.
  6567. If the count gets to zero, the object will be deleted.
  6568. */
  6569. inline void decReferenceCount() throw()
  6570. {
  6571. jassert (refCounts > 0);
  6572. if (atomicDecrementAndReturn (refCounts) == 0)
  6573. delete this;
  6574. }
  6575. /** Returns the object's current reference count. */
  6576. inline int getReferenceCount() const throw()
  6577. {
  6578. return refCounts;
  6579. }
  6580. protected:
  6581. /** Creates the reference-counted object (with an initial ref count of zero). */
  6582. ReferenceCountedObject()
  6583. : refCounts (0)
  6584. {
  6585. }
  6586. /** Destructor. */
  6587. virtual ~ReferenceCountedObject()
  6588. {
  6589. // it's dangerous to delete an object that's still referenced by something else!
  6590. jassert (refCounts == 0);
  6591. }
  6592. private:
  6593. int refCounts;
  6594. };
  6595. /**
  6596. Used to point to an object of type ReferenceCountedObject.
  6597. It's wise to use a typedef instead of typing out the templated name
  6598. each time - e.g.
  6599. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  6600. @see ReferenceCountedObject, ReferenceCountedObjectArray
  6601. */
  6602. template <class ReferenceCountedObjectClass>
  6603. class ReferenceCountedObjectPtr
  6604. {
  6605. public:
  6606. /** Creates a pointer to a null object. */
  6607. inline ReferenceCountedObjectPtr() throw()
  6608. : referencedObject (0)
  6609. {
  6610. }
  6611. /** Creates a pointer to an object.
  6612. This will increment the object's reference-count if it is non-null.
  6613. */
  6614. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  6615. : referencedObject (refCountedObject)
  6616. {
  6617. if (refCountedObject != 0)
  6618. refCountedObject->incReferenceCount();
  6619. }
  6620. /** Copies another pointer.
  6621. This will increment the object's reference-count (if it is non-null).
  6622. */
  6623. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  6624. : referencedObject (other.referencedObject)
  6625. {
  6626. if (referencedObject != 0)
  6627. referencedObject->incReferenceCount();
  6628. }
  6629. /** Changes this pointer to point at a different object.
  6630. The reference count of the old object is decremented, and it might be
  6631. deleted if it hits zero. The new object's count is incremented.
  6632. */
  6633. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  6634. {
  6635. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  6636. if (newObject != referencedObject)
  6637. {
  6638. if (newObject != 0)
  6639. newObject->incReferenceCount();
  6640. ReferenceCountedObjectClass* const oldObject = referencedObject;
  6641. referencedObject = newObject;
  6642. if (oldObject != 0)
  6643. oldObject->decReferenceCount();
  6644. }
  6645. return *this;
  6646. }
  6647. /** Changes this pointer to point at a different object.
  6648. The reference count of the old object is decremented, and it might be
  6649. deleted if it hits zero. The new object's count is incremented.
  6650. */
  6651. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  6652. {
  6653. if (referencedObject != newObject)
  6654. {
  6655. if (newObject != 0)
  6656. newObject->incReferenceCount();
  6657. ReferenceCountedObjectClass* const oldObject = referencedObject;
  6658. referencedObject = newObject;
  6659. if (oldObject != 0)
  6660. oldObject->decReferenceCount();
  6661. }
  6662. return *this;
  6663. }
  6664. /** Destructor.
  6665. This will decrement the object's reference-count, and may delete it if it
  6666. gets to zero.
  6667. */
  6668. inline ~ReferenceCountedObjectPtr()
  6669. {
  6670. if (referencedObject != 0)
  6671. referencedObject->decReferenceCount();
  6672. }
  6673. /** Returns the object that this pointer references.
  6674. The pointer returned may be zero, of course.
  6675. */
  6676. inline operator ReferenceCountedObjectClass*() const throw()
  6677. {
  6678. return referencedObject;
  6679. }
  6680. /** Returns true if this pointer refers to the given object. */
  6681. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  6682. {
  6683. return referencedObject == object;
  6684. }
  6685. /** Returns true if this pointer doesn't refer to the given object. */
  6686. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  6687. {
  6688. return referencedObject != object;
  6689. }
  6690. // the -> operator is called on the referenced object
  6691. inline ReferenceCountedObjectClass* operator->() const throw()
  6692. {
  6693. return referencedObject;
  6694. }
  6695. private:
  6696. ReferenceCountedObjectClass* referencedObject;
  6697. };
  6698. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6699. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  6700. /********* Start of inlined file: juce_OutputStream.h *********/
  6701. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6702. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6703. /********* Start of inlined file: juce_InputStream.h *********/
  6704. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6705. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6706. /** The base class for streams that read data.
  6707. Input and output streams are used throughout the library - subclasses can override
  6708. some or all of the virtual functions to implement their behaviour.
  6709. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6710. */
  6711. class JUCE_API InputStream
  6712. {
  6713. public:
  6714. /** Destructor. */
  6715. virtual ~InputStream() {}
  6716. /** Returns the total number of bytes available for reading in this stream.
  6717. Note that this is the number of bytes available from the start of the
  6718. stream, not from the current position.
  6719. If the size of the stream isn't actually known, this may return -1.
  6720. */
  6721. virtual int64 getTotalLength() = 0;
  6722. /** Returns true if the stream has no more data to read. */
  6723. virtual bool isExhausted() = 0;
  6724. /** Reads a set of bytes from the stream into a memory buffer.
  6725. This is the only read method that subclasses actually need to implement, as the
  6726. InputStream base class implements the other read methods in terms of this one (although
  6727. it's often more efficient for subclasses to implement them directly).
  6728. @param destBuffer the destination buffer for the data
  6729. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6730. memory block passed in is big enough to contain this
  6731. many bytes.
  6732. @returns the actual number of bytes that were read, which may be less than
  6733. maxBytesToRead if the stream is exhausted before it gets that far
  6734. */
  6735. virtual int read (void* destBuffer,
  6736. int maxBytesToRead) = 0;
  6737. /** Reads a byte from the stream.
  6738. If the stream is exhausted, this will return zero.
  6739. @see OutputStream::writeByte
  6740. */
  6741. virtual char readByte();
  6742. /** Reads a boolean from the stream.
  6743. The bool is encoded as a single byte - 1 for true, 0 for false.
  6744. If the stream is exhausted, this will return false.
  6745. @see OutputStream::writeBool
  6746. */
  6747. virtual bool readBool();
  6748. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6749. If the next two bytes read are byte1 and byte2, this returns
  6750. (byte1 | (byte2 << 8)).
  6751. If the stream is exhausted partway through reading the bytes, this will return zero.
  6752. @see OutputStream::writeShort, readShortBigEndian
  6753. */
  6754. virtual short readShort();
  6755. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6756. If the next two bytes read are byte1 and byte2, this returns
  6757. (byte2 | (byte1 << 8)).
  6758. If the stream is exhausted partway through reading the bytes, this will return zero.
  6759. @see OutputStream::writeShortBigEndian, readShort
  6760. */
  6761. virtual short readShortBigEndian();
  6762. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6763. If the next four bytes are byte1 to byte4, this returns
  6764. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6765. If the stream is exhausted partway through reading the bytes, this will return zero.
  6766. @see OutputStream::writeInt, readIntBigEndian
  6767. */
  6768. virtual int readInt();
  6769. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6770. If the next four bytes are byte1 to byte4, this returns
  6771. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6772. If the stream is exhausted partway through reading the bytes, this will return zero.
  6773. @see OutputStream::writeIntBigEndian, readInt
  6774. */
  6775. virtual int readIntBigEndian();
  6776. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6777. If the next eight bytes are byte1 to byte8, this returns
  6778. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6779. If the stream is exhausted partway through reading the bytes, this will return zero.
  6780. @see OutputStream::writeInt64, readInt64BigEndian
  6781. */
  6782. virtual int64 readInt64();
  6783. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6784. If the next eight bytes are byte1 to byte8, this returns
  6785. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6786. If the stream is exhausted partway through reading the bytes, this will return zero.
  6787. @see OutputStream::writeInt64BigEndian, readInt64
  6788. */
  6789. virtual int64 readInt64BigEndian();
  6790. /** Reads four bytes as a 32-bit floating point value.
  6791. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6792. If the stream is exhausted partway through reading the bytes, this will return zero.
  6793. @see OutputStream::writeFloat, readDouble
  6794. */
  6795. virtual float readFloat();
  6796. /** Reads four bytes as a 32-bit floating point value.
  6797. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6798. If the stream is exhausted partway through reading the bytes, this will return zero.
  6799. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6800. */
  6801. virtual float readFloatBigEndian();
  6802. /** Reads eight bytes as a 64-bit floating point value.
  6803. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6804. If the stream is exhausted partway through reading the bytes, this will return zero.
  6805. @see OutputStream::writeDouble, readFloat
  6806. */
  6807. virtual double readDouble();
  6808. /** Reads eight bytes as a 64-bit floating point value.
  6809. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6810. If the stream is exhausted partway through reading the bytes, this will return zero.
  6811. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6812. */
  6813. virtual double readDoubleBigEndian();
  6814. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6815. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6816. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6817. @see OutputStream::writeCompressedInt()
  6818. */
  6819. virtual int readCompressedInt();
  6820. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6821. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6822. After this call, the stream's position will be left pointing to the next character
  6823. following the line-feed, but the linefeeds aren't included in the string that
  6824. is returned.
  6825. */
  6826. virtual const String readNextLine();
  6827. /** Reads a zero-terminated UTF8 string from the stream.
  6828. This will read characters from the stream until it hits a zero character or
  6829. end-of-stream.
  6830. @see OutputStream::writeString, readEntireStreamAsString
  6831. */
  6832. virtual const String readString();
  6833. /** Tries to read the whole stream and turn it into a string.
  6834. This will read from the stream's current position until the end-of-stream, and
  6835. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6836. */
  6837. virtual const String readEntireStreamAsString();
  6838. /** Reads from the stream and appends the data to a MemoryBlock.
  6839. @param destBlock the block to append the data onto
  6840. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6841. of bytes that will be read - if it's negative, data
  6842. will be read until the stream is exhausted.
  6843. @returns the number of bytes that were added to the memory block
  6844. */
  6845. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6846. int maxNumBytesToRead = -1);
  6847. /** Returns the offset of the next byte that will be read from the stream.
  6848. @see setPosition
  6849. */
  6850. virtual int64 getPosition() = 0;
  6851. /** Tries to move the current read position of the stream.
  6852. The position is an absolute number of bytes from the stream's start.
  6853. Some streams might not be able to do this, in which case they should do
  6854. nothing and return false. Others might be able to manage it by resetting
  6855. themselves and skipping to the correct position, although this is
  6856. obviously a bit slow.
  6857. @returns true if the stream manages to reposition itself correctly
  6858. @see getPosition
  6859. */
  6860. virtual bool setPosition (int64 newPosition) = 0;
  6861. /** Reads and discards a number of bytes from the stream.
  6862. Some input streams might implement this efficiently, but the base
  6863. class will just keep reading data until the requisite number of bytes
  6864. have been done.
  6865. */
  6866. virtual void skipNextBytes (int64 numBytesToSkip);
  6867. juce_UseDebuggingNewOperator
  6868. protected:
  6869. InputStream() throw() {}
  6870. };
  6871. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6872. /********* End of inlined file: juce_InputStream.h *********/
  6873. /**
  6874. The base class for streams that write data to some kind of destination.
  6875. Input and output streams are used throughout the library - subclasses can override
  6876. some or all of the virtual functions to implement their behaviour.
  6877. @see InputStream, MemoryOutputStream, FileOutputStream
  6878. */
  6879. class JUCE_API OutputStream
  6880. {
  6881. public:
  6882. /** Destructor.
  6883. Some subclasses might want to do things like call flush() during their
  6884. destructors.
  6885. */
  6886. virtual ~OutputStream();
  6887. /** If the stream is using a buffer, this will ensure it gets written
  6888. out to the destination. */
  6889. virtual void flush() = 0;
  6890. /** Tries to move the stream's output position.
  6891. Not all streams will be able to seek to a new position - this will return
  6892. false if it fails to work.
  6893. @see getPosition
  6894. */
  6895. virtual bool setPosition (int64 newPosition) = 0;
  6896. /** Returns the stream's current position.
  6897. @see setPosition
  6898. */
  6899. virtual int64 getPosition() = 0;
  6900. /** Writes a block of data to the stream.
  6901. When creating a subclass of OutputStream, this is the only write method
  6902. that needs to be overloaded - the base class has methods for writing other
  6903. types of data which use this to do the work.
  6904. @returns false if the write operation fails for some reason
  6905. */
  6906. virtual bool write (const void* dataToWrite,
  6907. int howManyBytes) = 0;
  6908. /** Writes a single byte to the stream.
  6909. @see InputStream::readByte
  6910. */
  6911. virtual void writeByte (char byte);
  6912. /** Writes a boolean to the stream.
  6913. This is encoded as a byte - either 1 or 0.
  6914. @see InputStream::readBool
  6915. */
  6916. virtual void writeBool (bool boolValue);
  6917. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6918. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6919. @see InputStream::readShort
  6920. */
  6921. virtual void writeShort (short value);
  6922. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6923. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6924. @see InputStream::readShortBigEndian
  6925. */
  6926. virtual void writeShortBigEndian (short value);
  6927. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6928. @see InputStream::readInt
  6929. */
  6930. virtual void writeInt (int value);
  6931. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6932. @see InputStream::readIntBigEndian
  6933. */
  6934. virtual void writeIntBigEndian (int value);
  6935. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6936. @see InputStream::readInt64
  6937. */
  6938. virtual void writeInt64 (int64 value);
  6939. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6940. @see InputStream::readInt64BigEndian
  6941. */
  6942. virtual void writeInt64BigEndian (int64 value);
  6943. /** Writes a 32-bit floating point value to the stream.
  6944. The binary 32-bit encoding of the float is written as a little-endian int.
  6945. @see InputStream::readFloat
  6946. */
  6947. virtual void writeFloat (float value);
  6948. /** Writes a 32-bit floating point value to the stream.
  6949. The binary 32-bit encoding of the float is written as a big-endian int.
  6950. @see InputStream::readFloatBigEndian
  6951. */
  6952. virtual void writeFloatBigEndian (float value);
  6953. /** Writes a 64-bit floating point value to the stream.
  6954. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6955. @see InputStream::readDouble
  6956. */
  6957. virtual void writeDouble (double value);
  6958. /** Writes a 64-bit floating point value to the stream.
  6959. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6960. @see InputStream::readDoubleBigEndian
  6961. */
  6962. virtual void writeDoubleBigEndian (double value);
  6963. /** Writes a condensed encoding of a 32-bit integer.
  6964. If you're storing a lot of integers which are unlikely to have very large values,
  6965. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6966. under 0xffff only 3 bytes, etc.
  6967. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6968. @see InputStream::readCompressedInt
  6969. */
  6970. virtual void writeCompressedInt (int value);
  6971. /** Stores a string in the stream.
  6972. This isn't the method to use if you're trying to append text to the end of a
  6973. text-file! It's intended for storing a string for later retrieval
  6974. by InputStream::readString.
  6975. It writes the string to the stream as UTF8, with a null character terminating it.
  6976. For appending text to a file, instead use writeText, printf, or operator<<
  6977. @see InputStream::readString, writeText, printf, operator<<
  6978. */
  6979. virtual void writeString (const String& text);
  6980. /** Writes a string of text to the stream.
  6981. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6982. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6983. should only be done at the start of a file).
  6984. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6985. */
  6986. virtual void writeText (const String& text,
  6987. const bool asUnicode,
  6988. const bool writeUnicodeHeaderBytes);
  6989. /** Writes a string of text to the stream.
  6990. @see writeText
  6991. */
  6992. virtual void printf (const char* format, ...);
  6993. /** Reads data from an input stream and writes it to this stream.
  6994. @param source the stream to read from
  6995. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6996. less than zero, it will keep reading until the input
  6997. is exhausted)
  6998. */
  6999. virtual int writeFromInputStream (InputStream& source,
  7000. int maxNumBytesToWrite);
  7001. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  7002. virtual OutputStream& operator<< (const int number);
  7003. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  7004. virtual OutputStream& operator<< (const double number);
  7005. /** Writes a character to the stream. */
  7006. virtual OutputStream& operator<< (const char character);
  7007. /** Writes a null-terminated string to the stream. */
  7008. virtual OutputStream& operator<< (const char* const text);
  7009. /** Writes a null-terminated unicode text string to the stream, converting it
  7010. to 8-bit characters in the default system encoding. */
  7011. virtual OutputStream& operator<< (const juce_wchar* const text);
  7012. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  7013. virtual OutputStream& operator<< (const String& text);
  7014. juce_UseDebuggingNewOperator
  7015. protected:
  7016. OutputStream() throw();
  7017. };
  7018. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  7019. /********* End of inlined file: juce_OutputStream.h *********/
  7020. class JUCE_API DynamicObject;
  7021. /**
  7022. A variant class, that can be used to hold a range of primitive values.
  7023. A var object can hold a range of simple primitive values, strings, or
  7024. a reference-counted pointer to a DynamicObject. The var class is intended
  7025. to act like the values used in dynamic scripting languages.
  7026. @see DynamicObject
  7027. */
  7028. class JUCE_API var
  7029. {
  7030. public:
  7031. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  7032. /** Creates a void variant. */
  7033. var() throw();
  7034. /** Destructor. */
  7035. ~var();
  7036. var (const var& valueToCopy) throw();
  7037. var (const int value) throw();
  7038. var (const bool value) throw();
  7039. var (const double value) throw();
  7040. var (const char* const value) throw();
  7041. var (const juce_wchar* const value) throw();
  7042. var (const String& value) throw();
  7043. var (DynamicObject* const object) throw();
  7044. var (MethodFunction method) throw();
  7045. const var& operator= (const var& valueToCopy) throw();
  7046. const var& operator= (const int value) throw();
  7047. const var& operator= (const bool value) throw();
  7048. const var& operator= (const double value) throw();
  7049. const var& operator= (const char* const value) throw();
  7050. const var& operator= (const juce_wchar* const value) throw();
  7051. const var& operator= (const String& value) throw();
  7052. const var& operator= (DynamicObject* const object) throw();
  7053. const var& operator= (MethodFunction method) throw();
  7054. operator int() const throw();
  7055. operator bool() const throw();
  7056. operator float() const throw();
  7057. operator double() const throw();
  7058. operator const String() const throw();
  7059. const String toString() const throw();
  7060. DynamicObject* getObject() const throw();
  7061. bool isVoid() const throw() { return type == voidType; }
  7062. bool isInt() const throw() { return type == intType; }
  7063. bool isBool() const throw() { return type == boolType; }
  7064. bool isDouble() const throw() { return type == doubleType; }
  7065. bool isString() const throw() { return type == stringType; }
  7066. bool isObject() const throw() { return type == objectType; }
  7067. bool isMethod() const throw() { return type == methodType; }
  7068. bool operator== (const var& other) const throw();
  7069. bool operator!= (const var& other) const throw();
  7070. /** Writes a binary representation of this value to a stream.
  7071. The data can be read back later using readFromStream().
  7072. */
  7073. void writeToStream (OutputStream& output) const throw();
  7074. /** Reads back a stored binary representation of a value.
  7075. The data in the stream must have been written using writeToStream(), or this
  7076. will have unpredictable results.
  7077. */
  7078. static const var readFromStream (InputStream& input) throw();
  7079. class JUCE_API identifier
  7080. {
  7081. public:
  7082. identifier (const char* const name) throw();
  7083. identifier (const String& name) throw();
  7084. ~identifier() throw();
  7085. bool operator== (const identifier& other) const throw()
  7086. {
  7087. jassert (hashCode != other.hashCode || name == other.name); // check for name hash collisions
  7088. return hashCode == other.hashCode;
  7089. }
  7090. String name;
  7091. int hashCode;
  7092. };
  7093. /** If this variant is an object, this returns one of its properties. */
  7094. const var operator[] (const identifier& propertyName) const throw();
  7095. /** If this variant is an object, this invokes one of its methods with no arguments. */
  7096. const var call (const identifier& method) const;
  7097. /** If this variant is an object, this invokes one of its methods with one argument. */
  7098. const var call (const identifier& method, const var& arg1) const;
  7099. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  7100. const var call (const identifier& method, const var& arg1, const var& arg2) const;
  7101. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  7102. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3);
  7103. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  7104. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  7105. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  7106. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  7107. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  7108. const var invoke (const identifier& method, const var* arguments, int numArguments) const;
  7109. /** If this variant is a method pointer, this invokes it on a target object. */
  7110. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  7111. juce_UseDebuggingNewOperator
  7112. private:
  7113. enum Type
  7114. {
  7115. voidType = 0,
  7116. intType,
  7117. boolType,
  7118. doubleType,
  7119. stringType,
  7120. objectType,
  7121. methodType
  7122. };
  7123. Type type;
  7124. union
  7125. {
  7126. int intValue;
  7127. bool boolValue;
  7128. double doubleValue;
  7129. String* stringValue;
  7130. DynamicObject* objectValue;
  7131. MethodFunction methodValue;
  7132. } value;
  7133. void releaseValue() throw();
  7134. };
  7135. /**
  7136. Represents a dynamically implemented object.
  7137. An instance of this class can be used to store named properties, and
  7138. by subclassing hasMethod() and invokeMethod(), you can give your object
  7139. methods.
  7140. This is intended for use as a wrapper for scripting language objects.
  7141. */
  7142. class JUCE_API DynamicObject : public ReferenceCountedObject
  7143. {
  7144. public:
  7145. DynamicObject();
  7146. /** Destructor. */
  7147. virtual ~DynamicObject();
  7148. /** Returns true if the object has a property with this name.
  7149. Note that if the property is actually a method, this will return false.
  7150. */
  7151. virtual bool hasProperty (const var::identifier& propertyName) const;
  7152. /** Returns a named property.
  7153. This returns a void if no such property exists.
  7154. */
  7155. virtual const var getProperty (const var::identifier& propertyName) const;
  7156. /** Sets a named property. */
  7157. virtual void setProperty (const var::identifier& propertyName, const var& newValue);
  7158. /** Removes a named property. */
  7159. virtual void removeProperty (const var::identifier& propertyName);
  7160. /** Checks whether this object has the specified method.
  7161. The default implementation of this just checks whether there's a property
  7162. with this name that's actually a method, but this can be overridden for
  7163. building objects with dynamic invocation.
  7164. */
  7165. virtual bool hasMethod (const var::identifier& methodName) const;
  7166. /** Invokes a named method on this object.
  7167. The default implementation looks up the named property, and if it's a method
  7168. call, then it invokes it.
  7169. This method is virtual to allow more dynamic invocation to used for objects
  7170. where the methods may not already be set as properies.
  7171. */
  7172. virtual const var invokeMethod (const var::identifier& methodName,
  7173. const var* parameters,
  7174. int numParameters);
  7175. /** Sets up a method.
  7176. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7177. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7178. the code easier to read,
  7179. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7180. @code
  7181. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7182. @endcode
  7183. */
  7184. void setMethod (const var::identifier& methodName,
  7185. var::MethodFunction methodFunction);
  7186. /** Removes all properties and methods from the object. */
  7187. void clear();
  7188. juce_UseDebuggingNewOperator
  7189. private:
  7190. Array <int> propertyIds;
  7191. OwnedArray <var> propertyValues;
  7192. };
  7193. #endif // __JUCE_VARIANT_JUCEHEADER__
  7194. /********* End of inlined file: juce_Variant.h *********/
  7195. #endif
  7196. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  7197. #endif
  7198. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7199. #endif
  7200. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  7201. #endif
  7202. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7203. #endif
  7204. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  7205. /********* Start of inlined file: juce_PropertySet.h *********/
  7206. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  7207. #define __JUCE_PROPERTYSET_JUCEHEADER__
  7208. /********* Start of inlined file: juce_StringPairArray.h *********/
  7209. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7210. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7211. /**
  7212. A container for holding a set of strings which are keyed by another string.
  7213. @see StringArray
  7214. */
  7215. class JUCE_API StringPairArray
  7216. {
  7217. public:
  7218. /** Creates an empty array */
  7219. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  7220. /** Creates a copy of another array */
  7221. StringPairArray (const StringPairArray& other) throw();
  7222. /** Destructor. */
  7223. ~StringPairArray() throw();
  7224. /** Copies the contents of another string array into this one */
  7225. const StringPairArray& operator= (const StringPairArray& other) throw();
  7226. /** Compares two arrays.
  7227. Comparisons are case-sensitive.
  7228. @returns true only if the other array contains exactly the same strings with the same keys
  7229. */
  7230. bool operator== (const StringPairArray& other) const throw();
  7231. /** Compares two arrays.
  7232. Comparisons are case-sensitive.
  7233. @returns false if the other array contains exactly the same strings with the same keys
  7234. */
  7235. bool operator!= (const StringPairArray& other) const throw();
  7236. /** Finds the value corresponding to a key string.
  7237. If no such key is found, this will just return an empty string. To check whether
  7238. a given key actually exists (because it might actually be paired with an empty string), use
  7239. the getAllKeys() method to obtain a list.
  7240. Obviously the reference returned shouldn't be stored for later use, as the
  7241. string it refers to may disappear when the array changes.
  7242. @see getValue
  7243. */
  7244. const String& operator[] (const String& key) const throw();
  7245. /** Finds the value corresponding to a key string.
  7246. If no such key is found, this will just return the value provided as a default.
  7247. @see operator[]
  7248. */
  7249. const String getValue (const String& key, const String& defaultReturnValue) const;
  7250. /** Returns a list of all keys in the array. */
  7251. const StringArray& getAllKeys() const throw() { return keys; }
  7252. /** Returns a list of all values in the array. */
  7253. const StringArray& getAllValues() const throw() { return values; }
  7254. /** Returns the number of strings in the array */
  7255. inline int size() const throw() { return keys.size(); };
  7256. /** Adds or amends a key/value pair.
  7257. If a value already exists with this key, its value will be overwritten,
  7258. otherwise the key/value pair will be added to the array.
  7259. */
  7260. void set (const String& key,
  7261. const String& value) throw();
  7262. /** Adds the items from another array to this one.
  7263. This is equivalent to using set() to add each of the pairs from the other array.
  7264. */
  7265. void addArray (const StringPairArray& other);
  7266. /** Removes all elements from the array. */
  7267. void clear() throw();
  7268. /** Removes a string from the array based on its key.
  7269. If the key isn't found, nothing will happen.
  7270. */
  7271. void remove (const String& key) throw();
  7272. /** Removes a string from the array based on its index.
  7273. If the index is out-of-range, no action will be taken.
  7274. */
  7275. void remove (const int index) throw();
  7276. /** Indicates whether to use a case-insensitive search when looking up a key string.
  7277. */
  7278. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  7279. /** Returns a descriptive string containing the items.
  7280. This is handy for dumping the contents of an array.
  7281. */
  7282. const String getDescription() const;
  7283. /** Reduces the amount of storage being used by the array.
  7284. Arrays typically allocate slightly more storage than they need, and after
  7285. removing elements, they may have quite a lot of unused space allocated.
  7286. This method will reduce the amount of allocated storage to a minimum.
  7287. */
  7288. void minimiseStorageOverheads() throw();
  7289. juce_UseDebuggingNewOperator
  7290. private:
  7291. StringArray keys, values;
  7292. bool ignoreCase;
  7293. };
  7294. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7295. /********* End of inlined file: juce_StringPairArray.h *********/
  7296. /********* Start of inlined file: juce_XmlElement.h *********/
  7297. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  7298. #define __JUCE_XMLELEMENT_JUCEHEADER__
  7299. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  7300. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7301. will be the name of a pointer to each child element.
  7302. E.g. @code
  7303. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7304. forEachXmlChildElement (*myParentXml, child)
  7305. {
  7306. if (child->hasTagName ("FOO"))
  7307. doSomethingWithXmlElement (child);
  7308. }
  7309. @endcode
  7310. @see forEachXmlChildElementWithTagName
  7311. */
  7312. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  7313. \
  7314. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  7315. childElementVariableName != 0; \
  7316. childElementVariableName = childElementVariableName->getNextElement())
  7317. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  7318. which have a specified tag.
  7319. This does the same job as the forEachXmlChildElement macro, but only for those
  7320. elements that have a particular tag name.
  7321. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7322. will be the name of a pointer to each child element. The requiredTagName is the
  7323. tag name to match.
  7324. E.g. @code
  7325. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7326. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  7327. {
  7328. // the child object is now guaranteed to be a <MYTAG> element..
  7329. doSomethingWithMYTAGElement (child);
  7330. }
  7331. @endcode
  7332. @see forEachXmlChildElement
  7333. */
  7334. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7335. \
  7336. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7337. childElementVariableName != 0; \
  7338. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7339. /** Used to build a tree of elements representing an XML document.
  7340. An XML document can be parsed into a tree of XmlElements, each of which
  7341. represents an XML tag structure, and which may itself contain other
  7342. nested elements.
  7343. An XmlElement can also be converted back into a text document, and has
  7344. lots of useful methods for manipulating its attributes and sub-elements,
  7345. so XmlElements can actually be used as a handy general-purpose data
  7346. structure.
  7347. Here's an example of parsing some elements: @code
  7348. // check we're looking at the right kind of document..
  7349. if (myElement->hasTagName ("ANIMALS"))
  7350. {
  7351. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7352. forEachXmlChildElement (*myElement, e)
  7353. {
  7354. if (e->hasTagName ("GIRAFFE"))
  7355. {
  7356. // found a giraffe, so use some of its attributes..
  7357. String giraffeName = e->getStringAttribute ("name");
  7358. int giraffeAge = e->getIntAttribute ("age");
  7359. bool isFriendly = e->getBoolAttribute ("friendly");
  7360. }
  7361. }
  7362. }
  7363. @endcode
  7364. And here's an example of how to create an XML document from scratch: @code
  7365. // create an outer node called "ANIMALS"
  7366. XmlElement animalsList ("ANIMALS");
  7367. for (int i = 0; i < numAnimals; ++i)
  7368. {
  7369. // create an inner element..
  7370. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7371. giraffe->setAttribute ("name", "nigel");
  7372. giraffe->setAttribute ("age", 10);
  7373. giraffe->setAttribute ("friendly", true);
  7374. // ..and add our new element to the parent node
  7375. animalsList.addChildElement (giraffe);
  7376. }
  7377. // now we can turn the whole thing into a text document..
  7378. String myXmlDoc = animalsList.createDocument (String::empty);
  7379. @endcode
  7380. @see XmlDocument
  7381. */
  7382. class JUCE_API XmlElement
  7383. {
  7384. public:
  7385. /** Creates an XmlElement with this tag name. */
  7386. XmlElement (const String& tagName) throw();
  7387. /** Creates a (deep) copy of another element. */
  7388. XmlElement (const XmlElement& other) throw();
  7389. /** Creates a (deep) copy of another element. */
  7390. const XmlElement& operator= (const XmlElement& other) throw();
  7391. /** Deleting an XmlElement will also delete all its child elements. */
  7392. ~XmlElement() throw();
  7393. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7394. The elements are only considered equivalent if they contain the same attiributes
  7395. with the same values, and have the same sub-nodes.
  7396. @param other the other element to compare to
  7397. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7398. same attributes in a different order will be
  7399. considered the same; if false, the attributes must
  7400. be in the same order as well
  7401. */
  7402. bool isEquivalentTo (const XmlElement* const other,
  7403. const bool ignoreOrderOfAttributes) const throw();
  7404. /** Returns an XML text document that represents this element.
  7405. The string returned can be parsed to recreate the same XmlElement that
  7406. was used to create it.
  7407. @param dtdToUse the DTD to add to the document
  7408. @param allOnOneLine if true, this means that the document will not contain any
  7409. linefeeds, so it'll be smaller but not very easy to read.
  7410. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7411. document
  7412. @param encodingType the character encoding format string to put into the xml
  7413. header
  7414. @param lineWrapLength the line length that will be used before items get placed on
  7415. a new line. This isn't an absolute maximum length, it just
  7416. determines how lists of attributes get broken up
  7417. @see writeToStream, writeToFile
  7418. */
  7419. const String createDocument (const String& dtdToUse,
  7420. const bool allOnOneLine = false,
  7421. const bool includeXmlHeader = true,
  7422. const tchar* const encodingType = JUCE_T("UTF-8"),
  7423. const int lineWrapLength = 60) const throw();
  7424. /** Writes the document to a stream as UTF-8.
  7425. @param output the stream to write to
  7426. @param dtdToUse the DTD to add to the document
  7427. @param allOnOneLine if true, this means that the document will not contain any
  7428. linefeeds, so it'll be smaller but not very easy to read.
  7429. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7430. document
  7431. @param encodingType the character encoding format string to put into the xml
  7432. header
  7433. @param lineWrapLength the line length that will be used before items get placed on
  7434. a new line. This isn't an absolute maximum length, it just
  7435. determines how lists of attributes get broken up
  7436. @see writeToFile, createDocument
  7437. */
  7438. void writeToStream (OutputStream& output,
  7439. const String& dtdToUse,
  7440. const bool allOnOneLine = false,
  7441. const bool includeXmlHeader = true,
  7442. const tchar* const encodingType = JUCE_T("UTF-8"),
  7443. const int lineWrapLength = 60) const throw();
  7444. /** Writes the element to a file as an XML document.
  7445. To improve safety in case something goes wrong while writing the file, this
  7446. will actually write the document to a new temporary file in the same
  7447. directory as the destination file, and if this succeeds, it will rename this
  7448. new file as the destination file (overwriting any existing file that was there).
  7449. @param destinationFile the file to write to. If this already exists, it will be
  7450. overwritten.
  7451. @param dtdToUse the DTD to add to the document
  7452. @param encodingType the character encoding format string to put into the xml
  7453. header
  7454. @param lineWrapLength the line length that will be used before items get placed on
  7455. a new line. This isn't an absolute maximum length, it just
  7456. determines how lists of attributes get broken up
  7457. @returns true if the file is written successfully; false if something goes wrong
  7458. in the process
  7459. @see createDocument
  7460. */
  7461. bool writeToFile (const File& destinationFile,
  7462. const String& dtdToUse,
  7463. const tchar* const encodingType = JUCE_T("UTF-8"),
  7464. const int lineWrapLength = 60) const throw();
  7465. /** Returns this element's tag type name.
  7466. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7467. "MOOSE".
  7468. @see hasTagName
  7469. */
  7470. inline const String& getTagName() const throw() { return tagName; }
  7471. /** Tests whether this element has a particular tag name.
  7472. @param possibleTagName the tag name you're comparing it with
  7473. @see getTagName
  7474. */
  7475. bool hasTagName (const tchar* const possibleTagName) const throw();
  7476. /** Returns the number of XML attributes this element contains.
  7477. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7478. return 2.
  7479. */
  7480. int getNumAttributes() const throw();
  7481. /** Returns the name of one of the elements attributes.
  7482. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7483. getAttributeName(1) would return "antlers".
  7484. @see getAttributeValue, getStringAttribute
  7485. */
  7486. const String& getAttributeName (const int attributeIndex) const throw();
  7487. /** Returns the value of one of the elements attributes.
  7488. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7489. getAttributeName(1) would return "2".
  7490. @see getAttributeName, getStringAttribute
  7491. */
  7492. const String& getAttributeValue (const int attributeIndex) const throw();
  7493. // Attribute-handling methods..
  7494. /** Checks whether the element contains an attribute with a certain name. */
  7495. bool hasAttribute (const tchar* const attributeName) const throw();
  7496. /** Returns the value of a named attribute.
  7497. @param attributeName the name of the attribute to look up
  7498. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7499. with this name
  7500. */
  7501. const String getStringAttribute (const tchar* const attributeName,
  7502. const tchar* const defaultReturnValue = 0) const throw();
  7503. /** Compares the value of a named attribute with a value passed-in.
  7504. @param attributeName the name of the attribute to look up
  7505. @param stringToCompareAgainst the value to compare it with
  7506. @param ignoreCase whether the comparison should be case-insensitive
  7507. @returns true if the value of the attribute is the same as the string passed-in;
  7508. false if it's different (or if no such attribute exists)
  7509. */
  7510. bool compareAttribute (const tchar* const attributeName,
  7511. const tchar* const stringToCompareAgainst,
  7512. const bool ignoreCase = false) const throw();
  7513. /** Returns the value of a named attribute as an integer.
  7514. This will try to find the attribute and convert it to an integer (using
  7515. the String::getIntValue() method).
  7516. @param attributeName the name of the attribute to look up
  7517. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7518. with this name
  7519. @see setAttribute (const tchar* const, int)
  7520. */
  7521. int getIntAttribute (const tchar* const attributeName,
  7522. const int defaultReturnValue = 0) const throw();
  7523. /** Returns the value of a named attribute as floating-point.
  7524. This will try to find the attribute and convert it to an integer (using
  7525. the String::getDoubleValue() method).
  7526. @param attributeName the name of the attribute to look up
  7527. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7528. with this name
  7529. @see setAttribute (const tchar* const, double)
  7530. */
  7531. double getDoubleAttribute (const tchar* const attributeName,
  7532. const double defaultReturnValue = 0.0) const throw();
  7533. /** Returns the value of a named attribute as a boolean.
  7534. This will try to find the attribute and interpret it as a boolean. To do this,
  7535. it'll return true if the value is "1", "true", "y", etc, or false for other
  7536. values.
  7537. @param attributeName the name of the attribute to look up
  7538. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7539. with this name
  7540. */
  7541. bool getBoolAttribute (const tchar* const attributeName,
  7542. const bool defaultReturnValue = false) const throw();
  7543. /** Adds a named attribute to the element.
  7544. If the element already contains an attribute with this name, it's value will
  7545. be updated to the new value. If there's no such attribute yet, a new one will
  7546. be added.
  7547. Note that there are other setAttribute() methods that take integers,
  7548. doubles, etc. to make it easy to store numbers.
  7549. @param attributeName the name of the attribute to set
  7550. @param newValue the value to set it to
  7551. @see removeAttribute
  7552. */
  7553. void setAttribute (const tchar* const attributeName,
  7554. const String& newValue) throw();
  7555. /** Adds a named attribute to the element.
  7556. If the element already contains an attribute with this name, it's value will
  7557. be updated to the new value. If there's no such attribute yet, a new one will
  7558. be added.
  7559. Note that there are other setAttribute() methods that take integers,
  7560. doubles, etc. to make it easy to store numbers.
  7561. @param attributeName the name of the attribute to set
  7562. @param newValue the value to set it to
  7563. */
  7564. void setAttribute (const tchar* const attributeName,
  7565. const tchar* const newValue) throw();
  7566. /** Adds a named attribute to the element, setting it to an integer value.
  7567. If the element already contains an attribute with this name, it's value will
  7568. be updated to the new value. If there's no such attribute yet, a new one will
  7569. be added.
  7570. Note that there are other setAttribute() methods that take integers,
  7571. doubles, etc. to make it easy to store numbers.
  7572. @param attributeName the name of the attribute to set
  7573. @param newValue the value to set it to
  7574. */
  7575. void setAttribute (const tchar* const attributeName,
  7576. const int newValue) throw();
  7577. /** Adds a named attribute to the element, setting it to a floating-point value.
  7578. If the element already contains an attribute with this name, it's value will
  7579. be updated to the new value. If there's no such attribute yet, a new one will
  7580. be added.
  7581. Note that there are other setAttribute() methods that take integers,
  7582. doubles, etc. to make it easy to store numbers.
  7583. @param attributeName the name of the attribute to set
  7584. @param newValue the value to set it to
  7585. */
  7586. void setAttribute (const tchar* const attributeName,
  7587. const double newValue) throw();
  7588. /** Removes a named attribute from the element.
  7589. @param attributeName the name of the attribute to remove
  7590. @see removeAllAttributes
  7591. */
  7592. void removeAttribute (const tchar* const attributeName) throw();
  7593. /** Removes all attributes from this element.
  7594. */
  7595. void removeAllAttributes() throw();
  7596. // Child element methods..
  7597. /** Returns the first of this element's sub-elements.
  7598. see getNextElement() for an example of how to iterate the sub-elements.
  7599. @see forEachXmlChildElement
  7600. */
  7601. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7602. /** Returns the next of this element's siblings.
  7603. This can be used for iterating an element's sub-elements, e.g.
  7604. @code
  7605. XmlElement* child = myXmlDocument->getFirstChildElement();
  7606. while (child != 0)
  7607. {
  7608. ...do stuff with this child..
  7609. child = child->getNextElement();
  7610. }
  7611. @endcode
  7612. Note that when iterating the child elements, some of them might be
  7613. text elements as well as XML tags - use isTextElement() to work this
  7614. out.
  7615. Also, it's much easier and neater to use this method indirectly via the
  7616. forEachXmlChildElement macro.
  7617. @returns the sibling element that follows this one, or zero if this is the last
  7618. element in its parent
  7619. @see getNextElement, isTextElement, forEachXmlChildElement
  7620. */
  7621. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7622. /** Returns the next of this element's siblings which has the specified tag
  7623. name.
  7624. This is like getNextElement(), but will scan through the list until it
  7625. finds an element with the given tag name.
  7626. @see getNextElement, forEachXmlChildElementWithTagName
  7627. */
  7628. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  7629. /** Returns the number of sub-elements in this element.
  7630. @see getChildElement
  7631. */
  7632. int getNumChildElements() const throw();
  7633. /** Returns the sub-element at a certain index.
  7634. It's not very efficient to iterate the sub-elements by index - see
  7635. getNextElement() for an example of how best to iterate.
  7636. @returns the n'th child of this element, or 0 if the index is out-of-range
  7637. @see getNextElement, isTextElement, getChildByName
  7638. */
  7639. XmlElement* getChildElement (const int index) const throw();
  7640. /** Returns the first sub-element with a given tag-name.
  7641. @param tagNameToLookFor the tag name of the element you want to find
  7642. @returns the first element with this tag name, or 0 if none is found
  7643. @see getNextElement, isTextElement, getChildElement
  7644. */
  7645. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  7646. /** Appends an element to this element's list of children.
  7647. Child elements are deleted automatically when their parent is deleted, so
  7648. make sure the object that you pass in will not be deleted by anything else,
  7649. and make sure it's not already the child of another element.
  7650. @see getFirstChildElement, getNextElement, getNumChildElements,
  7651. getChildElement, removeChildElement
  7652. */
  7653. void addChildElement (XmlElement* const newChildElement) throw();
  7654. /** Inserts an element into this element's list of children.
  7655. Child elements are deleted automatically when their parent is deleted, so
  7656. make sure the object that you pass in will not be deleted by anything else,
  7657. and make sure it's not already the child of another element.
  7658. @param newChildNode the element to add
  7659. @param indexToInsertAt the index at which to insert the new element - if this is
  7660. below zero, it will be added to the end of the list
  7661. @see addChildElement, insertChildElement
  7662. */
  7663. void insertChildElement (XmlElement* const newChildNode,
  7664. int indexToInsertAt) throw();
  7665. /** Replaces one of this element's children with another node.
  7666. If the current element passed-in isn't actually a child of this element,
  7667. this will return false and the new one won't be added. Otherwise, the
  7668. existing element will be deleted, replaced with the new one, and it
  7669. will return true.
  7670. */
  7671. bool replaceChildElement (XmlElement* const currentChildElement,
  7672. XmlElement* const newChildNode) throw();
  7673. /** Removes a child element.
  7674. @param childToRemove the child to look for and remove
  7675. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7676. just remove it
  7677. */
  7678. void removeChildElement (XmlElement* const childToRemove,
  7679. const bool shouldDeleteTheChild) throw();
  7680. /** Deletes all the child elements in the element.
  7681. @see removeChildElement, deleteAllChildElementsWithTagName
  7682. */
  7683. void deleteAllChildElements() throw();
  7684. /** Deletes all the child elements with a given tag name.
  7685. @see removeChildElement
  7686. */
  7687. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  7688. /** Returns true if the given element is a child of this one. */
  7689. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7690. /** Recursively searches all sub-elements to find one that contains the specified
  7691. child element.
  7692. */
  7693. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  7694. /** Sorts the child elements using a comparator.
  7695. This will use a comparator object to sort the elements into order. The object
  7696. passed must have a method of the form:
  7697. @code
  7698. int compareElements (const XmlElement* first, const XmlElement* second);
  7699. @endcode
  7700. ..and this method must return:
  7701. - a value of < 0 if the first comes before the second
  7702. - a value of 0 if the two objects are equivalent
  7703. - a value of > 0 if the second comes before the first
  7704. To improve performance, the compareElements() method can be declared as static or const.
  7705. @param comparator the comparator to use for comparing elements.
  7706. @param retainOrderOfEquivalentItems if this is true, then items
  7707. which the comparator says are equivalent will be
  7708. kept in the order in which they currently appear
  7709. in the array. This is slower to perform, but may
  7710. be important in some cases. If it's false, a faster
  7711. algorithm is used, but equivalent elements may be
  7712. rearranged.
  7713. */
  7714. template <class ElementComparator>
  7715. void sortChildElements (ElementComparator& comparator,
  7716. const bool retainOrderOfEquivalentItems = false) throw()
  7717. {
  7718. const int num = getNumChildElements();
  7719. if (num > 1)
  7720. {
  7721. XmlElement** const elems = getChildElementsAsArray (num);
  7722. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  7723. reorderChildElements (elems, num);
  7724. delete[] elems;
  7725. }
  7726. }
  7727. /** Returns true if this element is a section of text.
  7728. Elements can either be an XML tag element or a secton of text, so this
  7729. is used to find out what kind of element this one is.
  7730. @see getAllText, addTextElement, deleteAllTextElements
  7731. */
  7732. bool isTextElement() const throw();
  7733. /** Returns the text for a text element.
  7734. Note that if you have an element like this:
  7735. @code<xyz>hello</xyz>@endcode
  7736. then calling getText on the "xyz" element won't return "hello", because that is
  7737. actually stored in a special text sub-element inside the xyz element. To get the
  7738. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7739. use getAllSubText() to do this automatically.
  7740. @see isTextElement, getAllSubText, getChildElementAllSubText
  7741. */
  7742. const String getText() const throw();
  7743. /** Sets the text in a text element.
  7744. Note that this is only a valid call if this element is a text element. If it's
  7745. not, then no action will be performed.
  7746. */
  7747. void setText (const String& newText) throw();
  7748. /** Returns all the text from this element's child nodes.
  7749. This iterates all the child elements and when it finds text elements,
  7750. it concatenates their text into a big string which it returns.
  7751. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7752. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7753. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7754. */
  7755. const String getAllSubText() const throw();
  7756. /** Returns all the sub-text of a named child element.
  7757. If there is a child element with the given tag name, this will return
  7758. all of its sub-text (by calling getAllSubText() on it). If there is
  7759. no such child element, this will return the default string passed-in.
  7760. @see getAllSubText
  7761. */
  7762. const String getChildElementAllSubText (const tchar* const childTagName,
  7763. const String& defaultReturnValue) const throw();
  7764. /** Appends a section of text to this element.
  7765. @see isTextElement, getText, getAllSubText
  7766. */
  7767. void addTextElement (const String& text) throw();
  7768. /** Removes all the text elements from this element.
  7769. @see isTextElement, getText, getAllSubText, addTextElement
  7770. */
  7771. void deleteAllTextElements() throw();
  7772. /** Creates a text element that can be added to a parent element.
  7773. */
  7774. static XmlElement* createTextElement (const String& text) throw();
  7775. juce_UseDebuggingNewOperator
  7776. private:
  7777. friend class XmlDocument;
  7778. String tagName;
  7779. XmlElement* firstChildElement;
  7780. XmlElement* nextElement;
  7781. struct XmlAttributeNode
  7782. {
  7783. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7784. XmlAttributeNode (const String& name, const String& value) throw();
  7785. String name, value;
  7786. XmlAttributeNode* next;
  7787. private:
  7788. const XmlAttributeNode& operator= (const XmlAttributeNode&);
  7789. };
  7790. XmlAttributeNode* attributes;
  7791. XmlElement (int) throw(); // for internal use
  7792. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  7793. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  7794. void writeElementAsText (OutputStream& out,
  7795. const int indentationLevel,
  7796. const int lineWrapLength) const throw();
  7797. XmlElement** getChildElementsAsArray (const int) const throw();
  7798. void reorderChildElements (XmlElement** const, const int) throw();
  7799. };
  7800. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7801. /********* End of inlined file: juce_XmlElement.h *********/
  7802. /**
  7803. A set of named property values, which can be strings, integers, floating point, etc.
  7804. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7805. to load and save types other than strings.
  7806. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7807. messages and saves/loads the list from a file.
  7808. */
  7809. class JUCE_API PropertySet
  7810. {
  7811. public:
  7812. /** Creates an empty PropertySet.
  7813. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7814. case-insensitive way
  7815. */
  7816. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7817. /** Creates a copy of another PropertySet.
  7818. */
  7819. PropertySet (const PropertySet& other) throw();
  7820. /** Copies another PropertySet over this one.
  7821. */
  7822. const PropertySet& operator= (const PropertySet& other) throw();
  7823. /** Destructor. */
  7824. virtual ~PropertySet();
  7825. /** Returns one of the properties as a string.
  7826. If the value isn't found in this set, then this will look for it in a fallback
  7827. property set (if you've specified one with the setFallbackPropertySet() method),
  7828. and if it can't find one there, it'll return the default value passed-in.
  7829. @param keyName the name of the property to retrieve
  7830. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7831. */
  7832. const String getValue (const String& keyName,
  7833. const String& defaultReturnValue = String::empty) const throw();
  7834. /** Returns one of the properties as an integer.
  7835. If the value isn't found in this set, then this will look for it in a fallback
  7836. property set (if you've specified one with the setFallbackPropertySet() method),
  7837. and if it can't find one there, it'll return the default value passed-in.
  7838. @param keyName the name of the property to retrieve
  7839. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7840. */
  7841. int getIntValue (const String& keyName,
  7842. const int defaultReturnValue = 0) const throw();
  7843. /** Returns one of the properties as an double.
  7844. If the value isn't found in this set, then this will look for it in a fallback
  7845. property set (if you've specified one with the setFallbackPropertySet() method),
  7846. and if it can't find one there, it'll return the default value passed-in.
  7847. @param keyName the name of the property to retrieve
  7848. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7849. */
  7850. double getDoubleValue (const String& keyName,
  7851. const double defaultReturnValue = 0.0) const throw();
  7852. /** Returns one of the properties as an boolean.
  7853. The result will be true if the string found for this key name can be parsed as a non-zero
  7854. integer.
  7855. If the value isn't found in this set, then this will look for it in a fallback
  7856. property set (if you've specified one with the setFallbackPropertySet() method),
  7857. and if it can't find one there, it'll return the default value passed-in.
  7858. @param keyName the name of the property to retrieve
  7859. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7860. */
  7861. bool getBoolValue (const String& keyName,
  7862. const bool defaultReturnValue = false) const throw();
  7863. /** Returns one of the properties as an XML element.
  7864. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7865. key isn't found, or if the entry contains an string that isn't valid XML.
  7866. If the value isn't found in this set, then this will look for it in a fallback
  7867. property set (if you've specified one with the setFallbackPropertySet() method),
  7868. and if it can't find one there, it'll return the default value passed-in.
  7869. @param keyName the name of the property to retrieve
  7870. */
  7871. XmlElement* getXmlValue (const String& keyName) const;
  7872. /** Sets a named property as a string.
  7873. @param keyName the name of the property to set. (This mustn't be an empty string)
  7874. @param value the new value to set it to
  7875. */
  7876. void setValue (const String& keyName, const String& value) throw();
  7877. /** Sets a named property as a string.
  7878. @param keyName the name of the property to set. (This mustn't be an empty string)
  7879. @param value the new value to set it to
  7880. */
  7881. void setValue (const String& keyName, const tchar* const value) throw();
  7882. /** Sets a named property to an integer.
  7883. @param keyName the name of the property to set. (This mustn't be an empty string)
  7884. @param value the new value to set it to
  7885. */
  7886. void setValue (const String& keyName, const int value) throw();
  7887. /** Sets a named property to a double.
  7888. @param keyName the name of the property to set. (This mustn't be an empty string)
  7889. @param value the new value to set it to
  7890. */
  7891. void setValue (const String& keyName, const double value) throw();
  7892. /** Sets a named property to a boolean.
  7893. @param keyName the name of the property to set. (This mustn't be an empty string)
  7894. @param value the new value to set it to
  7895. */
  7896. void setValue (const String& keyName, const bool value) throw();
  7897. /** Sets a named property to an XML element.
  7898. @param keyName the name of the property to set. (This mustn't be an empty string)
  7899. @param xml the new element to set it to. If this is zero, the value will be set to
  7900. an empty string
  7901. @see getXmlValue
  7902. */
  7903. void setValue (const String& keyName, const XmlElement* const xml);
  7904. /** Deletes a property.
  7905. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7906. */
  7907. void removeValue (const String& keyName) throw();
  7908. /** Returns true if the properies include the given key. */
  7909. bool containsKey (const String& keyName) const throw();
  7910. /** Removes all values. */
  7911. void clear();
  7912. /** Returns the keys/value pair array containing all the properties. */
  7913. StringPairArray& getAllProperties() throw() { return properties; }
  7914. /** Returns the lock used when reading or writing to this set */
  7915. const CriticalSection& getLock() const throw() { return lock; }
  7916. /** Returns an XML element which encapsulates all the items in this property set.
  7917. The string parameter is the tag name that should be used for the node.
  7918. @see restoreFromXml
  7919. */
  7920. XmlElement* createXml (const String& nodeName) const throw();
  7921. /** Reloads a set of properties that were previously stored as XML.
  7922. The node passed in must have been created by the createXml() method.
  7923. @see createXml
  7924. */
  7925. void restoreFromXml (const XmlElement& xml) throw();
  7926. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7927. set in this one.
  7928. If you set this up to be a pointer to a second property set, then whenever one
  7929. of the getValue() methods fails to find an entry in this set, it will look up that
  7930. value in the fallback set, and if it finds it, it will return that.
  7931. Make sure that you don't delete the fallback set while it's still being used by
  7932. another set! To remove the fallback set, just call this method with a null pointer.
  7933. @see getFallbackPropertySet
  7934. */
  7935. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7936. /** Returns the fallback property set.
  7937. @see setFallbackPropertySet
  7938. */
  7939. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7940. juce_UseDebuggingNewOperator
  7941. protected:
  7942. /** Subclasses can override this to be told when one of the properies has been changed.
  7943. */
  7944. virtual void propertyChanged();
  7945. private:
  7946. StringPairArray properties;
  7947. PropertySet* fallbackProperties;
  7948. CriticalSection lock;
  7949. bool ignoreCaseOfKeys;
  7950. };
  7951. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7952. /********* End of inlined file: juce_PropertySet.h *********/
  7953. #endif
  7954. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7955. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7956. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7957. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7958. /**
  7959. Holds a list of objects derived from ReferenceCountedObject.
  7960. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7961. and takes care of incrementing and decrementing their ref counts when they
  7962. are added and removed from the array.
  7963. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7964. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7965. @see Array, OwnedArray, StringArray
  7966. */
  7967. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7968. class ReferenceCountedArray
  7969. {
  7970. public:
  7971. /** Creates an empty array.
  7972. @param granularity this is the size of increment by which the internal storage
  7973. used by the array will grow. Only change it from the default if you know the
  7974. array is going to be very big and needs to be able to grow efficiently.
  7975. @see ReferenceCountedObject, Array, OwnedArray
  7976. */
  7977. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7978. : data (granularity),
  7979. numUsed (0)
  7980. {
  7981. }
  7982. /** Creates a copy of another array */
  7983. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7984. : data (other.data.granularity)
  7985. {
  7986. other.lockArray();
  7987. numUsed = other.numUsed;
  7988. data.setAllocatedSize (numUsed);
  7989. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7990. for (int i = numUsed; --i >= 0;)
  7991. if (data.elements[i] != 0)
  7992. data.elements[i]->incReferenceCount();
  7993. other.unlockArray();
  7994. }
  7995. /** Copies another array into this one.
  7996. Any existing objects in this array will first be released.
  7997. */
  7998. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7999. {
  8000. if (this != &other)
  8001. {
  8002. other.lockArray();
  8003. lock.enter();
  8004. clear();
  8005. data.granularity = other.granularity;
  8006. data.ensureAllocatedSize (other.numUsed);
  8007. numUsed = other.numUsed;
  8008. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  8009. minimiseStorageOverheads();
  8010. for (int i = numUsed; --i >= 0;)
  8011. if (data.elements[i] != 0)
  8012. data.elements[i]->incReferenceCount();
  8013. lock.exit();
  8014. other.unlockArray();
  8015. }
  8016. return *this;
  8017. }
  8018. /** Destructor.
  8019. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  8020. */
  8021. ~ReferenceCountedArray()
  8022. {
  8023. clear();
  8024. }
  8025. /** Removes all objects from the array.
  8026. Any objects in the array that are not referenced from elsewhere will be deleted.
  8027. */
  8028. void clear()
  8029. {
  8030. lock.enter();
  8031. while (numUsed > 0)
  8032. if (data.elements [--numUsed] != 0)
  8033. data.elements [numUsed]->decReferenceCount();
  8034. jassert (numUsed == 0);
  8035. data.setAllocatedSize (0);
  8036. lock.exit();
  8037. }
  8038. /** Returns the current number of objects in the array. */
  8039. inline int size() const throw()
  8040. {
  8041. return numUsed;
  8042. }
  8043. /** Returns a pointer to the object at this index in the array.
  8044. If the index is out-of-range, this will return a null pointer, (and
  8045. it could be null anyway, because it's ok for the array to hold null
  8046. pointers as well as objects).
  8047. @see getUnchecked
  8048. */
  8049. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  8050. {
  8051. lock.enter();
  8052. const ReferenceCountedObjectPtr<ObjectClass> result ((((unsigned int) index) < (unsigned int) numUsed)
  8053. ? data.elements [index]
  8054. : (ObjectClass*) 0);
  8055. lock.exit();
  8056. return result;
  8057. }
  8058. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  8059. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  8060. it can be used when you're sure the index if always going to be legal.
  8061. */
  8062. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  8063. {
  8064. lock.enter();
  8065. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8066. const ReferenceCountedObjectPtr<ObjectClass> result (data.elements [index]);
  8067. lock.exit();
  8068. return result;
  8069. }
  8070. /** Returns a pointer to the first object in the array.
  8071. This will return a null pointer if the array's empty.
  8072. @see getLast
  8073. */
  8074. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  8075. {
  8076. lock.enter();
  8077. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? data.elements [0]
  8078. : (ObjectClass*) 0);
  8079. lock.exit();
  8080. return result;
  8081. }
  8082. /** Returns a pointer to the last object in the array.
  8083. This will return a null pointer if the array's empty.
  8084. @see getFirst
  8085. */
  8086. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  8087. {
  8088. lock.enter();
  8089. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? data.elements [numUsed - 1]
  8090. : (ObjectClass*) 0);
  8091. lock.exit();
  8092. return result;
  8093. }
  8094. /** Finds the index of the first occurrence of an object in the array.
  8095. @param objectToLookFor the object to look for
  8096. @returns the index at which the object was found, or -1 if it's not found
  8097. */
  8098. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  8099. {
  8100. int result = -1;
  8101. lock.enter();
  8102. ObjectClass** e = data.elements;
  8103. for (int i = numUsed; --i >= 0;)
  8104. {
  8105. if (objectToLookFor == *e)
  8106. {
  8107. result = (int) (e - data.elements);
  8108. break;
  8109. }
  8110. ++e;
  8111. }
  8112. lock.exit();
  8113. return result;
  8114. }
  8115. /** Returns true if the array contains a specified object.
  8116. @param objectToLookFor the object to look for
  8117. @returns true if the object is in the array
  8118. */
  8119. bool contains (const ObjectClass* const objectToLookFor) const throw()
  8120. {
  8121. lock.enter();
  8122. ObjectClass** e = data.elements;
  8123. for (int i = numUsed; --i >= 0;)
  8124. {
  8125. if (objectToLookFor == *e)
  8126. {
  8127. lock.exit();
  8128. return true;
  8129. }
  8130. ++e;
  8131. }
  8132. lock.exit();
  8133. return false;
  8134. }
  8135. /** Appends a new object to the end of the array.
  8136. This will increase the new object's reference count.
  8137. @param newObject the new object to add to the array
  8138. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  8139. */
  8140. void add (ObjectClass* const newObject) throw()
  8141. {
  8142. lock.enter();
  8143. data.ensureAllocatedSize (numUsed + 1);
  8144. data.elements [numUsed++] = newObject;
  8145. if (newObject != 0)
  8146. newObject->incReferenceCount();
  8147. lock.exit();
  8148. }
  8149. /** Inserts a new object into the array at the given index.
  8150. If the index is less than 0 or greater than the size of the array, the
  8151. element will be added to the end of the array.
  8152. Otherwise, it will be inserted into the array, moving all the later elements
  8153. along to make room.
  8154. This will increase the new object's reference count.
  8155. @param indexToInsertAt the index at which the new element should be inserted
  8156. @param newObject the new object to add to the array
  8157. @see add, addSorted, addIfNotAlreadyThere, set
  8158. */
  8159. void insert (int indexToInsertAt,
  8160. ObjectClass* const newObject) throw()
  8161. {
  8162. if (indexToInsertAt >= 0)
  8163. {
  8164. lock.enter();
  8165. if (indexToInsertAt > numUsed)
  8166. indexToInsertAt = numUsed;
  8167. data.ensureAllocatedSize (numUsed + 1);
  8168. ObjectClass** const e = data.elements + indexToInsertAt;
  8169. const int numToMove = numUsed - indexToInsertAt;
  8170. if (numToMove > 0)
  8171. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8172. *e = newObject;
  8173. if (newObject != 0)
  8174. newObject->incReferenceCount();
  8175. ++numUsed;
  8176. lock.exit();
  8177. }
  8178. else
  8179. {
  8180. add (newObject);
  8181. }
  8182. }
  8183. /** Appends a new object at the end of the array as long as the array doesn't
  8184. already contain it.
  8185. If the array already contains a matching object, nothing will be done.
  8186. @param newObject the new object to add to the array
  8187. */
  8188. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8189. {
  8190. lock.enter();
  8191. if (! contains (newObject))
  8192. add (newObject);
  8193. lock.exit();
  8194. }
  8195. /** Replaces an object in the array with a different one.
  8196. If the index is less than zero, this method does nothing.
  8197. If the index is beyond the end of the array, the new object is added to the end of the array.
  8198. The object being added has its reference count increased, and if it's replacing
  8199. another object, then that one has its reference count decreased, and may be deleted.
  8200. @param indexToChange the index whose value you want to change
  8201. @param newObject the new value to set for this index.
  8202. @see add, insert, remove
  8203. */
  8204. void set (const int indexToChange,
  8205. ObjectClass* const newObject)
  8206. {
  8207. if (indexToChange >= 0)
  8208. {
  8209. lock.enter();
  8210. if (newObject != 0)
  8211. newObject->incReferenceCount();
  8212. if (indexToChange < numUsed)
  8213. {
  8214. if (data.elements [indexToChange] != 0)
  8215. data.elements [indexToChange]->decReferenceCount();
  8216. data.elements [indexToChange] = newObject;
  8217. }
  8218. else
  8219. {
  8220. data.ensureAllocatedSize (numUsed + 1);
  8221. data.elements [numUsed++] = newObject;
  8222. }
  8223. lock.exit();
  8224. }
  8225. }
  8226. /** Adds elements from another array to the end of this array.
  8227. @param arrayToAddFrom the array from which to copy the elements
  8228. @param startIndex the first element of the other array to start copying from
  8229. @param numElementsToAdd how many elements to add from the other array. If this
  8230. value is negative or greater than the number of available elements,
  8231. all available elements will be copied.
  8232. @see add
  8233. */
  8234. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8235. int startIndex = 0,
  8236. int numElementsToAdd = -1) throw()
  8237. {
  8238. arrayToAddFrom.lockArray();
  8239. lock.enter();
  8240. if (startIndex < 0)
  8241. {
  8242. jassertfalse
  8243. startIndex = 0;
  8244. }
  8245. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8246. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8247. if (numElementsToAdd > 0)
  8248. {
  8249. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8250. while (--numElementsToAdd >= 0)
  8251. add (arrayToAddFrom.getUnchecked (startIndex++));
  8252. }
  8253. lock.exit();
  8254. arrayToAddFrom.unlockArray();
  8255. }
  8256. /** Inserts a new object into the array assuming that the array is sorted.
  8257. This will use a comparator to find the position at which the new object
  8258. should go. If the array isn't sorted, the behaviour of this
  8259. method will be unpredictable.
  8260. @param comparator the comparator object to use to compare the elements - see the
  8261. sort() method for details about this object's form
  8262. @param newObject the new object to insert to the array
  8263. @see add, sort
  8264. */
  8265. template <class ElementComparator>
  8266. void addSorted (ElementComparator& comparator,
  8267. ObjectClass* newObject) throw()
  8268. {
  8269. lock.enter();
  8270. insert (findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed), newObject);
  8271. lock.exit();
  8272. }
  8273. /** Inserts or replaces an object in the array, assuming it is sorted.
  8274. This is similar to addSorted, but if a matching element already exists, then it will be
  8275. replaced by the new one, rather than the new one being added as well.
  8276. */
  8277. template <class ElementComparator>
  8278. void addOrReplaceSorted (ElementComparator& comparator,
  8279. ObjectClass* newObject) throw()
  8280. {
  8281. lock.enter();
  8282. const int index = findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed);
  8283. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8284. set (index - 1, newObject); // replace an existing object that matches
  8285. else
  8286. insert (index, newObject); // no match, so insert the new one
  8287. lock.exit();
  8288. }
  8289. /** Removes an object from the array.
  8290. This will remove the object at a given index and move back all the
  8291. subsequent objects to close the gap.
  8292. If the index passed in is out-of-range, nothing will happen.
  8293. The object that is removed will have its reference count decreased,
  8294. and may be deleted if not referenced from elsewhere.
  8295. @param indexToRemove the index of the element to remove
  8296. @see removeObject, removeRange
  8297. */
  8298. void remove (const int indexToRemove)
  8299. {
  8300. lock.enter();
  8301. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8302. {
  8303. ObjectClass** const e = data.elements + indexToRemove;
  8304. if (*e != 0)
  8305. (*e)->decReferenceCount();
  8306. --numUsed;
  8307. const int numberToShift = numUsed - indexToRemove;
  8308. if (numberToShift > 0)
  8309. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8310. if ((numUsed << 1) < data.numAllocated)
  8311. minimiseStorageOverheads();
  8312. }
  8313. lock.exit();
  8314. }
  8315. /** Removes the first occurrence of a specified object from the array.
  8316. If the item isn't found, no action is taken. If it is found, it is
  8317. removed and has its reference count decreased.
  8318. @param objectToRemove the object to try to remove
  8319. @see remove, removeRange
  8320. */
  8321. void removeObject (ObjectClass* const objectToRemove)
  8322. {
  8323. lock.enter();
  8324. remove (indexOf (objectToRemove));
  8325. lock.exit();
  8326. }
  8327. /** Removes a range of objects from the array.
  8328. This will remove a set of objects, starting from the given index,
  8329. and move any subsequent elements down to close the gap.
  8330. If the range extends beyond the bounds of the array, it will
  8331. be safely clipped to the size of the array.
  8332. The objects that are removed will have their reference counts decreased,
  8333. and may be deleted if not referenced from elsewhere.
  8334. @param startIndex the index of the first object to remove
  8335. @param numberToRemove how many objects should be removed
  8336. @see remove, removeObject
  8337. */
  8338. void removeRange (const int startIndex,
  8339. const int numberToRemove)
  8340. {
  8341. lock.enter();
  8342. const int start = jlimit (0, numUsed, startIndex);
  8343. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8344. if (end > start)
  8345. {
  8346. int i;
  8347. for (i = start; i < end; ++i)
  8348. {
  8349. if (data.elements[i] != 0)
  8350. {
  8351. data.elements[i]->decReferenceCount();
  8352. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8353. }
  8354. }
  8355. const int rangeSize = end - start;
  8356. ObjectClass** e = data.elements + start;
  8357. i = numUsed - end;
  8358. numUsed -= rangeSize;
  8359. while (--i >= 0)
  8360. {
  8361. *e = e [rangeSize];
  8362. ++e;
  8363. }
  8364. if ((numUsed << 1) < data.numAllocated)
  8365. minimiseStorageOverheads();
  8366. }
  8367. lock.exit();
  8368. }
  8369. /** Removes the last n objects from the array.
  8370. The objects that are removed will have their reference counts decreased,
  8371. and may be deleted if not referenced from elsewhere.
  8372. @param howManyToRemove how many objects to remove from the end of the array
  8373. @see remove, removeObject, removeRange
  8374. */
  8375. void removeLast (int howManyToRemove = 1)
  8376. {
  8377. lock.enter();
  8378. if (howManyToRemove > numUsed)
  8379. howManyToRemove = numUsed;
  8380. while (--howManyToRemove >= 0)
  8381. remove (numUsed - 1);
  8382. lock.exit();
  8383. }
  8384. /** Swaps a pair of objects in the array.
  8385. If either of the indexes passed in is out-of-range, nothing will happen,
  8386. otherwise the two objects at these positions will be exchanged.
  8387. */
  8388. void swap (const int index1,
  8389. const int index2) throw()
  8390. {
  8391. lock.enter();
  8392. if (((unsigned int) index1) < (unsigned int) numUsed
  8393. && ((unsigned int) index2) < (unsigned int) numUsed)
  8394. {
  8395. swapVariables (data.elements [index1],
  8396. data.elements [index2]);
  8397. }
  8398. lock.exit();
  8399. }
  8400. /** Moves one of the objects to a different position.
  8401. This will move the object to a specified index, shuffling along
  8402. any intervening elements as required.
  8403. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8404. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8405. @param currentIndex the index of the object to be moved. If this isn't a
  8406. valid index, then nothing will be done
  8407. @param newIndex the index at which you'd like this object to end up. If this
  8408. is less than zero, it will be moved to the end of the array
  8409. */
  8410. void move (const int currentIndex,
  8411. int newIndex) throw()
  8412. {
  8413. if (currentIndex != newIndex)
  8414. {
  8415. lock.enter();
  8416. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8417. {
  8418. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8419. newIndex = numUsed - 1;
  8420. ObjectClass* const value = data.elements [currentIndex];
  8421. if (newIndex > currentIndex)
  8422. {
  8423. memmove (data.elements + currentIndex,
  8424. data.elements + currentIndex + 1,
  8425. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8426. }
  8427. else
  8428. {
  8429. memmove (data.elements + newIndex + 1,
  8430. data.elements + newIndex,
  8431. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8432. }
  8433. data.elements [newIndex] = value;
  8434. }
  8435. lock.exit();
  8436. }
  8437. }
  8438. /** Compares this array to another one.
  8439. @returns true only if the other array contains the same objects in the same order
  8440. */
  8441. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8442. {
  8443. other.lockArray();
  8444. lock.enter();
  8445. bool result = numUsed == other.numUsed;
  8446. if (result)
  8447. {
  8448. for (int i = numUsed; --i >= 0;)
  8449. {
  8450. if (data.elements [i] != other.data.elements [i])
  8451. {
  8452. result = false;
  8453. break;
  8454. }
  8455. }
  8456. }
  8457. lock.exit();
  8458. other.unlockArray();
  8459. return result;
  8460. }
  8461. /** Compares this array to another one.
  8462. @see operator==
  8463. */
  8464. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8465. {
  8466. return ! operator== (other);
  8467. }
  8468. /** Sorts the elements in the array.
  8469. This will use a comparator object to sort the elements into order. The object
  8470. passed must have a method of the form:
  8471. @code
  8472. int compareElements (ElementType first, ElementType second);
  8473. @endcode
  8474. ..and this method must return:
  8475. - a value of < 0 if the first comes before the second
  8476. - a value of 0 if the two objects are equivalent
  8477. - a value of > 0 if the second comes before the first
  8478. To improve performance, the compareElements() method can be declared as static or const.
  8479. @param comparator the comparator to use for comparing elements.
  8480. @param retainOrderOfEquivalentItems if this is true, then items
  8481. which the comparator says are equivalent will be
  8482. kept in the order in which they currently appear
  8483. in the array. This is slower to perform, but may
  8484. be important in some cases. If it's false, a faster
  8485. algorithm is used, but equivalent elements may be
  8486. rearranged.
  8487. @see sortArray
  8488. */
  8489. template <class ElementComparator>
  8490. void sort (ElementComparator& comparator,
  8491. const bool retainOrderOfEquivalentItems = false) const throw()
  8492. {
  8493. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8494. // avoids getting warning messages about the parameter being unused
  8495. lock.enter();
  8496. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  8497. lock.exit();
  8498. }
  8499. /** Reduces the amount of storage being used by the array.
  8500. Arrays typically allocate slightly more storage than they need, and after
  8501. removing elements, they may have quite a lot of unused space allocated.
  8502. This method will reduce the amount of allocated storage to a minimum.
  8503. */
  8504. void minimiseStorageOverheads() throw()
  8505. {
  8506. lock.enter();
  8507. if (numUsed == 0)
  8508. {
  8509. data.setAllocatedSize (0);
  8510. }
  8511. else
  8512. {
  8513. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  8514. if (newAllocation < data.numAllocated)
  8515. data.setAllocatedSize (newAllocation);
  8516. }
  8517. lock.exit();
  8518. }
  8519. /** Locks the array's CriticalSection.
  8520. Of course if the type of section used is a DummyCriticalSection, this won't
  8521. have any effect.
  8522. @see unlockArray
  8523. */
  8524. void lockArray() const throw()
  8525. {
  8526. lock.enter();
  8527. }
  8528. /** Unlocks the array's CriticalSection.
  8529. Of course if the type of section used is a DummyCriticalSection, this won't
  8530. have any effect.
  8531. @see lockArray
  8532. */
  8533. void unlockArray() const throw()
  8534. {
  8535. lock.exit();
  8536. }
  8537. juce_UseDebuggingNewOperator
  8538. private:
  8539. ArrayAllocationBase <ObjectClass*> data;
  8540. int numUsed;
  8541. TypeOfCriticalSectionToUse lock;
  8542. };
  8543. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8544. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  8545. #endif
  8546. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8547. #endif
  8548. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8549. /********* Start of inlined file: juce_SortedSet.h *********/
  8550. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8551. #define __JUCE_SORTEDSET_JUCEHEADER__
  8552. #if JUCE_MSVC
  8553. #pragma warning (push)
  8554. #pragma warning (disable: 4512)
  8555. #endif
  8556. /**
  8557. Holds a set of unique primitive objects, such as ints or doubles.
  8558. A set can only hold one item with a given value, so if for example it's a
  8559. set of integers, attempting to add the same integer twice will do nothing
  8560. the second time.
  8561. Internally, the list of items is kept sorted (which means that whatever
  8562. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8563. to determine the order), and searching the set for known values is very fast
  8564. because it uses a binary-chop method.
  8565. Note that if you're using a class or struct as the element type, it must be
  8566. capable of being copied or moved with a straightforward memcpy, rather than
  8567. needing construction and destruction code.
  8568. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8569. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8570. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8571. */
  8572. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8573. class SortedSet
  8574. {
  8575. public:
  8576. /** Creates an empty set.
  8577. @param granularity this is the size of increment by which the internal storage
  8578. used by the array will grow. Only change it from the default if you know the
  8579. array is going to be very big and needs to be able to grow efficiently.
  8580. */
  8581. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  8582. : data (granularity),
  8583. numUsed (0)
  8584. {
  8585. }
  8586. /** Creates a copy of another set.
  8587. @param other the set to copy
  8588. */
  8589. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8590. : data (other.data.granularity)
  8591. {
  8592. other.lockSet();
  8593. numUsed = other.numUsed;
  8594. data.setAllocatedSize (other.numUsed);
  8595. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8596. other.unlockSet();
  8597. }
  8598. /** Destructor. */
  8599. ~SortedSet() throw()
  8600. {
  8601. }
  8602. /** Copies another set over this one.
  8603. @param other the set to copy
  8604. */
  8605. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8606. {
  8607. if (this != &other)
  8608. {
  8609. other.lockSet();
  8610. lock.enter();
  8611. data.granularity = other.data.granularity;
  8612. data.ensureAllocatedSize (other.size());
  8613. numUsed = other.numUsed;
  8614. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8615. minimiseStorageOverheads();
  8616. lock.exit();
  8617. other.unlockSet();
  8618. }
  8619. return *this;
  8620. }
  8621. /** Compares this set to another one.
  8622. Two sets are considered equal if they both contain the same set of
  8623. elements.
  8624. @param other the other set to compare with
  8625. */
  8626. bool operator== (const SortedSet<ElementType>& other) const throw()
  8627. {
  8628. lock.enter();
  8629. if (numUsed != other.numUsed)
  8630. {
  8631. lock.exit();
  8632. return false;
  8633. }
  8634. for (int i = numUsed; --i >= 0;)
  8635. {
  8636. if (data.elements [i] != other.data.elements [i])
  8637. {
  8638. lock.exit();
  8639. return false;
  8640. }
  8641. }
  8642. lock.exit();
  8643. return true;
  8644. }
  8645. /** Compares this set to another one.
  8646. Two sets are considered equal if they both contain the same set of
  8647. elements.
  8648. @param other the other set to compare with
  8649. */
  8650. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8651. {
  8652. return ! operator== (other);
  8653. }
  8654. /** Removes all elements from the set.
  8655. This will remove all the elements, and free any storage that the set is
  8656. using. To clear it without freeing the storage, use the clearQuick()
  8657. method instead.
  8658. @see clearQuick
  8659. */
  8660. void clear() throw()
  8661. {
  8662. lock.enter();
  8663. data.setAllocatedSize (0);
  8664. numUsed = 0;
  8665. lock.exit();
  8666. }
  8667. /** Removes all elements from the set without freeing the array's allocated storage.
  8668. @see clear
  8669. */
  8670. void clearQuick() throw()
  8671. {
  8672. lock.enter();
  8673. numUsed = 0;
  8674. lock.exit();
  8675. }
  8676. /** Returns the current number of elements in the set.
  8677. */
  8678. inline int size() const throw()
  8679. {
  8680. return numUsed;
  8681. }
  8682. /** Returns one of the elements in the set.
  8683. If the index passed in is beyond the range of valid elements, this
  8684. will return zero.
  8685. If you're certain that the index will always be a valid element, you
  8686. can call getUnchecked() instead, which is faster.
  8687. @param index the index of the element being requested (0 is the first element in the set)
  8688. @see getUnchecked, getFirst, getLast
  8689. */
  8690. inline ElementType operator[] (const int index) const throw()
  8691. {
  8692. lock.enter();
  8693. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8694. ? data.elements [index]
  8695. : (ElementType) 0;
  8696. lock.exit();
  8697. return result;
  8698. }
  8699. /** Returns one of the elements in the set, without checking the index passed in.
  8700. Unlike the operator[] method, this will try to return an element without
  8701. checking that the index is within the bounds of the set, so should only
  8702. be used when you're confident that it will always be a valid index.
  8703. @param index the index of the element being requested (0 is the first element in the set)
  8704. @see operator[], getFirst, getLast
  8705. */
  8706. inline ElementType getUnchecked (const int index) const throw()
  8707. {
  8708. lock.enter();
  8709. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8710. const ElementType result = data.elements [index];
  8711. lock.exit();
  8712. return result;
  8713. }
  8714. /** Returns the first element in the set, or 0 if the set is empty.
  8715. @see operator[], getUnchecked, getLast
  8716. */
  8717. inline ElementType getFirst() const throw()
  8718. {
  8719. lock.enter();
  8720. const ElementType result = (numUsed > 0) ? data.elements [0]
  8721. : (ElementType) 0;
  8722. lock.exit();
  8723. return result;
  8724. }
  8725. /** Returns the last element in the set, or 0 if the set is empty.
  8726. @see operator[], getUnchecked, getFirst
  8727. */
  8728. inline ElementType getLast() const throw()
  8729. {
  8730. lock.enter();
  8731. const ElementType result = (numUsed > 0) ? data.elements [numUsed - 1]
  8732. : (ElementType) 0;
  8733. lock.exit();
  8734. return result;
  8735. }
  8736. /** Finds the index of the first element which matches the value passed in.
  8737. This will search the set for the given object, and return the index
  8738. of its first occurrence. If the object isn't found, the method will return -1.
  8739. @param elementToLookFor the value or object to look for
  8740. @returns the index of the object, or -1 if it's not found
  8741. */
  8742. int indexOf (const ElementType elementToLookFor) const throw()
  8743. {
  8744. lock.enter();
  8745. int start = 0;
  8746. int end = numUsed;
  8747. for (;;)
  8748. {
  8749. if (start >= end)
  8750. {
  8751. lock.exit();
  8752. return -1;
  8753. }
  8754. else if (elementToLookFor == data.elements [start])
  8755. {
  8756. lock.exit();
  8757. return start;
  8758. }
  8759. else
  8760. {
  8761. const int halfway = (start + end) >> 1;
  8762. if (halfway == start)
  8763. {
  8764. lock.exit();
  8765. return -1;
  8766. }
  8767. else if (elementToLookFor >= data.elements [halfway])
  8768. start = halfway;
  8769. else
  8770. end = halfway;
  8771. }
  8772. }
  8773. }
  8774. /** Returns true if the set contains at least one occurrence of an object.
  8775. @param elementToLookFor the value or object to look for
  8776. @returns true if the item is found
  8777. */
  8778. bool contains (const ElementType elementToLookFor) const throw()
  8779. {
  8780. lock.enter();
  8781. int start = 0;
  8782. int end = numUsed;
  8783. for (;;)
  8784. {
  8785. if (start >= end)
  8786. {
  8787. lock.exit();
  8788. return false;
  8789. }
  8790. else if (elementToLookFor == data.elements [start])
  8791. {
  8792. lock.exit();
  8793. return true;
  8794. }
  8795. else
  8796. {
  8797. const int halfway = (start + end) >> 1;
  8798. if (halfway == start)
  8799. {
  8800. lock.exit();
  8801. return false;
  8802. }
  8803. else if (elementToLookFor >= data.elements [halfway])
  8804. start = halfway;
  8805. else
  8806. end = halfway;
  8807. }
  8808. }
  8809. }
  8810. /** Adds a new element to the set, (as long as it's not already in there).
  8811. @param newElement the new object to add to the set
  8812. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8813. */
  8814. void add (const ElementType newElement) throw()
  8815. {
  8816. lock.enter();
  8817. int start = 0;
  8818. int end = numUsed;
  8819. for (;;)
  8820. {
  8821. if (start >= end)
  8822. {
  8823. jassert (start <= end);
  8824. insertInternal (start, newElement);
  8825. break;
  8826. }
  8827. else if (newElement == data.elements [start])
  8828. {
  8829. break;
  8830. }
  8831. else
  8832. {
  8833. const int halfway = (start + end) >> 1;
  8834. if (halfway == start)
  8835. {
  8836. if (newElement >= data.elements [halfway])
  8837. insertInternal (start + 1, newElement);
  8838. else
  8839. insertInternal (start, newElement);
  8840. break;
  8841. }
  8842. else if (newElement >= data.elements [halfway])
  8843. start = halfway;
  8844. else
  8845. end = halfway;
  8846. }
  8847. }
  8848. lock.exit();
  8849. }
  8850. /** Adds elements from an array to this set.
  8851. @param elementsToAdd the array of elements to add
  8852. @param numElementsToAdd how many elements are in this other array
  8853. @see add
  8854. */
  8855. void addArray (const ElementType* elementsToAdd,
  8856. int numElementsToAdd) throw()
  8857. {
  8858. lock.enter();
  8859. while (--numElementsToAdd >= 0)
  8860. add (*elementsToAdd++);
  8861. lock.exit();
  8862. }
  8863. /** Adds elements from another set to this one.
  8864. @param setToAddFrom the set from which to copy the elements
  8865. @param startIndex the first element of the other set to start copying from
  8866. @param numElementsToAdd how many elements to add from the other set. If this
  8867. value is negative or greater than the number of available elements,
  8868. all available elements will be copied.
  8869. @see add
  8870. */
  8871. template <class OtherSetType>
  8872. void addSet (const OtherSetType& setToAddFrom,
  8873. int startIndex = 0,
  8874. int numElementsToAdd = -1) throw()
  8875. {
  8876. setToAddFrom.lockSet();
  8877. lock.enter();
  8878. jassert (this != &setToAddFrom);
  8879. if (this != &setToAddFrom)
  8880. {
  8881. if (startIndex < 0)
  8882. {
  8883. jassertfalse
  8884. startIndex = 0;
  8885. }
  8886. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8887. numElementsToAdd = setToAddFrom.size() - startIndex;
  8888. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8889. }
  8890. lock.exit();
  8891. setToAddFrom.unlockSet();
  8892. }
  8893. /** Removes an element from the set.
  8894. This will remove the element at a given index.
  8895. If the index passed in is out-of-range, nothing will happen.
  8896. @param indexToRemove the index of the element to remove
  8897. @returns the element that has been removed
  8898. @see removeValue, removeRange
  8899. */
  8900. ElementType remove (const int indexToRemove) throw()
  8901. {
  8902. lock.enter();
  8903. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8904. {
  8905. --numUsed;
  8906. ElementType* const e = data.elements + indexToRemove;
  8907. ElementType const removed = *e;
  8908. const int numberToShift = numUsed - indexToRemove;
  8909. if (numberToShift > 0)
  8910. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8911. if ((numUsed << 1) < data.numAllocated)
  8912. minimiseStorageOverheads();
  8913. lock.exit();
  8914. return removed;
  8915. }
  8916. else
  8917. {
  8918. lock.exit();
  8919. return 0;
  8920. }
  8921. }
  8922. /** Removes an item from the set.
  8923. This will remove the given element from the set, if it's there.
  8924. @param valueToRemove the object to try to remove
  8925. @see remove, removeRange
  8926. */
  8927. void removeValue (const ElementType valueToRemove) throw()
  8928. {
  8929. lock.enter();
  8930. remove (indexOf (valueToRemove));
  8931. lock.exit();
  8932. }
  8933. /** Removes any elements which are also in another set.
  8934. @param otherSet the other set in which to look for elements to remove
  8935. @see removeValuesNotIn, remove, removeValue, removeRange
  8936. */
  8937. template <class OtherSetType>
  8938. void removeValuesIn (const OtherSetType& otherSet) throw()
  8939. {
  8940. otherSet.lockSet();
  8941. lock.enter();
  8942. if (this == &otherSet)
  8943. {
  8944. clear();
  8945. }
  8946. else
  8947. {
  8948. if (otherSet.size() > 0)
  8949. {
  8950. for (int i = numUsed; --i >= 0;)
  8951. if (otherSet.contains (data.elements [i]))
  8952. remove (i);
  8953. }
  8954. }
  8955. lock.exit();
  8956. otherSet.unlockSet();
  8957. }
  8958. /** Removes any elements which are not found in another set.
  8959. Only elements which occur in this other set will be retained.
  8960. @param otherSet the set in which to look for elements NOT to remove
  8961. @see removeValuesIn, remove, removeValue, removeRange
  8962. */
  8963. template <class OtherSetType>
  8964. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8965. {
  8966. otherSet.lockSet();
  8967. lock.enter();
  8968. if (this != &otherSet)
  8969. {
  8970. if (otherSet.size() <= 0)
  8971. {
  8972. clear();
  8973. }
  8974. else
  8975. {
  8976. for (int i = numUsed; --i >= 0;)
  8977. if (! otherSet.contains (data.elements [i]))
  8978. remove (i);
  8979. }
  8980. }
  8981. lock.exit();
  8982. otherSet.lockSet();
  8983. }
  8984. /** Reduces the amount of storage being used by the set.
  8985. Sets typically allocate slightly more storage than they need, and after
  8986. removing elements, they may have quite a lot of unused space allocated.
  8987. This method will reduce the amount of allocated storage to a minimum.
  8988. */
  8989. void minimiseStorageOverheads() throw()
  8990. {
  8991. lock.enter();
  8992. if (numUsed == 0)
  8993. {
  8994. data.setAllocatedSize (0);
  8995. }
  8996. else
  8997. {
  8998. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  8999. if (newAllocation < data.numAllocated)
  9000. data.setAllocatedSize (newAllocation);
  9001. }
  9002. lock.exit();
  9003. }
  9004. /** Locks the set's CriticalSection.
  9005. Of course if the type of section used is a DummyCriticalSection, this won't
  9006. have any effect.
  9007. @see unlockSet
  9008. */
  9009. void lockSet() const throw()
  9010. {
  9011. lock.enter();
  9012. }
  9013. /** Unlocks the set's CriticalSection.
  9014. Of course if the type of section used is a DummyCriticalSection, this won't
  9015. have any effect.
  9016. @see lockSet
  9017. */
  9018. void unlockSet() const throw()
  9019. {
  9020. lock.exit();
  9021. }
  9022. juce_UseDebuggingNewOperator
  9023. private:
  9024. ArrayAllocationBase <ElementType> data;
  9025. int numUsed;
  9026. TypeOfCriticalSectionToUse lock;
  9027. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  9028. {
  9029. data.ensureAllocatedSize (numUsed + 1);
  9030. ElementType* const insertPos = data.elements + indexToInsertAt;
  9031. const int numberToMove = numUsed - indexToInsertAt;
  9032. if (numberToMove > 0)
  9033. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  9034. *insertPos = newElement;
  9035. ++numUsed;
  9036. }
  9037. };
  9038. #if JUCE_MSVC
  9039. #pragma warning (pop)
  9040. #endif
  9041. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  9042. /********* End of inlined file: juce_SortedSet.h *********/
  9043. #endif
  9044. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  9045. /********* Start of inlined file: juce_SparseSet.h *********/
  9046. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  9047. #define __JUCE_SPARSESET_JUCEHEADER__
  9048. /**
  9049. Holds a set of primitive values, storing them as a set of ranges.
  9050. This container acts like a simple BitArray, but can efficiently hold large
  9051. continguous ranges of values. It's quite a specialised class, mostly useful
  9052. for things like keeping the set of selected rows in a listbox.
  9053. The type used as a template paramter must be an integer type, such as int, short,
  9054. int64, etc.
  9055. */
  9056. template <class Type>
  9057. class SparseSet
  9058. {
  9059. public:
  9060. /** Creates a new empty set. */
  9061. SparseSet() throw()
  9062. {
  9063. }
  9064. /** Creates a copy of another SparseSet. */
  9065. SparseSet (const SparseSet<Type>& other) throw()
  9066. : values (other.values)
  9067. {
  9068. }
  9069. /** Destructor. */
  9070. ~SparseSet() throw()
  9071. {
  9072. }
  9073. /** Clears the set. */
  9074. void clear() throw()
  9075. {
  9076. values.clear();
  9077. }
  9078. /** Checks whether the set is empty.
  9079. This is much quicker than using (size() == 0).
  9080. */
  9081. bool isEmpty() const throw()
  9082. {
  9083. return values.size() == 0;
  9084. }
  9085. /** Returns the number of values in the set.
  9086. Because of the way the data is stored, this method can take longer if there
  9087. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  9088. are any items.
  9089. */
  9090. Type size() const throw()
  9091. {
  9092. Type num = 0;
  9093. for (int i = 0; i < values.size(); i += 2)
  9094. num += values[i + 1] - values[i];
  9095. return num;
  9096. }
  9097. /** Returns one of the values in the set.
  9098. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  9099. @returns the value at this index, or 0 if it's out-of-range
  9100. */
  9101. Type operator[] (int index) const throw()
  9102. {
  9103. for (int i = 0; i < values.size(); i += 2)
  9104. {
  9105. const Type s = values.getUnchecked(i);
  9106. const Type e = values.getUnchecked(i + 1);
  9107. if (index < e - s)
  9108. return s + index;
  9109. index -= e - s;
  9110. }
  9111. return (Type) 0;
  9112. }
  9113. /** Checks whether a particular value is in the set. */
  9114. bool contains (const Type valueToLookFor) const throw()
  9115. {
  9116. bool on = false;
  9117. for (int i = 0; i < values.size(); ++i)
  9118. {
  9119. if (values.getUnchecked(i) > valueToLookFor)
  9120. return on;
  9121. on = ! on;
  9122. }
  9123. return false;
  9124. }
  9125. /** Returns the number of contiguous blocks of values.
  9126. @see getRange
  9127. */
  9128. int getNumRanges() const throw()
  9129. {
  9130. return values.size() >> 1;
  9131. }
  9132. /** Returns one of the contiguous ranges of values stored.
  9133. @param rangeIndex the index of the range to look up, between 0
  9134. and (getNumRanges() - 1)
  9135. @param startValue on return, the value at the start of the range
  9136. @param numValues on return, the number of values in the range
  9137. @see getTotalRange
  9138. */
  9139. bool getRange (const int rangeIndex,
  9140. Type& startValue,
  9141. Type& numValues) const throw()
  9142. {
  9143. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  9144. {
  9145. startValue = values [rangeIndex << 1];
  9146. numValues = values [(rangeIndex << 1) + 1] - startValue;
  9147. return true;
  9148. }
  9149. return false;
  9150. }
  9151. /** Returns the lowest and highest values in the set.
  9152. @see getRange
  9153. */
  9154. bool getTotalRange (Type& lowestValue,
  9155. Type& highestValue) const throw()
  9156. {
  9157. if (values.size() > 0)
  9158. {
  9159. lowestValue = values.getUnchecked (0);
  9160. highestValue = values.getUnchecked (values.size() - 1);
  9161. return true;
  9162. }
  9163. return false;
  9164. }
  9165. /** Adds a range of contiguous values to the set.
  9166. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  9167. @param firstValue the start of the range of values to add
  9168. @param numValuesToAdd how many values to add
  9169. */
  9170. void addRange (const Type firstValue,
  9171. const Type numValuesToAdd) throw()
  9172. {
  9173. jassert (numValuesToAdd >= 0);
  9174. if (numValuesToAdd > 0)
  9175. {
  9176. removeRange (firstValue, numValuesToAdd);
  9177. IntegerElementComparator<Type> sorter;
  9178. values.addSorted (sorter, firstValue);
  9179. values.addSorted (sorter, firstValue + numValuesToAdd);
  9180. simplify();
  9181. }
  9182. }
  9183. /** Removes a range of values from the set.
  9184. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  9185. @param firstValue the start of the range of values to remove
  9186. @param numValuesToRemove how many values to remove
  9187. */
  9188. void removeRange (const Type firstValue,
  9189. const Type numValuesToRemove) throw()
  9190. {
  9191. jassert (numValuesToRemove >= 0);
  9192. if (numValuesToRemove >= 0
  9193. && firstValue < values.getLast())
  9194. {
  9195. const bool onAtStart = contains (firstValue - 1);
  9196. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  9197. const bool onAtEnd = contains (lastValue);
  9198. for (int i = values.size(); --i >= 0;)
  9199. {
  9200. if (values.getUnchecked(i) <= lastValue)
  9201. {
  9202. while (values.getUnchecked(i) >= firstValue)
  9203. {
  9204. values.remove (i);
  9205. if (--i < 0)
  9206. break;
  9207. }
  9208. break;
  9209. }
  9210. }
  9211. IntegerElementComparator<Type> sorter;
  9212. if (onAtStart)
  9213. values.addSorted (sorter, firstValue);
  9214. if (onAtEnd)
  9215. values.addSorted (sorter, lastValue);
  9216. simplify();
  9217. }
  9218. }
  9219. /** Does an XOR of the values in a given range. */
  9220. void invertRange (const Type firstValue,
  9221. const Type numValues)
  9222. {
  9223. SparseSet newItems;
  9224. newItems.addRange (firstValue, numValues);
  9225. int i;
  9226. for (i = getNumRanges(); --i >= 0;)
  9227. {
  9228. const int start = values [i << 1];
  9229. const int end = values [(i << 1) + 1];
  9230. newItems.removeRange (start, end);
  9231. }
  9232. removeRange (firstValue, numValues);
  9233. for (i = newItems.getNumRanges(); --i >= 0;)
  9234. {
  9235. const int start = newItems.values [i << 1];
  9236. const int end = newItems.values [(i << 1) + 1];
  9237. addRange (start, end);
  9238. }
  9239. }
  9240. /** Checks whether any part of a given range overlaps any part of this one. */
  9241. bool overlapsRange (const Type firstValue,
  9242. const Type numValues) throw()
  9243. {
  9244. jassert (numValues >= 0);
  9245. if (numValues > 0)
  9246. {
  9247. for (int i = getNumRanges(); --i >= 0;)
  9248. {
  9249. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  9250. return false;
  9251. if (firstValue + numValues > values.getUnchecked (i << 1))
  9252. return true;
  9253. }
  9254. }
  9255. return false;
  9256. }
  9257. /** Checks whether the whole of a given range is contained within this one. */
  9258. bool containsRange (const Type firstValue,
  9259. const Type numValues) throw()
  9260. {
  9261. jassert (numValues >= 0);
  9262. if (numValues > 0)
  9263. {
  9264. for (int i = getNumRanges(); --i >= 0;)
  9265. {
  9266. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  9267. return false;
  9268. if (firstValue >= values.getUnchecked (i << 1)
  9269. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  9270. return true;
  9271. }
  9272. }
  9273. return false;
  9274. }
  9275. bool operator== (const SparseSet<Type>& other) throw()
  9276. {
  9277. return values == other.values;
  9278. }
  9279. bool operator!= (const SparseSet<Type>& other) throw()
  9280. {
  9281. return values != other.values;
  9282. }
  9283. juce_UseDebuggingNewOperator
  9284. private:
  9285. // alternating start/end values of ranges of values that are present.
  9286. Array<Type> values;
  9287. void simplify() throw()
  9288. {
  9289. jassert ((values.size() & 1) == 0);
  9290. for (int i = values.size(); --i > 0;)
  9291. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  9292. values.removeRange (i - 1, 2);
  9293. }
  9294. };
  9295. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9296. /********* End of inlined file: juce_SparseSet.h *********/
  9297. #endif
  9298. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9299. #endif
  9300. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9301. /********* Start of inlined file: juce_ValueTree.h *********/
  9302. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9303. #define __JUCE_VALUETREE_JUCEHEADER__
  9304. /********* Start of inlined file: juce_UndoManager.h *********/
  9305. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9306. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9307. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  9308. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9309. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9310. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  9311. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9312. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9313. /********* Start of inlined file: juce_ChangeListener.h *********/
  9314. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9315. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9316. /**
  9317. Receives callbacks about changes to some kind of object.
  9318. Many objects use a ChangeListenerList to keep a set of listeners which they
  9319. will inform when something changes. A subclass of ChangeListener
  9320. is used to receive these callbacks.
  9321. Note that the major difference between an ActionListener and a ChangeListener
  9322. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9323. callbacks, but ActionListeners perform one callback for every event posted.
  9324. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9325. */
  9326. class JUCE_API ChangeListener
  9327. {
  9328. public:
  9329. /** Destructor. */
  9330. virtual ~ChangeListener() {}
  9331. /** Overridden by your subclass to receive the callback.
  9332. @param objectThatHasChanged the value that was passed to the
  9333. ChangeListenerList::sendChangeMessage() method
  9334. */
  9335. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9336. };
  9337. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9338. /********* End of inlined file: juce_ChangeListener.h *********/
  9339. /********* Start of inlined file: juce_MessageListener.h *********/
  9340. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  9341. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  9342. /********* Start of inlined file: juce_Message.h *********/
  9343. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  9344. #define __JUCE_MESSAGE_JUCEHEADER__
  9345. class MessageListener;
  9346. class MessageManager;
  9347. /** The base class for objects that can be delivered to a MessageListener.
  9348. The simplest Message object contains a few integer and pointer parameters
  9349. that the user can set, and this is enough for a lot of purposes. For passing more
  9350. complex data, subclasses of Message can also be used.
  9351. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9352. */
  9353. class JUCE_API Message
  9354. {
  9355. public:
  9356. /** Creates an uninitialised message.
  9357. The class's variables will also be left uninitialised.
  9358. */
  9359. Message() throw();
  9360. /** Creates a message object, filling in the member variables.
  9361. The corresponding public member variables will be set from the parameters
  9362. passed in.
  9363. */
  9364. Message (const int intParameter1,
  9365. const int intParameter2,
  9366. const int intParameter3,
  9367. void* const pointerParameter) throw();
  9368. /** Destructor. */
  9369. virtual ~Message() throw();
  9370. // These values can be used for carrying simple data that the application needs to
  9371. // pass around. For more complex messages, just create a subclass.
  9372. int intParameter1; /**< user-defined integer value. */
  9373. int intParameter2; /**< user-defined integer value. */
  9374. int intParameter3; /**< user-defined integer value. */
  9375. void* pointerParameter; /**< user-defined pointer value. */
  9376. juce_UseDebuggingNewOperator
  9377. private:
  9378. friend class MessageListener;
  9379. friend class MessageManager;
  9380. MessageListener* messageRecipient;
  9381. Message (const Message&);
  9382. const Message& operator= (const Message&);
  9383. };
  9384. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9385. /********* End of inlined file: juce_Message.h *********/
  9386. /**
  9387. MessageListener subclasses can post and receive Message objects.
  9388. @see Message, MessageManager, ActionListener, ChangeListener
  9389. */
  9390. class JUCE_API MessageListener
  9391. {
  9392. protected:
  9393. /** Creates a MessageListener. */
  9394. MessageListener() throw();
  9395. public:
  9396. /** Destructor.
  9397. When a MessageListener is deleted, it removes itself from a global list
  9398. of registered listeners, so that the isValidMessageListener() method
  9399. will no longer return true.
  9400. */
  9401. virtual ~MessageListener();
  9402. /** This is the callback method that receives incoming messages.
  9403. This is called by the MessageManager from its dispatch loop.
  9404. @see postMessage
  9405. */
  9406. virtual void handleMessage (const Message& message) = 0;
  9407. /** Sends a message to the message queue, for asynchronous delivery to this listener
  9408. later on.
  9409. This method can be called safely by any thread.
  9410. @param message the message object to send - this will be deleted
  9411. automatically by the message queue, so don't keep any
  9412. references to it after calling this method.
  9413. @see handleMessage
  9414. */
  9415. void postMessage (Message* const message) const throw();
  9416. /** Checks whether this MessageListener has been deleted.
  9417. Although not foolproof, this method is safe to call on dangling or null
  9418. pointers. A list of active MessageListeners is kept internally, so this
  9419. checks whether the object is on this list or not.
  9420. Note that it's possible to get a false-positive here, if an object is
  9421. deleted and another is subsequently created that happens to be at the
  9422. exact same memory location, but I can't think of a good way of avoiding
  9423. this.
  9424. */
  9425. bool isValidMessageListener() const throw();
  9426. };
  9427. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  9428. /********* End of inlined file: juce_MessageListener.h *********/
  9429. /**
  9430. A set of ChangeListeners.
  9431. Listeners can be added and removed from the list, and change messages can be
  9432. broadcast to all the listeners.
  9433. @see ChangeListener, ChangeBroadcaster
  9434. */
  9435. class JUCE_API ChangeListenerList : public MessageListener
  9436. {
  9437. public:
  9438. /** Creates an empty list. */
  9439. ChangeListenerList() throw();
  9440. /** Destructor. */
  9441. ~ChangeListenerList() throw();
  9442. /** Adds a listener to the list.
  9443. (Trying to add a listener that's already on the list will have no effect).
  9444. */
  9445. void addChangeListener (ChangeListener* const listener) throw();
  9446. /** Removes a listener from the list.
  9447. If the listener isn't on the list, this won't have any effect.
  9448. */
  9449. void removeChangeListener (ChangeListener* const listener) throw();
  9450. /** Removes all listeners from the list. */
  9451. void removeAllChangeListeners() throw();
  9452. /** Posts an asynchronous change message to all the listeners.
  9453. If a message has already been sent and hasn't yet been delivered, this
  9454. method won't send another - in this way it coalesces multiple frequent
  9455. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9456. with the ActionListener, which posts a new event for every call to its
  9457. sendActionMessage() method.
  9458. Only listeners which are on the list when the change event is delivered
  9459. will receive the event - and this may include listeners that weren't on
  9460. the list when the change message was sent.
  9461. @param objectThatHasChanged this pointer is passed to the
  9462. ChangeListener::changeListenerCallback() method,
  9463. and can be any value the application needs
  9464. @see sendSynchronousChangeMessage
  9465. */
  9466. void sendChangeMessage (void* objectThatHasChanged) throw();
  9467. /** This will synchronously callback all the ChangeListeners.
  9468. Use this if you need to synchronously force a call to all the
  9469. listeners' ChangeListener::changeListenerCallback() methods.
  9470. */
  9471. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9472. /** If a change message has been sent but not yet dispatched, this will
  9473. use sendSynchronousChangeMessage() to make the callback immediately.
  9474. */
  9475. void dispatchPendingMessages();
  9476. /** @internal */
  9477. void handleMessage (const Message&);
  9478. juce_UseDebuggingNewOperator
  9479. private:
  9480. SortedSet <void*> listeners;
  9481. CriticalSection lock;
  9482. void* lastChangedObject;
  9483. bool messagePending;
  9484. ChangeListenerList (const ChangeListenerList&);
  9485. const ChangeListenerList& operator= (const ChangeListenerList&);
  9486. };
  9487. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9488. /********* End of inlined file: juce_ChangeListenerList.h *********/
  9489. /** Manages a list of ChangeListeners, and can send them messages.
  9490. To quickly add methods to your class that can add/remove change
  9491. listeners and broadcast to them, you can derive from this.
  9492. @see ChangeListenerList, ChangeListener
  9493. */
  9494. class JUCE_API ChangeBroadcaster
  9495. {
  9496. public:
  9497. /** Creates an ChangeBroadcaster. */
  9498. ChangeBroadcaster() throw();
  9499. /** Destructor. */
  9500. virtual ~ChangeBroadcaster();
  9501. /** Adds a listener to the list.
  9502. (Trying to add a listener that's already on the list will have no effect).
  9503. */
  9504. void addChangeListener (ChangeListener* const listener) throw();
  9505. /** Removes a listener from the list.
  9506. If the listener isn't on the list, this won't have any effect.
  9507. */
  9508. void removeChangeListener (ChangeListener* const listener) throw();
  9509. /** Removes all listeners from the list. */
  9510. void removeAllChangeListeners() throw();
  9511. /** Broadcasts a change message to all the registered listeners.
  9512. The message will be delivered asynchronously by the event thread, so this
  9513. method will not directly call any of the listeners. For a synchronous
  9514. message, use sendSynchronousChangeMessage().
  9515. @see ChangeListenerList::sendActionMessage
  9516. */
  9517. void sendChangeMessage (void* objectThatHasChanged) throw();
  9518. /** Sends a synchronous change message to all the registered listeners.
  9519. @see ChangeListenerList::sendSynchronousChangeMessage
  9520. */
  9521. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9522. /** If a change message has been sent but not yet dispatched, this will
  9523. use sendSynchronousChangeMessage() to make the callback immediately.
  9524. */
  9525. void dispatchPendingMessages();
  9526. private:
  9527. ChangeListenerList changeListenerList;
  9528. ChangeBroadcaster (const ChangeBroadcaster&);
  9529. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9530. };
  9531. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9532. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  9533. /********* Start of inlined file: juce_UndoableAction.h *********/
  9534. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9535. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9536. /**
  9537. Used by the UndoManager class to store an action which can be done
  9538. and undone.
  9539. @see UndoManager
  9540. */
  9541. class JUCE_API UndoableAction
  9542. {
  9543. protected:
  9544. /** Creates an action. */
  9545. UndoableAction() throw() {}
  9546. public:
  9547. /** Destructor. */
  9548. virtual ~UndoableAction() {}
  9549. /** Overridden by a subclass to perform the action.
  9550. This method is called by the UndoManager, and shouldn't be used directly by
  9551. applications.
  9552. Be careful not to make any calls in a perform() method that could call
  9553. recursively back into the UndoManager::perform() method
  9554. @returns true if the action could be performed.
  9555. @see UndoManager::perform
  9556. */
  9557. virtual bool perform() = 0;
  9558. /** Overridden by a subclass to undo the action.
  9559. This method is called by the UndoManager, and shouldn't be used directly by
  9560. applications.
  9561. Be careful not to make any calls in an undo() method that could call
  9562. recursively back into the UndoManager::perform() method
  9563. @returns true if the action could be undone without any errors.
  9564. @see UndoManager::perform
  9565. */
  9566. virtual bool undo() = 0;
  9567. /** Returns a value to indicate how much memory this object takes up.
  9568. Because the UndoManager keeps a list of UndoableActions, this is used
  9569. to work out how much space each one will take up, so that the UndoManager
  9570. can work out how many to keep.
  9571. The default value returned here is 10 - units are arbitrary and
  9572. don't have to be accurate.
  9573. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9574. UndoManager::setMaxNumberOfStoredUnits
  9575. */
  9576. virtual int getSizeInUnits() { return 10; }
  9577. };
  9578. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9579. /********* End of inlined file: juce_UndoableAction.h *********/
  9580. /**
  9581. Manages a list of undo/redo commands.
  9582. An UndoManager object keeps a list of past actions and can use these actions
  9583. to move backwards and forwards through an undo history.
  9584. To use it, create subclasses of UndoableAction which perform all the
  9585. actions you need, then when you need to actually perform an action, create one
  9586. and pass it to the UndoManager's perform() method.
  9587. The manager also uses the concept of 'transactions' to group the actions
  9588. together - all actions performed between calls to beginNewTransaction() are
  9589. grouped together and are all undone/redone as a group.
  9590. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9591. when actions are performed or undone.
  9592. @see UndoableAction
  9593. */
  9594. class JUCE_API UndoManager : public ChangeBroadcaster
  9595. {
  9596. public:
  9597. /** Creates an UndoManager.
  9598. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9599. to indicate how much storage it takes up
  9600. (UndoableAction::getSizeInUnits()), so this
  9601. lets you specify the maximum total number of
  9602. units that the undomanager is allowed to
  9603. keep in memory before letting the older actions
  9604. drop off the end of the list.
  9605. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9606. that will be kept, even if this involves exceeding
  9607. the amount of space specified in maxNumberOfUnitsToKeep
  9608. */
  9609. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  9610. const int minimumTransactionsToKeep = 30);
  9611. /** Destructor. */
  9612. ~UndoManager();
  9613. /** Deletes all stored actions in the list. */
  9614. void clearUndoHistory();
  9615. /** Returns the current amount of space to use for storing UndoableAction objects.
  9616. @see setMaxNumberOfStoredUnits
  9617. */
  9618. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9619. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9620. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9621. to indicate how much storage it takes up
  9622. (UndoableAction::getSizeInUnits()), so this
  9623. lets you specify the maximum total number of
  9624. units that the undomanager is allowed to
  9625. keep in memory before letting the older actions
  9626. drop off the end of the list.
  9627. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9628. that will be kept, even if this involves exceeding
  9629. the amount of space specified in maxNumberOfUnitsToKeep
  9630. @see getNumberOfUnitsTakenUpByStoredCommands
  9631. */
  9632. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  9633. const int minimumTransactionsToKeep);
  9634. /** Performs an action and adds it to the undo history list.
  9635. @param action the action to perform - this will be deleted by the UndoManager
  9636. when no longer needed
  9637. @param actionName if this string is non-empty, the current transaction will be
  9638. given this name; if it's empty, the current transaction name will
  9639. be left unchanged. See setCurrentTransactionName()
  9640. @returns true if the command succeeds - see UndoableAction::perform
  9641. @see beginNewTransaction
  9642. */
  9643. bool perform (UndoableAction* const action,
  9644. const String& actionName = String::empty);
  9645. /** Starts a new group of actions that together will be treated as a single transaction.
  9646. All actions that are passed to the perform() method between calls to this
  9647. method are grouped together and undone/redone together by a single call to
  9648. undo() or redo().
  9649. @param actionName a description of the transaction that is about to be
  9650. performed
  9651. */
  9652. void beginNewTransaction (const String& actionName = String::empty);
  9653. /** Changes the name stored for the current transaction.
  9654. Each transaction is given a name when the beginNewTransaction() method is
  9655. called, but this can be used to change that name without starting a new
  9656. transaction.
  9657. */
  9658. void setCurrentTransactionName (const String& newName);
  9659. /** Returns true if there's at least one action in the list to undo.
  9660. @see getUndoDescription, undo, canRedo
  9661. */
  9662. bool canUndo() const;
  9663. /** Returns the description of the transaction that would be next to get undone.
  9664. The description returned is the one that was passed into beginNewTransaction
  9665. before the set of actions was performed.
  9666. @see undo
  9667. */
  9668. const String getUndoDescription() const;
  9669. /** Tries to roll-back the last transaction.
  9670. @returns true if the transaction can be undone, and false if it fails, or
  9671. if there aren't any transactions to undo
  9672. */
  9673. bool undo();
  9674. /** Tries to roll-back any actions that were added to the current transaction.
  9675. This will perform an undo() only if there are some actions in the undo list
  9676. that were added after the last call to beginNewTransaction().
  9677. This is useful because it lets you call beginNewTransaction(), then
  9678. perform an operation which may or may not actually perform some actions, and
  9679. then call this method to get rid of any actions that might have been done
  9680. without it rolling back the previous transaction if nothing was actually
  9681. done.
  9682. @returns true if any actions were undone.
  9683. */
  9684. bool undoCurrentTransactionOnly();
  9685. /** Returns a list of the UndoableAction objects that have been performed during the
  9686. transaction that is currently open.
  9687. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9688. were to be called now.
  9689. The first item in the list is the earliest action performed.
  9690. */
  9691. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9692. /** Returns true if there's at least one action in the list to redo.
  9693. @see getRedoDescription, redo, canUndo
  9694. */
  9695. bool canRedo() const;
  9696. /** Returns the description of the transaction that would be next to get redone.
  9697. The description returned is the one that was passed into beginNewTransaction
  9698. before the set of actions was performed.
  9699. @see redo
  9700. */
  9701. const String getRedoDescription() const;
  9702. /** Tries to redo the last transaction that was undone.
  9703. @returns true if the transaction can be redone, and false if it fails, or
  9704. if there aren't any transactions to redo
  9705. */
  9706. bool redo();
  9707. juce_UseDebuggingNewOperator
  9708. private:
  9709. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9710. StringArray transactionNames;
  9711. String currentTransactionName;
  9712. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9713. bool newTransaction, reentrancyCheck;
  9714. // disallow copy constructor
  9715. UndoManager (const UndoManager&);
  9716. const UndoManager& operator= (const UndoManager&);
  9717. };
  9718. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  9719. /********* End of inlined file: juce_UndoManager.h *********/
  9720. /**
  9721. A powerful tree structure that can be used to hold free-form data, and which can
  9722. handle its own undo and redo behaviour.
  9723. A ValueTree contains a list of named properties as var objects, and also holds
  9724. any number of sub-trees.
  9725. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  9726. they are simply a lightweight reference to a shared data container. Creating a copy
  9727. of another ValueTree simply creates a new reference to the same underlying object - to
  9728. make a separate, deep copy of a tree you should explicitly call createCopy().
  9729. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  9730. and much of the structure of a ValueTree is similar to an XmlElement tree.
  9731. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  9732. contain text elements, the conversion works well and makes a good serialisation
  9733. format.
  9734. All the methods that change data take an optional UndoManager, which will be used
  9735. to track any changes to the object. For this to work, you have to be careful to
  9736. consistently always use the same UndoManager for all operations to any node inside
  9737. the tree.
  9738. Nodes can only be a child of one parent at a time, so if you're moving a node from
  9739. one tree to another, be careful to always remove it first, before adding it. This
  9740. could also mess up your undo/redo chain, so be wary!
  9741. Listeners can be added to a ValueTree to be told when properies change and when
  9742. nodes are added or removed.
  9743. @see var, XmlElement
  9744. */
  9745. class JUCE_API ValueTree
  9746. {
  9747. public:
  9748. /** Creates an empty ValueTree with the given type name.
  9749. Like an XmlElement, each ValueTree node has a type, which you can access with
  9750. getType() and hasType().
  9751. */
  9752. ValueTree (const String& type) throw();
  9753. /** Creates a reference to another ValueTree. */
  9754. ValueTree (const ValueTree& other) throw();
  9755. /** Makes this object reference another node. */
  9756. const ValueTree& operator= (const ValueTree& other) throw();
  9757. /** Destructor. */
  9758. ~ValueTree() throw();
  9759. /** Returns true if both this and the other tree node refer to the same underlying structure.
  9760. Note that this isn't a value comparison - two independently-created trees which
  9761. contain identical data are not considered equal.
  9762. */
  9763. bool operator== (const ValueTree& other) const throw();
  9764. /** Returns true if this and the other node refer to different underlying structures.
  9765. Note that this isn't a value comparison - two independently-created trees which
  9766. contain identical data are not considered equal.
  9767. */
  9768. bool operator!= (const ValueTree& other) const throw();
  9769. /** Returns true if this node refers to some valid data.
  9770. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  9771. call to getChild().
  9772. */
  9773. bool isValid() const throw() { return object != 0; }
  9774. /** Returns a deep copy of this tree and all its sub-nodes. */
  9775. ValueTree createCopy() const throw();
  9776. /** Returns the type of this node.
  9777. The type is specified when the ValueTree is created.
  9778. @see hasType
  9779. */
  9780. const String getType() const throw();
  9781. /** Returns true if the node has this type.
  9782. The comparison is case-sensitive.
  9783. */
  9784. bool hasType (const String& typeName) const throw();
  9785. /** Returns the value of a named property.
  9786. If no such property has been set, this will return a void variant.
  9787. You can also use operator[] to get a property.
  9788. @see var, setProperty, hasProperty
  9789. */
  9790. const var getProperty (const var::identifier& name) const throw();
  9791. /** Returns the value of a named property.
  9792. If no such property has been set, this will return a void variant. This is the same as
  9793. calling getProperty().
  9794. @see getProperty
  9795. */
  9796. const var operator[] (const var::identifier& name) const throw();
  9797. /** Changes a named property of the node.
  9798. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9799. so that this change can be undone.
  9800. @see var, getProperty, removeProperty
  9801. */
  9802. void setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager) throw();
  9803. /** Returns true if the node contains a named property. */
  9804. bool hasProperty (const var::identifier& name) const throw();
  9805. /** Removes a property from the node.
  9806. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9807. so that this change can be undone.
  9808. */
  9809. void removeProperty (const var::identifier& name, UndoManager* const undoManager) throw();
  9810. /** Removes all properties from the node.
  9811. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9812. so that this change can be undone.
  9813. */
  9814. void removeAllProperties (UndoManager* const undoManager) throw();
  9815. /** Returns the total number of properties that the node contains.
  9816. @see getProperty.
  9817. */
  9818. int getNumProperties() const throw();
  9819. /** Returns the identifier of the property with a given index.
  9820. @see getNumProperties
  9821. */
  9822. const var::identifier getPropertyName (int index) const throw();
  9823. /** Returns the number of child nodes belonging to this one.
  9824. @see getChild
  9825. */
  9826. int getNumChildren() const throw();
  9827. /** Returns one of this node's child nodes.
  9828. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  9829. whether a node is valid).
  9830. */
  9831. ValueTree getChild (int index) const throw();
  9832. /** Looks for a child node with the speficied type name.
  9833. If no such node is found, it'll return an invalid node. (See isValid() to find out
  9834. whether a node is valid).
  9835. */
  9836. ValueTree getChildWithName (const String& type) const throw();
  9837. /** Looks for the first child node that has the speficied property value.
  9838. This will scan the child nodes in order, until it finds one that has property that matches
  9839. the specified value.
  9840. If no such node is found, it'll return an invalid node. (See isValid() to find out
  9841. whether a node is valid).
  9842. */
  9843. ValueTree getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const throw();
  9844. /** Adds a child to this node.
  9845. Make sure that the child is removed from any former parent node before calling this, or
  9846. you'll hit an assertion.
  9847. If the index is < 0 or greater than the current number of child nodes, the new node will
  9848. be added at the end of the list.
  9849. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9850. so that this change can be undone.
  9851. */
  9852. void addChild (ValueTree child, int index, UndoManager* const undoManager) throw();
  9853. /** Removes the specified child from this node's child-list.
  9854. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9855. so that this change can be undone.
  9856. */
  9857. void removeChild (ValueTree& child, UndoManager* const undoManager) throw();
  9858. /** Removes a child from this node's child-list.
  9859. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9860. so that this change can be undone.
  9861. */
  9862. void removeChild (const int childIndex, UndoManager* const undoManager) throw();
  9863. /** Removes all child-nodes from this node.
  9864. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9865. so that this change can be undone.
  9866. */
  9867. void removeAllChildren (UndoManager* const undoManager) throw();
  9868. /** Returns true if this node is anywhere below the specified parent node.
  9869. This returns true if the node is a child-of-a-child, as well as a direct child.
  9870. */
  9871. bool isAChildOf (const ValueTree& possibleParent) const throw();
  9872. /** Returns the parent node that contains this one.
  9873. If the node has no parent, this will return an invalid node. (See isValid() to find out
  9874. whether a node is valid).
  9875. */
  9876. ValueTree getParent() const throw();
  9877. /** Creates an XmlElement that holds a complete image of this node and all its children.
  9878. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  9879. be used to recreate a similar node by calling fromXml()
  9880. @see fromXml
  9881. */
  9882. XmlElement* createXml() const throw();
  9883. /** Tries to recreate a node from its XML representation.
  9884. This isn't designed to cope with random XML data - for a sensible result, it should only
  9885. be fed XML that was created by the createXml() method.
  9886. */
  9887. static ValueTree fromXml (const XmlElement& xml) throw();
  9888. /** Stores this tree (and all its children) in a binary format.
  9889. Once written, the data can be read back with readFromStream().
  9890. It's much faster to load/save your tree in binary form than as XML, but
  9891. obviously isn't human-readable.
  9892. */
  9893. void writeToStream (OutputStream& output) throw();
  9894. /** Reloads a tree from a stream that was written with writeToStream().
  9895. */
  9896. static ValueTree readFromStream (InputStream& input) throw();
  9897. /** Listener class for events that happen to a ValueTree.
  9898. To get events from a ValueTree, make your class implement this interface, and use
  9899. ValueTree::addListener() and ValueTree::removeListener() to register it.
  9900. */
  9901. class JUCE_API Listener
  9902. {
  9903. public:
  9904. /** Destructor. */
  9905. virtual ~Listener() {}
  9906. /** This method is called when one or more of the properties of this node have changed. */
  9907. virtual void valueTreePropertyChanged (ValueTree& tree) = 0;
  9908. /** This method is called when one or more of the children of this node have been added or removed. */
  9909. virtual void valueTreeChildrenChanged (ValueTree& tree) = 0;
  9910. /** This method is called when this node has been added or removed from a parent node. */
  9911. virtual void valueTreeParentChanged() = 0;
  9912. };
  9913. /** Adds a listener to receive callbacks when this node is changed. */
  9914. void addListener (Listener* listener) throw();
  9915. /** Removes a listener that was previously added with addListener(). */
  9916. void removeListener (Listener* listener) throw();
  9917. juce_UseDebuggingNewOperator
  9918. private:
  9919. friend class ValueTreeSetPropertyAction;
  9920. friend class ValueTreeChildChangeAction;
  9921. class SharedObject : public ReferenceCountedObject
  9922. {
  9923. public:
  9924. SharedObject (const String& type) throw();
  9925. SharedObject (const SharedObject& other) throw();
  9926. ~SharedObject() throw();
  9927. struct Property
  9928. {
  9929. Property (const var::identifier& name, const var& value) throw();
  9930. var::identifier name;
  9931. var value;
  9932. };
  9933. const String type;
  9934. OwnedArray <Property> properties;
  9935. ReferenceCountedArray <SharedObject> children;
  9936. SortedSet <Listener*> listeners;
  9937. SharedObject* parent;
  9938. void sendPropertyChangeMessage();
  9939. void sendChildChangeMessage();
  9940. void sendParentChangeMessage();
  9941. const var getProperty (const var::identifier& name) const throw();
  9942. void setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager) throw();
  9943. bool hasProperty (const var::identifier& name) const throw();
  9944. void removeProperty (const var::identifier& name, UndoManager* const undoManager) throw();
  9945. void removeAllProperties (UndoManager* const undoManager) throw();
  9946. bool isAChildOf (const SharedObject* const possibleParent) const throw();
  9947. ValueTree getChildWithName (const String& type) const throw();
  9948. ValueTree getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const throw();
  9949. void addChild (SharedObject* child, int index, UndoManager* const undoManager) throw();
  9950. void removeChild (const int childIndex, UndoManager* const undoManager) throw();
  9951. void removeAllChildren (UndoManager* const undoManager) throw();
  9952. XmlElement* createXml() const throw();
  9953. };
  9954. friend class SharedObject;
  9955. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  9956. ReferenceCountedObjectPtr <SharedObject> object;
  9957. ValueTree (SharedObject* const object_) throw();
  9958. };
  9959. #endif // __JUCE_VALUETREE_JUCEHEADER__
  9960. /********* End of inlined file: juce_ValueTree.h *********/
  9961. #endif
  9962. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9963. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  9964. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9965. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9966. /**
  9967. Searches through a the files in a directory, returning each file that is found.
  9968. A DirectoryIterator will search through a directory and its subdirectories using
  9969. a wildcard filepattern match.
  9970. If you may be finding a large number of files, this is better than
  9971. using File::findChildFiles() because it doesn't block while it finds them
  9972. all, and this is more memory-efficient.
  9973. It can also guess how far it's got using a wildly inaccurate algorithm.
  9974. */
  9975. class JUCE_API DirectoryIterator
  9976. {
  9977. public:
  9978. /** Creates a DirectoryIterator for a given directory.
  9979. After creating one of these, call its next() method to get the
  9980. first file - e.g. @code
  9981. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  9982. while (iter.next())
  9983. {
  9984. File theFileItFound (iter.getFile());
  9985. ... etc
  9986. }
  9987. @endcode
  9988. @param directory the directory to search in
  9989. @param isRecursive whether all the subdirectories should also be searched
  9990. @param wildCard the file pattern to match
  9991. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  9992. whether to look for files, directories, or both.
  9993. */
  9994. DirectoryIterator (const File& directory,
  9995. bool isRecursive,
  9996. const String& wildCard = JUCE_T("*"),
  9997. const int whatToLookFor = File::findFiles) throw();
  9998. /** Destructor. */
  9999. ~DirectoryIterator() throw();
  10000. /** Call this to move the iterator along to the next file.
  10001. @returns true if a file was found (you can then use getFile() to see what it was) - or
  10002. false if there are no more matching files.
  10003. */
  10004. bool next() throw();
  10005. /** Returns the file that the iterator is currently pointing at.
  10006. The result of this call is only valid after a call to next() has returned true.
  10007. */
  10008. const File getFile() const throw();
  10009. /** Returns a guess of how far through the search the iterator has got.
  10010. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  10011. very accurate.
  10012. */
  10013. float getEstimatedProgress() const throw();
  10014. juce_UseDebuggingNewOperator
  10015. private:
  10016. OwnedArray <File> filesFound;
  10017. OwnedArray <File> dirsFound;
  10018. String wildCard;
  10019. int index;
  10020. const int whatToLookFor;
  10021. DirectoryIterator* subIterator;
  10022. DirectoryIterator (const DirectoryIterator&);
  10023. const DirectoryIterator& operator= (const DirectoryIterator&);
  10024. };
  10025. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10026. /********* End of inlined file: juce_DirectoryIterator.h *********/
  10027. #endif
  10028. #ifndef __JUCE_FILE_JUCEHEADER__
  10029. #endif
  10030. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10031. /********* Start of inlined file: juce_FileInputStream.h *********/
  10032. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10033. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10034. /**
  10035. An input stream that reads from a local file.
  10036. @see InputStream, FileOutputStream, File::createInputStream
  10037. */
  10038. class JUCE_API FileInputStream : public InputStream
  10039. {
  10040. public:
  10041. /** Creates a FileInputStream.
  10042. @param fileToRead the file to read from - if the file can't be accessed for some
  10043. reason, then the stream will just contain no data
  10044. */
  10045. FileInputStream (const File& fileToRead);
  10046. /** Destructor. */
  10047. ~FileInputStream();
  10048. const File& getFile() const throw() { return file; }
  10049. int64 getTotalLength();
  10050. int read (void* destBuffer, int maxBytesToRead);
  10051. bool isExhausted();
  10052. int64 getPosition();
  10053. bool setPosition (int64 pos);
  10054. juce_UseDebuggingNewOperator
  10055. private:
  10056. File file;
  10057. void* fileHandle;
  10058. int64 currentPosition, totalSize;
  10059. bool needToSeek;
  10060. FileInputStream (const FileInputStream&);
  10061. const FileInputStream& operator= (const FileInputStream&);
  10062. };
  10063. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10064. /********* End of inlined file: juce_FileInputStream.h *********/
  10065. #endif
  10066. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10067. /********* Start of inlined file: juce_FileOutputStream.h *********/
  10068. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10069. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10070. /**
  10071. An output stream that writes into a local file.
  10072. @see OutputStream, FileInputStream, File::createOutputStream
  10073. */
  10074. class JUCE_API FileOutputStream : public OutputStream
  10075. {
  10076. public:
  10077. /** Creates a FileOutputStream.
  10078. If the file doesn't exist, it will first be created. If the file can't be
  10079. created or opened, the failedToOpen() method will return
  10080. true.
  10081. If the file already exists when opened, the stream's write-postion will
  10082. be set to the end of the file. To overwrite an existing file,
  10083. use File::deleteFile() before opening the stream, or use setPosition(0)
  10084. after it's opened (although this won't truncate the file).
  10085. It's better to use File::createOutputStream() to create one of these, rather
  10086. than using the class directly.
  10087. */
  10088. FileOutputStream (const File& fileToWriteTo,
  10089. const int bufferSizeToUse = 16384);
  10090. /** Destructor. */
  10091. ~FileOutputStream();
  10092. /** Returns the file that this stream is writing to.
  10093. */
  10094. const File& getFile() const throw() { return file; }
  10095. /** Returns true if the stream couldn't be opened for some reason.
  10096. */
  10097. bool failedToOpen() const throw() { return fileHandle == 0; }
  10098. void flush();
  10099. int64 getPosition();
  10100. bool setPosition (int64 pos);
  10101. bool write (const void* data, int numBytes);
  10102. juce_UseDebuggingNewOperator
  10103. private:
  10104. File file;
  10105. void* fileHandle;
  10106. int64 currentPosition;
  10107. int bufferSize, bytesInBuffer;
  10108. char* buffer;
  10109. };
  10110. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10111. /********* End of inlined file: juce_FileOutputStream.h *********/
  10112. #endif
  10113. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  10114. /********* Start of inlined file: juce_FileSearchPath.h *********/
  10115. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  10116. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  10117. /**
  10118. Encapsulates a set of folders that make up a search path.
  10119. @see File
  10120. */
  10121. class JUCE_API FileSearchPath
  10122. {
  10123. public:
  10124. /** Creates an empty search path. */
  10125. FileSearchPath();
  10126. /** Creates a search path from a string of pathnames.
  10127. The path can be semicolon- or comma-separated, e.g.
  10128. "/foo/bar;/foo/moose;/fish/moose"
  10129. The separate folders are tokenised and added to the search path.
  10130. */
  10131. FileSearchPath (const String& path);
  10132. /** Creates a copy of another search path. */
  10133. FileSearchPath (const FileSearchPath& other);
  10134. /** Destructor. */
  10135. ~FileSearchPath();
  10136. /** Uses a string containing a list of pathnames to re-initialise this list.
  10137. This search path is cleared and the semicolon- or comma-separated folders
  10138. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  10139. */
  10140. const FileSearchPath& operator= (const String& path);
  10141. /** Returns the number of folders in this search path.
  10142. @see operator[]
  10143. */
  10144. int getNumPaths() const;
  10145. /** Returns one of the folders in this search path.
  10146. The file returned isn't guaranteed to actually be a valid directory.
  10147. @see getNumPaths
  10148. */
  10149. const File operator[] (const int index) const;
  10150. /** Returns the search path as a semicolon-separated list of directories. */
  10151. const String toString() const;
  10152. /** Adds a new directory to the search path.
  10153. The new directory is added to the end of the list if the insertIndex parameter is
  10154. less than zero, otherwise it is inserted at the given index.
  10155. */
  10156. void add (const File& directoryToAdd,
  10157. const int insertIndex = -1);
  10158. /** Adds a new directory to the search path if it's not already in there. */
  10159. void addIfNotAlreadyThere (const File& directoryToAdd);
  10160. /** Removes a directory from the search path. */
  10161. void remove (const int indexToRemove);
  10162. /** Merges another search path into this one.
  10163. This will remove any duplicate directories.
  10164. */
  10165. void addPath (const FileSearchPath& other);
  10166. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  10167. If the search is intended to be recursive, there's no point having nested folders in the search
  10168. path, because they'll just get searched twice and you'll get duplicate results.
  10169. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  10170. */
  10171. void removeRedundantPaths();
  10172. /** Removes any directories that don't actually exist. */
  10173. void removeNonExistentPaths();
  10174. /** Searches the path for a wildcard.
  10175. This will search all the directories in the search path in order, adding any
  10176. matching files to the results array.
  10177. @param results an array to append the results to
  10178. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  10179. return files, directories, or both.
  10180. @param searchRecursively whether to recursively search the subdirectories too
  10181. @param wildCardPattern a pattern to match against the filenames
  10182. @returns the number of files added to the array
  10183. @see File::findChildFiles
  10184. */
  10185. int findChildFiles (OwnedArray<File>& results,
  10186. const int whatToLookFor,
  10187. const bool searchRecursively,
  10188. const String& wildCardPattern = JUCE_T("*")) const;
  10189. /** Finds out whether a file is inside one of the path's directories.
  10190. This will return true if the specified file is a child of one of the
  10191. directories specified by this path. Note that this doesn't actually do any
  10192. searching or check that the files exist - it just looks at the pathnames
  10193. to work out whether the file would be inside a directory.
  10194. @param fileToCheck the file to look for
  10195. @param checkRecursively if true, then this will return true if the file is inside a
  10196. subfolder of one of the path's directories (at any depth). If false
  10197. it will only return true if the file is actually a direct child
  10198. of one of the directories.
  10199. @see File::isAChildOf
  10200. */
  10201. bool isFileInPath (const File& fileToCheck,
  10202. const bool checkRecursively) const;
  10203. juce_UseDebuggingNewOperator
  10204. private:
  10205. StringArray directories;
  10206. void init (const String& path);
  10207. };
  10208. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  10209. /********* End of inlined file: juce_FileSearchPath.h *********/
  10210. #endif
  10211. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  10212. /********* Start of inlined file: juce_NamedPipe.h *********/
  10213. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  10214. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  10215. /**
  10216. A cross-process pipe that can have data written to and read from it.
  10217. Two or more processes can use these for inter-process communication.
  10218. @see InterprocessConnection
  10219. */
  10220. class JUCE_API NamedPipe
  10221. {
  10222. public:
  10223. /** Creates a NamedPipe. */
  10224. NamedPipe();
  10225. /** Destructor. */
  10226. ~NamedPipe();
  10227. /** Tries to open a pipe that already exists.
  10228. Returns true if it succeeds.
  10229. */
  10230. bool openExisting (const String& pipeName);
  10231. /** Tries to create a new pipe.
  10232. Returns true if it succeeds.
  10233. */
  10234. bool createNewPipe (const String& pipeName);
  10235. /** Closes the pipe, if it's open. */
  10236. void close();
  10237. /** True if the pipe is currently open. */
  10238. bool isOpen() const throw();
  10239. /** Returns the last name that was used to try to open this pipe. */
  10240. const String getName() const throw();
  10241. /** Reads data from the pipe.
  10242. This will block until another thread has written enough data into the pipe to fill
  10243. the number of bytes specified, or until another thread calls the cancelPendingReads()
  10244. method.
  10245. If the operation fails, it returns -1, otherwise, it will return the number of
  10246. bytes read.
  10247. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  10248. this is a maximum timeout for reading from the pipe.
  10249. */
  10250. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  10251. /** Writes some data to the pipe.
  10252. If the operation fails, it returns -1, otherwise, it will return the number of
  10253. bytes written.
  10254. */
  10255. int write (const void* sourceBuffer, int numBytesToWrite,
  10256. int timeOutMilliseconds = 2000);
  10257. /** If any threads are currently blocked on a read operation, this tells them to abort.
  10258. */
  10259. void cancelPendingReads();
  10260. juce_UseDebuggingNewOperator
  10261. private:
  10262. void* internal;
  10263. String currentPipeName;
  10264. NamedPipe (const NamedPipe&);
  10265. const NamedPipe& operator= (const NamedPipe&);
  10266. bool openInternal (const String& pipeName, const bool createPipe);
  10267. };
  10268. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  10269. /********* End of inlined file: juce_NamedPipe.h *********/
  10270. #endif
  10271. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10272. /********* Start of inlined file: juce_ZipFile.h *********/
  10273. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10274. #define __JUCE_ZIPFILE_JUCEHEADER__
  10275. /********* Start of inlined file: juce_InputSource.h *********/
  10276. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  10277. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  10278. /**
  10279. A lightweight object that can create a stream to read some kind of resource.
  10280. This may be used to refer to a file, or some other kind of source, allowing a
  10281. caller to create an input stream that can read from it when required.
  10282. @see FileInputSource
  10283. */
  10284. class JUCE_API InputSource
  10285. {
  10286. public:
  10287. InputSource() throw() {}
  10288. /** Destructor. */
  10289. virtual ~InputSource() {}
  10290. /** Returns a new InputStream to read this item.
  10291. @returns an inputstream that the caller will delete, or 0 if
  10292. the filename isn't found.
  10293. */
  10294. virtual InputStream* createInputStream() = 0;
  10295. /** Returns a new InputStream to read an item, relative.
  10296. @param relatedItemPath the relative pathname of the resource that is required
  10297. @returns an inputstream that the caller will delete, or 0 if
  10298. the item isn't found.
  10299. */
  10300. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  10301. /** Returns a hash code that uniquely represents this item.
  10302. */
  10303. virtual int64 hashCode() const = 0;
  10304. juce_UseDebuggingNewOperator
  10305. };
  10306. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  10307. /********* End of inlined file: juce_InputSource.h *********/
  10308. /**
  10309. Decodes a ZIP file from a stream.
  10310. This can enumerate the items in a ZIP file and can create suitable stream objects
  10311. to read each one.
  10312. */
  10313. class JUCE_API ZipFile
  10314. {
  10315. public:
  10316. /** Creates a ZipFile for a given stream.
  10317. @param inputStream the stream to read from
  10318. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10319. will be deleted when this ZipFile object is deleted
  10320. */
  10321. ZipFile (InputStream* const inputStream,
  10322. const bool deleteStreamWhenDestroyed) throw();
  10323. /** Creates a ZipFile based for a file. */
  10324. ZipFile (const File& file);
  10325. /** Creates a ZipFile for an input source.
  10326. The inputSource object will be owned by the zip file, which will delete
  10327. it later when not needed.
  10328. */
  10329. ZipFile (InputSource* const inputSource);
  10330. /** Destructor. */
  10331. ~ZipFile() throw();
  10332. /**
  10333. Contains information about one of the entries in a ZipFile.
  10334. @see ZipFile::getEntry
  10335. */
  10336. struct ZipEntry
  10337. {
  10338. /** The name of the file, which may also include a partial pathname. */
  10339. String filename;
  10340. /** The file's original size. */
  10341. unsigned int uncompressedSize;
  10342. /** The last time the file was modified. */
  10343. Time fileTime;
  10344. };
  10345. /** Returns the number of items in the zip file. */
  10346. int getNumEntries() const throw();
  10347. /** Returns a structure that describes one of the entries in the zip file.
  10348. This may return zero if the index is out of range.
  10349. @see ZipFile::ZipEntry
  10350. */
  10351. const ZipEntry* getEntry (const int index) const throw();
  10352. /** Returns the index of the first entry with a given filename.
  10353. This uses a case-sensitive comparison to look for a filename in the
  10354. list of entries. It might return -1 if no match is found.
  10355. @see ZipFile::ZipEntry
  10356. */
  10357. int getIndexOfFileName (const String& fileName) const throw();
  10358. /** Returns a structure that describes one of the entries in the zip file.
  10359. This uses a case-sensitive comparison to look for a filename in the
  10360. list of entries. It might return 0 if no match is found.
  10361. @see ZipFile::ZipEntry
  10362. */
  10363. const ZipEntry* getEntry (const String& fileName) const throw();
  10364. /** Sorts the list of entries, based on the filename.
  10365. */
  10366. void sortEntriesByFilename();
  10367. /** Creates a stream that can read from one of the zip file's entries.
  10368. The stream that is returned must be deleted by the caller (and
  10369. zero might be returned if a stream can't be opened for some reason).
  10370. The stream must not be used after the ZipFile object that created
  10371. has been deleted.
  10372. */
  10373. InputStream* createStreamForEntry (const int index);
  10374. /** Uncompresses all of the files in the zip file.
  10375. This will expand all the entires into a target directory. The relative
  10376. paths of the entries are used.
  10377. @param targetDirectory the root folder to uncompress to
  10378. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10379. */
  10380. void uncompressTo (const File& targetDirectory,
  10381. const bool shouldOverwriteFiles = true);
  10382. juce_UseDebuggingNewOperator
  10383. private:
  10384. VoidArray entries;
  10385. friend class ZipInputStream;
  10386. CriticalSection lock;
  10387. InputStream* inputStream;
  10388. InputSource* inputSource;
  10389. bool deleteStreamWhenDestroyed;
  10390. int numEntries, centralRecStart;
  10391. #ifdef JUCE_DEBUG
  10392. int numOpenStreams;
  10393. #endif
  10394. void init();
  10395. int findEndOfZipEntryTable (InputStream* in);
  10396. ZipFile (const ZipFile&);
  10397. const ZipFile& operator= (const ZipFile&);
  10398. };
  10399. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10400. /********* End of inlined file: juce_ZipFile.h *********/
  10401. #endif
  10402. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  10403. /********* Start of inlined file: juce_BlowFish.h *********/
  10404. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  10405. #define __JUCE_BLOWFISH_JUCEHEADER__
  10406. /**
  10407. BlowFish encryption class.
  10408. */
  10409. class JUCE_API BlowFish
  10410. {
  10411. public:
  10412. /** Creates an object that can encode/decode based on the specified key.
  10413. The key data can be up to 72 bytes long.
  10414. */
  10415. BlowFish (const uint8* keyData, int keyBytes);
  10416. /** Creates a copy of another blowfish object. */
  10417. BlowFish (const BlowFish& other);
  10418. /** Copies another blowfish object. */
  10419. const BlowFish& operator= (const BlowFish& other);
  10420. /** Destructor. */
  10421. ~BlowFish();
  10422. /** Encrypts a pair of 32-bit integers. */
  10423. void encrypt (uint32& data1, uint32& data2) const;
  10424. /** Decrypts a pair of 32-bit integers. */
  10425. void decrypt (uint32& data1, uint32& data2) const;
  10426. juce_UseDebuggingNewOperator
  10427. private:
  10428. uint32 p[18];
  10429. uint32* s[4];
  10430. uint32 F (uint32 x) const;
  10431. };
  10432. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  10433. /********* End of inlined file: juce_BlowFish.h *********/
  10434. #endif
  10435. #ifndef __JUCE_MD5_JUCEHEADER__
  10436. /********* Start of inlined file: juce_MD5.h *********/
  10437. #ifndef __JUCE_MD5_JUCEHEADER__
  10438. #define __JUCE_MD5_JUCEHEADER__
  10439. /**
  10440. MD5 checksum class.
  10441. Create one of these with a block of source data or a string, and it calculates the
  10442. MD5 checksum of that data.
  10443. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  10444. */
  10445. class JUCE_API MD5
  10446. {
  10447. public:
  10448. /** Creates a null MD5 object. */
  10449. MD5();
  10450. /** Creates a copy of another MD5. */
  10451. MD5 (const MD5& other);
  10452. /** Copies another MD5. */
  10453. const MD5& operator= (const MD5& other);
  10454. /** Creates a checksum for a block of binary data. */
  10455. MD5 (const MemoryBlock& data);
  10456. /** Creates a checksum for a block of binary data. */
  10457. MD5 (const char* data, const int numBytes);
  10458. /** Creates a checksum for a string.
  10459. Note that this operates on the string as a block of unicode characters, so the
  10460. result you get will differ from the value you'd get if the string was treated
  10461. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  10462. of this method with a checksum created by a different framework, which may have
  10463. used a different encoding.
  10464. */
  10465. MD5 (const String& text);
  10466. /** Creates a checksum for the input from a stream.
  10467. This will read up to the given number of bytes from the stream, and produce the
  10468. checksum of that. If the number of bytes to read is negative, it'll read
  10469. until the stream is exhausted.
  10470. */
  10471. MD5 (InputStream& input, int numBytesToRead = -1);
  10472. /** Creates a checksum for a file. */
  10473. MD5 (const File& file);
  10474. /** Destructor. */
  10475. ~MD5();
  10476. /** Returns the checksum as a 16-byte block of data. */
  10477. const MemoryBlock getRawChecksumData() const;
  10478. /** Returns the checksum as a 32-digit hex string. */
  10479. const String toHexString() const;
  10480. /** Compares this to another MD5. */
  10481. bool operator== (const MD5& other) const;
  10482. /** Compares this to another MD5. */
  10483. bool operator!= (const MD5& other) const;
  10484. juce_UseDebuggingNewOperator
  10485. private:
  10486. uint8 result [16];
  10487. struct ProcessContext
  10488. {
  10489. uint8 buffer [64];
  10490. uint32 state [4];
  10491. uint32 count [2];
  10492. ProcessContext();
  10493. void processBlock (const uint8* const data, int dataSize);
  10494. void transform (const uint8* const buffer);
  10495. void finish (uint8* const result);
  10496. };
  10497. void processStream (InputStream& input, int numBytesToRead);
  10498. };
  10499. #endif // __JUCE_MD5_JUCEHEADER__
  10500. /********* End of inlined file: juce_MD5.h *********/
  10501. #endif
  10502. #ifndef __JUCE_PRIMES_JUCEHEADER__
  10503. /********* Start of inlined file: juce_Primes.h *********/
  10504. #ifndef __JUCE_PRIMES_JUCEHEADER__
  10505. #define __JUCE_PRIMES_JUCEHEADER__
  10506. /**
  10507. Prime number creation class.
  10508. This class contains static methods for generating and testing prime numbers.
  10509. @see BitArray
  10510. */
  10511. class JUCE_API Primes
  10512. {
  10513. public:
  10514. /** Creates a random prime number with a given bit-length.
  10515. The certainty parameter specifies how many iterations to use when testing
  10516. for primality. A safe value might be anything over about 20-30.
  10517. The randomSeeds parameter lets you optionally pass it a set of values with
  10518. which to seed the random number generation, improving the security of the
  10519. keys generated.
  10520. */
  10521. static const BitArray createProbablePrime (int bitLength,
  10522. int certainty,
  10523. const int* randomSeeds = 0,
  10524. int numRandomSeeds = 0) throw();
  10525. /** Tests a number to see if it's prime.
  10526. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  10527. whether the number is prime.
  10528. The certainty parameter specifies how many iterations to use when testing - a
  10529. safe value might be anything over about 20-30.
  10530. */
  10531. static bool isProbablyPrime (const BitArray& number,
  10532. int certainty) throw();
  10533. };
  10534. #endif // __JUCE_PRIMES_JUCEHEADER__
  10535. /********* End of inlined file: juce_Primes.h *********/
  10536. #endif
  10537. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  10538. /********* Start of inlined file: juce_RSAKey.h *********/
  10539. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  10540. #define __JUCE_RSAKEY_JUCEHEADER__
  10541. /**
  10542. RSA public/private key-pair encryption class.
  10543. An object of this type makes up one half of a public/private RSA key pair. Use the
  10544. createKeyPair() method to create a matching pair for encoding/decoding.
  10545. */
  10546. class JUCE_API RSAKey
  10547. {
  10548. public:
  10549. /** Creates a null key object.
  10550. Initialise a pair of objects for use with the createKeyPair() method.
  10551. */
  10552. RSAKey() throw();
  10553. /** Loads a key from an encoded string representation.
  10554. This reloads a key from a string created by the toString() method.
  10555. */
  10556. RSAKey (const String& stringRepresentation) throw();
  10557. /** Destructor. */
  10558. ~RSAKey() throw();
  10559. /** Turns the key into a string representation.
  10560. This can be reloaded using the constructor that takes a string.
  10561. */
  10562. const String toString() const throw();
  10563. /** Encodes or decodes a value.
  10564. Call this on the public key object to encode some data, then use the matching
  10565. private key object to decode it.
  10566. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  10567. initialised correctly.
  10568. NOTE: This method dumbly applies this key to this data. If you encode some data
  10569. and then try to decode it with a key that doesn't match, this method will still
  10570. happily do its job and return true, but the result won't be what you were expecting.
  10571. It's your responsibility to check that the result is what you wanted.
  10572. */
  10573. bool applyToValue (BitArray& value) const throw();
  10574. /** Creates a public/private key-pair.
  10575. Each key will perform one-way encryption that can only be reversed by
  10576. using the other key.
  10577. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  10578. sizes are more secure, but this method will take longer to execute.
  10579. The randomSeeds parameter lets you optionally pass it a set of values with
  10580. which to seed the random number generation, improving the security of the
  10581. keys generated.
  10582. */
  10583. static void createKeyPair (RSAKey& publicKey,
  10584. RSAKey& privateKey,
  10585. const int numBits,
  10586. const int* randomSeeds = 0,
  10587. const int numRandomSeeds = 0) throw();
  10588. juce_UseDebuggingNewOperator
  10589. protected:
  10590. BitArray part1, part2;
  10591. };
  10592. #endif // __JUCE_RSAKEY_JUCEHEADER__
  10593. /********* End of inlined file: juce_RSAKey.h *********/
  10594. #endif
  10595. #ifndef __JUCE_SOCKET_JUCEHEADER__
  10596. /********* Start of inlined file: juce_Socket.h *********/
  10597. #ifndef __JUCE_SOCKET_JUCEHEADER__
  10598. #define __JUCE_SOCKET_JUCEHEADER__
  10599. /**
  10600. A wrapper for a streaming (TCP) socket.
  10601. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  10602. sockets, you could also try the InterprocessConnection class.
  10603. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  10604. */
  10605. class JUCE_API StreamingSocket
  10606. {
  10607. public:
  10608. /** Creates an uninitialised socket.
  10609. To connect it, use the connect() method, after which you can read() or write()
  10610. to it.
  10611. To wait for other sockets to connect to this one, the createListener() method
  10612. enters "listener" mode, and can be used to spawn new sockets for each connection
  10613. that comes along.
  10614. */
  10615. StreamingSocket();
  10616. /** Destructor. */
  10617. ~StreamingSocket();
  10618. /** Binds the socket to the specified local port.
  10619. @returns true on success; false may indicate that another socket is already bound
  10620. on the same port
  10621. */
  10622. bool bindToPort (const int localPortNumber);
  10623. /** Tries to connect the socket to hostname:port.
  10624. If timeOutMillisecs is 0, then this method will block until the operating system
  10625. rejects the connection (which could take a long time).
  10626. @returns true if it succeeds.
  10627. @see isConnected
  10628. */
  10629. bool connect (const String& remoteHostname,
  10630. const int remotePortNumber,
  10631. const int timeOutMillisecs = 3000);
  10632. /** True if the socket is currently connected. */
  10633. bool isConnected() const throw() { return connected; }
  10634. /** Closes the connection. */
  10635. void close();
  10636. /** Returns the name of the currently connected host. */
  10637. const String& getHostName() const throw() { return hostName; }
  10638. /** Returns the port number that's currently open. */
  10639. int getPort() const throw() { return portNumber; }
  10640. /** True if the socket is connected to this machine rather than over the network. */
  10641. bool isLocal() const throw();
  10642. /** Waits until the socket is ready for reading or writing.
  10643. If readyForReading is true, it will wait until the socket is ready for
  10644. reading; if false, it will wait until it's ready for writing.
  10645. If the timeout is < 0, it will wait forever, or else will give up after
  10646. the specified time.
  10647. If the socket is ready on return, this returns 1. If it times-out before
  10648. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  10649. */
  10650. int waitUntilReady (const bool readyForReading,
  10651. const int timeoutMsecs) const;
  10652. /** Reads bytes from the socket.
  10653. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  10654. maxBytesToRead bytes have been read, (or until an error occurs). If this
  10655. flag is false, the method will return as much data as is currently available
  10656. without blocking.
  10657. @returns the number of bytes read, or -1 if there was an error.
  10658. @see waitUntilReady
  10659. */
  10660. int read (void* destBuffer, const int maxBytesToRead,
  10661. const bool blockUntilSpecifiedAmountHasArrived);
  10662. /** Writes bytes to the socket from a buffer.
  10663. Note that this method will block unless you have checked the socket is ready
  10664. for writing before calling it (see the waitUntilReady() method).
  10665. @returns the number of bytes written, or -1 if there was an error.
  10666. */
  10667. int write (const void* sourceBuffer, const int numBytesToWrite);
  10668. /** Puts this socket into "listener" mode.
  10669. When in this mode, your thread can call waitForNextConnection() repeatedly,
  10670. which will spawn new sockets for each new connection, so that these can
  10671. be handled in parallel by other threads.
  10672. @param portNumber the port number to listen on
  10673. @param localHostName the interface address to listen on - pass an empty
  10674. string to listen on all addresses
  10675. @returns true if it manages to open the socket successfully.
  10676. @see waitForNextConnection
  10677. */
  10678. bool createListener (const int portNumber, const String& localHostName = String::empty);
  10679. /** When in "listener" mode, this waits for a connection and spawns it as a new
  10680. socket.
  10681. The object that gets returned will be owned by the caller.
  10682. This method can only be called after using createListener().
  10683. @see createListener
  10684. */
  10685. StreamingSocket* waitForNextConnection() const;
  10686. juce_UseDebuggingNewOperator
  10687. private:
  10688. String hostName;
  10689. int volatile portNumber, handle;
  10690. bool connected, isListener;
  10691. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  10692. StreamingSocket (const StreamingSocket&);
  10693. const StreamingSocket& operator= (const StreamingSocket&);
  10694. };
  10695. /**
  10696. A wrapper for a datagram (UDP) socket.
  10697. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  10698. sockets, you could also try the InterprocessConnection class.
  10699. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  10700. */
  10701. class JUCE_API DatagramSocket
  10702. {
  10703. public:
  10704. /**
  10705. Creates an (uninitialised) datagram socket.
  10706. The localPortNumber is the port on which to bind this socket. If this value is 0,
  10707. the port number is assigned by the operating system.
  10708. To use the socket for sending, call the connect() method. This will not immediately
  10709. make a connection, but will save the destination you've provided. After this, you can
  10710. call read() or write().
  10711. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  10712. (may require extra privileges on linux)
  10713. To wait for other sockets to connect to this one, call waitForNextConnection().
  10714. */
  10715. DatagramSocket (const int localPortNumber,
  10716. const bool enableBroadcasting = false);
  10717. /** Destructor. */
  10718. ~DatagramSocket();
  10719. /** Binds the socket to the specified local port.
  10720. @returns true on success; false may indicate that another socket is already bound
  10721. on the same port
  10722. */
  10723. bool bindToPort (const int localPortNumber);
  10724. /** Tries to connect the socket to hostname:port.
  10725. If timeOutMillisecs is 0, then this method will block until the operating system
  10726. rejects the connection (which could take a long time).
  10727. @returns true if it succeeds.
  10728. @see isConnected
  10729. */
  10730. bool connect (const String& remoteHostname,
  10731. const int remotePortNumber,
  10732. const int timeOutMillisecs = 3000);
  10733. /** True if the socket is currently connected. */
  10734. bool isConnected() const throw() { return connected; }
  10735. /** Closes the connection. */
  10736. void close();
  10737. /** Returns the name of the currently connected host. */
  10738. const String& getHostName() const throw() { return hostName; }
  10739. /** Returns the port number that's currently open. */
  10740. int getPort() const throw() { return portNumber; }
  10741. /** True if the socket is connected to this machine rather than over the network. */
  10742. bool isLocal() const throw();
  10743. /** Waits until the socket is ready for reading or writing.
  10744. If readyForReading is true, it will wait until the socket is ready for
  10745. reading; if false, it will wait until it's ready for writing.
  10746. If the timeout is < 0, it will wait forever, or else will give up after
  10747. the specified time.
  10748. If the socket is ready on return, this returns 1. If it times-out before
  10749. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  10750. */
  10751. int waitUntilReady (const bool readyForReading,
  10752. const int timeoutMsecs) const;
  10753. /** Reads bytes from the socket.
  10754. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  10755. maxBytesToRead bytes have been read, (or until an error occurs). If this
  10756. flag is false, the method will return as much data as is currently available
  10757. without blocking.
  10758. @returns the number of bytes read, or -1 if there was an error.
  10759. @see waitUntilReady
  10760. */
  10761. int read (void* destBuffer, const int maxBytesToRead,
  10762. const bool blockUntilSpecifiedAmountHasArrived);
  10763. /** Writes bytes to the socket from a buffer.
  10764. Note that this method will block unless you have checked the socket is ready
  10765. for writing before calling it (see the waitUntilReady() method).
  10766. @returns the number of bytes written, or -1 if there was an error.
  10767. */
  10768. int write (const void* sourceBuffer, const int numBytesToWrite);
  10769. /** This waits for incoming data to be sent, and returns a socket that can be used
  10770. to read it.
  10771. The object that gets returned is owned by the caller, and can't be used for
  10772. sending, but can be used to read the data.
  10773. */
  10774. DatagramSocket* waitForNextConnection() const;
  10775. juce_UseDebuggingNewOperator
  10776. private:
  10777. String hostName;
  10778. int volatile portNumber, handle;
  10779. bool connected, allowBroadcast;
  10780. void* serverAddress;
  10781. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  10782. DatagramSocket (const DatagramSocket&);
  10783. const DatagramSocket& operator= (const DatagramSocket&);
  10784. };
  10785. #endif // __JUCE_SOCKET_JUCEHEADER__
  10786. /********* End of inlined file: juce_Socket.h *********/
  10787. #endif
  10788. #ifndef __JUCE_URL_JUCEHEADER__
  10789. /********* Start of inlined file: juce_URL.h *********/
  10790. #ifndef __JUCE_URL_JUCEHEADER__
  10791. #define __JUCE_URL_JUCEHEADER__
  10792. /**
  10793. Represents a URL and has a bunch of useful functions to manipulate it.
  10794. This class can be used to launch URLs in browsers, and also to create
  10795. InputStreams that can read from remote http or ftp sources.
  10796. */
  10797. class JUCE_API URL
  10798. {
  10799. public:
  10800. /** Creates an empty URL. */
  10801. URL() throw();
  10802. /** Creates a URL from a string. */
  10803. URL (const String& url);
  10804. /** Creates a copy of another URL. */
  10805. URL (const URL& other);
  10806. /** Destructor. */
  10807. ~URL() throw();
  10808. /** Copies this URL from another one. */
  10809. const URL& operator= (const URL& other);
  10810. /** Returns a string version of the URL.
  10811. If includeGetParameters is true and any parameters have been set with the
  10812. withParameter() method, then the string will have these appended on the
  10813. end and url-encoded.
  10814. */
  10815. const String toString (const bool includeGetParameters) const;
  10816. /** True if it seems to be valid. */
  10817. bool isWellFormed() const;
  10818. /** Returns just the domain part of the URL.
  10819. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  10820. */
  10821. const String getDomain() const;
  10822. /** Returns the path part of the URL.
  10823. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  10824. */
  10825. const String getSubPath() const;
  10826. /** Returns the scheme of the URL.
  10827. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  10828. include the colon).
  10829. */
  10830. const String getScheme() const;
  10831. /** Returns a new version of this URL that uses a different sub-path.
  10832. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  10833. "bar", it'll return "http://www.xyz.com/bar?x=1".
  10834. */
  10835. const URL withNewSubPath (const String& newPath) const;
  10836. /** Returns a copy of this URL, with a GET parameter added to the end.
  10837. Any control characters in the value will be encoded.
  10838. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  10839. would produce a new url whose toString(true) method would return
  10840. "www.fish.com?amount=some+fish".
  10841. */
  10842. const URL withParameter (const String& parameterName,
  10843. const String& parameterValue) const;
  10844. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  10845. When performing a POST where one of your parameters is a binary file, this
  10846. lets you specify the file.
  10847. Note that the filename is stored, but the file itself won't actually be read
  10848. until this URL is later used to create a network input stream.
  10849. */
  10850. const URL withFileToUpload (const String& parameterName,
  10851. const File& fileToUpload,
  10852. const String& mimeType) const;
  10853. /** Returns a set of all the parameters encoded into the url.
  10854. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  10855. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  10856. The values returned will have been cleaned up to remove any escape characters.
  10857. @see getNamedParameter, withParameter
  10858. */
  10859. const StringPairArray& getParameters() const throw();
  10860. /** Returns the set of files that should be uploaded as part of a POST operation.
  10861. This is the set of files that were added to the URL with the withFileToUpload()
  10862. method.
  10863. */
  10864. const StringPairArray& getFilesToUpload() const throw();
  10865. /** Returns the set of mime types associated with each of the upload files.
  10866. */
  10867. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  10868. /** Returns a copy of this URL, with a block of data to send as the POST data.
  10869. If you're setting the POST data, be careful not to have any parameters set
  10870. as well, otherwise it'll all get thrown in together, and might not have the
  10871. desired effect.
  10872. If the URL already contains some POST data, this will replace it, rather
  10873. than being appended to it.
  10874. This data will only be used if you specify a post operation when you call
  10875. createInputStream().
  10876. */
  10877. const URL withPOSTData (const String& postData) const;
  10878. /** Returns the data that was set using withPOSTData().
  10879. */
  10880. const String getPostData() const throw() { return postData; }
  10881. /** Tries to launch the system's default browser to open the URL.
  10882. Returns true if this seems to have worked.
  10883. */
  10884. bool launchInDefaultBrowser() const;
  10885. /** Takes a guess as to whether a string might be a valid website address.
  10886. This isn't foolproof!
  10887. */
  10888. static bool isProbablyAWebsiteURL (const String& possibleURL);
  10889. /** Takes a guess as to whether a string might be a valid email address.
  10890. This isn't foolproof!
  10891. */
  10892. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  10893. /** This callback function can be used by the createInputStream() method.
  10894. It allows your app to receive progress updates during a lengthy POST operation. If you
  10895. want to continue the operation, this should return true, or false to abort.
  10896. */
  10897. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  10898. /** Attempts to open a stream that can read from this URL.
  10899. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  10900. the paramters, otherwise it'll encode them into the
  10901. URL and do a 'GET'.
  10902. @param progressCallback if this is non-zero, it lets you supply a callback function
  10903. to keep track of the operation's progress. This can be useful
  10904. for lengthy POST operations, so that you can provide user feedback.
  10905. @param progressCallbackContext if a callback is specified, this value will be passed to
  10906. the function
  10907. @param extraHeaders if not empty, this string is appended onto the headers that
  10908. are used for the request. It must therefore be a valid set of HTML
  10909. header directives, separated by newlines.
  10910. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  10911. a negative number, it will be infinite. Otherwise it specifies a
  10912. time in milliseconds.
  10913. */
  10914. InputStream* createInputStream (const bool usePostCommand,
  10915. OpenStreamProgressCallback* const progressCallback = 0,
  10916. void* const progressCallbackContext = 0,
  10917. const String& extraHeaders = String::empty,
  10918. const int connectionTimeOutMs = 0) const;
  10919. /** Tries to download the entire contents of this URL into a binary data block.
  10920. If it succeeds, this will return true and append the data it read onto the end
  10921. of the memory block.
  10922. @param destData the memory block to append the new data to
  10923. @param usePostCommand whether to use a POST command to get the data (uses
  10924. a GET command if this is false)
  10925. @see readEntireTextStream, readEntireXmlStream
  10926. */
  10927. bool readEntireBinaryStream (MemoryBlock& destData,
  10928. const bool usePostCommand = false) const;
  10929. /** Tries to download the entire contents of this URL as a string.
  10930. If it fails, this will return an empty string, otherwise it will return the
  10931. contents of the downloaded file. If you need to distinguish between a read
  10932. operation that fails and one that returns an empty string, you'll need to use
  10933. a different method, such as readEntireBinaryStream().
  10934. @param usePostCommand whether to use a POST command to get the data (uses
  10935. a GET command if this is false)
  10936. @see readEntireBinaryStream, readEntireXmlStream
  10937. */
  10938. const String readEntireTextStream (const bool usePostCommand = false) const;
  10939. /** Tries to download the entire contents of this URL and parse it as XML.
  10940. If it fails, or if the text that it reads can't be parsed as XML, this will
  10941. return 0.
  10942. When it returns a valid XmlElement object, the caller is responsibile for deleting
  10943. this object when no longer needed.
  10944. @param usePostCommand whether to use a POST command to get the data (uses
  10945. a GET command if this is false)
  10946. @see readEntireBinaryStream, readEntireTextStream
  10947. */
  10948. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  10949. /** Adds escape sequences to a string to encode any characters that aren't
  10950. legal in a URL.
  10951. E.g. any spaces will be replaced with "%20".
  10952. This is the opposite of removeEscapeChars().
  10953. If isParameter is true, it means that the string is going to be used
  10954. as a parameter, so it also encodes '$' and ',' (which would otherwise
  10955. be legal in a URL.
  10956. @see removeEscapeChars
  10957. */
  10958. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  10959. const bool isParameter);
  10960. /** Replaces any escape character sequences in a string with their original
  10961. character codes.
  10962. E.g. any instances of "%20" will be replaced by a space.
  10963. This is the opposite of addEscapeChars().
  10964. @see addEscapeChars
  10965. */
  10966. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  10967. juce_UseDebuggingNewOperator
  10968. private:
  10969. String url, postData;
  10970. StringPairArray parameters, filesToUpload, mimeTypes;
  10971. };
  10972. #endif // __JUCE_URL_JUCEHEADER__
  10973. /********* End of inlined file: juce_URL.h *********/
  10974. #endif
  10975. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10976. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  10977. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10978. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10979. /** Wraps another input stream, and reads from it using an intermediate buffer
  10980. If you're using an input stream such as a file input stream, and making lots of
  10981. small read accesses to it, it's probably sensible to wrap it in one of these,
  10982. so that the source stream gets accessed in larger chunk sizes, meaning less
  10983. work for the underlying stream.
  10984. */
  10985. class JUCE_API BufferedInputStream : public InputStream
  10986. {
  10987. public:
  10988. /** Creates a BufferedInputStream from an input source.
  10989. @param sourceStream the source stream to read from
  10990. @param bufferSize the size of reservoir to use to buffer the source
  10991. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  10992. deleted by this object when it is itself deleted.
  10993. */
  10994. BufferedInputStream (InputStream* const sourceStream,
  10995. const int bufferSize,
  10996. const bool deleteSourceWhenDestroyed) throw();
  10997. /** Destructor.
  10998. This may also delete the source stream, if that option was chosen when the
  10999. buffered stream was created.
  11000. */
  11001. ~BufferedInputStream() throw();
  11002. int64 getTotalLength();
  11003. int64 getPosition();
  11004. bool setPosition (int64 newPosition);
  11005. int read (void* destBuffer, int maxBytesToRead);
  11006. const String readString();
  11007. bool isExhausted();
  11008. juce_UseDebuggingNewOperator
  11009. private:
  11010. InputStream* const source;
  11011. const bool deleteSourceWhenDestroyed;
  11012. int bufferSize;
  11013. int64 position, lastReadPos, bufferStart, bufferOverlap;
  11014. char* buffer;
  11015. void ensureBuffered();
  11016. BufferedInputStream (const BufferedInputStream&);
  11017. const BufferedInputStream& operator= (const BufferedInputStream&);
  11018. };
  11019. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11020. /********* End of inlined file: juce_BufferedInputStream.h *********/
  11021. #endif
  11022. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11023. /********* Start of inlined file: juce_FileInputSource.h *********/
  11024. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11025. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11026. /**
  11027. A type of InputSource that represents a normal file.
  11028. @see InputSource
  11029. */
  11030. class JUCE_API FileInputSource : public InputSource
  11031. {
  11032. public:
  11033. FileInputSource (const File& file) throw();
  11034. ~FileInputSource();
  11035. InputStream* createInputStream();
  11036. InputStream* createInputStreamFor (const String& relatedItemPath);
  11037. int64 hashCode() const;
  11038. juce_UseDebuggingNewOperator
  11039. private:
  11040. const File file;
  11041. FileInputSource (const FileInputSource&);
  11042. const FileInputSource& operator= (const FileInputSource&);
  11043. };
  11044. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11045. /********* End of inlined file: juce_FileInputSource.h *********/
  11046. #endif
  11047. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11048. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  11049. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11050. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11051. /**
  11052. A stream which uses zlib to compress the data written into it.
  11053. @see GZIPDecompressorInputStream
  11054. */
  11055. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  11056. {
  11057. public:
  11058. /** Creates a compression stream.
  11059. @param destStream the stream into which the compressed data should
  11060. be written
  11061. @param compressionLevel how much to compress the data, between 1 and 9, where
  11062. 1 is the fastest/lowest compression, and 9 is the
  11063. slowest/highest compression. Any value outside this range
  11064. indicates that a default compression level should be used.
  11065. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  11066. this stream is destroyed
  11067. @param noWrap this is used internally by the ZipFile class
  11068. and should be ignored by user applications
  11069. */
  11070. GZIPCompressorOutputStream (OutputStream* const destStream,
  11071. int compressionLevel = 0,
  11072. const bool deleteDestStreamWhenDestroyed = false,
  11073. const bool noWrap = false);
  11074. /** Destructor. */
  11075. ~GZIPCompressorOutputStream();
  11076. void flush();
  11077. int64 getPosition();
  11078. bool setPosition (int64 newPosition);
  11079. bool write (const void* destBuffer, int howMany);
  11080. juce_UseDebuggingNewOperator
  11081. private:
  11082. OutputStream* const destStream;
  11083. const bool deleteDestStream;
  11084. uint8* buffer;
  11085. void* helper;
  11086. bool doNextBlock();
  11087. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  11088. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  11089. };
  11090. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11091. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  11092. #endif
  11093. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11094. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  11095. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11096. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11097. /**
  11098. This stream will decompress a source-stream using zlib.
  11099. Tip: if you're reading lots of small items from one of these streams, you
  11100. can increase the performance enormously by passing it through a
  11101. BufferedInputStream, so that it has to read larger blocks less often.
  11102. @see GZIPCompressorOutputStream
  11103. */
  11104. class JUCE_API GZIPDecompressorInputStream : public InputStream
  11105. {
  11106. public:
  11107. /** Creates a decompressor stream.
  11108. @param sourceStream the stream to read from
  11109. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  11110. when this object is destroyed
  11111. @param noWrap this is used internally by the ZipFile class
  11112. and should be ignored by user applications
  11113. @param uncompressedStreamLength if the creator knows the length that the
  11114. uncompressed stream will be, then it can supply this
  11115. value, which will be returned by getTotalLength()
  11116. */
  11117. GZIPDecompressorInputStream (InputStream* const sourceStream,
  11118. const bool deleteSourceWhenDestroyed,
  11119. const bool noWrap = false,
  11120. const int64 uncompressedStreamLength = -1);
  11121. /** Destructor. */
  11122. ~GZIPDecompressorInputStream();
  11123. int64 getPosition();
  11124. bool setPosition (int64 pos);
  11125. int64 getTotalLength();
  11126. bool isExhausted();
  11127. int read (void* destBuffer, int maxBytesToRead);
  11128. juce_UseDebuggingNewOperator
  11129. private:
  11130. InputStream* const sourceStream;
  11131. const int64 uncompressedStreamLength;
  11132. const bool deleteSourceWhenDestroyed, noWrap;
  11133. bool isEof;
  11134. int activeBufferSize;
  11135. int64 originalSourcePos, currentPos;
  11136. uint8* buffer;
  11137. void* helper;
  11138. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  11139. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  11140. };
  11141. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11142. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  11143. #endif
  11144. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11145. #endif
  11146. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  11147. #endif
  11148. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11149. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  11150. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11151. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11152. /**
  11153. Allows a block of data and to be accessed as a stream.
  11154. This can either be used to refer to a shared block of memory, or can make its
  11155. own internal copy of the data when the MemoryInputStream is created.
  11156. */
  11157. class JUCE_API MemoryInputStream : public InputStream
  11158. {
  11159. public:
  11160. /** Creates a MemoryInputStream.
  11161. @param sourceData the block of data to use as the stream's source
  11162. @param sourceDataSize the number of bytes in the source data block
  11163. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  11164. the source data, so this data shouldn't be changed
  11165. for the lifetime of the stream; if this parameter is
  11166. true, the stream will make its own copy of the
  11167. data and use that.
  11168. */
  11169. MemoryInputStream (const void* const sourceData,
  11170. const int sourceDataSize,
  11171. const bool keepInternalCopyOfData) throw();
  11172. /** Destructor. */
  11173. ~MemoryInputStream() throw();
  11174. int64 getPosition();
  11175. bool setPosition (int64 pos);
  11176. int64 getTotalLength();
  11177. bool isExhausted();
  11178. int read (void* destBuffer, int maxBytesToRead);
  11179. juce_UseDebuggingNewOperator
  11180. private:
  11181. const char* data;
  11182. int dataSize, position;
  11183. MemoryBlock internalCopy;
  11184. };
  11185. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11186. /********* End of inlined file: juce_MemoryInputStream.h *********/
  11187. #endif
  11188. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11189. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  11190. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11191. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11192. /** Writes data to an internal memory buffer, which grows as required.
  11193. The data that was written into the stream can then be accessed later as
  11194. a contiguous block of memory.
  11195. */
  11196. class JUCE_API MemoryOutputStream : public OutputStream
  11197. {
  11198. public:
  11199. /** Creates a memory stream ready for writing into.
  11200. @param initialSize the intial amount of space to allocate for writing into
  11201. @param granularity the increments by which the internal storage will be increased
  11202. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  11203. place that the data gets stored. If it's zero, the stream
  11204. will allocate its own storage internally, which you can
  11205. access using getData() and getDataSize()
  11206. */
  11207. MemoryOutputStream (const int initialSize = 256,
  11208. const int granularity = 256,
  11209. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  11210. /** Destructor.
  11211. This will free any data that was written to it.
  11212. */
  11213. ~MemoryOutputStream() throw();
  11214. /** Returns a pointer to the data that has been written to the stream.
  11215. @see getDataSize
  11216. */
  11217. const char* getData() throw();
  11218. /** Returns the number of bytes of data that have been written to the stream.
  11219. @see getData
  11220. */
  11221. int getDataSize() const throw();
  11222. /** Resets the stream, clearing any data that has been written to it so far. */
  11223. void reset() throw();
  11224. void flush();
  11225. bool write (const void* buffer, int howMany);
  11226. int64 getPosition();
  11227. bool setPosition (int64 newPosition);
  11228. juce_UseDebuggingNewOperator
  11229. private:
  11230. MemoryBlock* data;
  11231. int position, size, blockSize;
  11232. bool ownsMemoryBlock;
  11233. };
  11234. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11235. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  11236. #endif
  11237. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  11238. #endif
  11239. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11240. /********* Start of inlined file: juce_SubregionStream.h *********/
  11241. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11242. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11243. /** Wraps another input stream, and reads from a specific part of it.
  11244. This lets you take a subsection of a stream and present it as an entire
  11245. stream in its own right.
  11246. */
  11247. class JUCE_API SubregionStream : public InputStream
  11248. {
  11249. public:
  11250. /** Creates a SubregionStream from an input source.
  11251. @param sourceStream the source stream to read from
  11252. @param startPositionInSourceStream this is the position in the source stream that
  11253. corresponds to position 0 in this stream
  11254. @param lengthOfSourceStream this specifies the maximum number of bytes
  11255. from the source stream that will be passed through
  11256. by this stream. When the position of this stream
  11257. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  11258. If the length passed in here is greater than the length
  11259. of the source stream (as returned by getTotalLength()),
  11260. then the smaller value will be used.
  11261. Passing a negative value for this parameter means it
  11262. will keep reading until the source's end-of-stream.
  11263. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  11264. deleted by this object when it is itself deleted.
  11265. */
  11266. SubregionStream (InputStream* const sourceStream,
  11267. const int64 startPositionInSourceStream,
  11268. const int64 lengthOfSourceStream,
  11269. const bool deleteSourceWhenDestroyed) throw();
  11270. /** Destructor.
  11271. This may also delete the source stream, if that option was chosen when the
  11272. buffered stream was created.
  11273. */
  11274. ~SubregionStream() throw();
  11275. int64 getTotalLength();
  11276. int64 getPosition();
  11277. bool setPosition (int64 newPosition);
  11278. int read (void* destBuffer, int maxBytesToRead);
  11279. bool isExhausted();
  11280. juce_UseDebuggingNewOperator
  11281. private:
  11282. InputStream* const source;
  11283. const bool deleteSourceWhenDestroyed;
  11284. const int64 startPositionInSourceStream, lengthOfSourceStream;
  11285. SubregionStream (const SubregionStream&);
  11286. const SubregionStream& operator= (const SubregionStream&);
  11287. };
  11288. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11289. /********* End of inlined file: juce_SubregionStream.h *********/
  11290. #endif
  11291. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11292. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  11293. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11294. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11295. /** Used in the same way as the T(text) macro, this will attempt to translate a
  11296. string into a localised version using the LocalisedStrings class.
  11297. @see LocalisedStrings
  11298. */
  11299. #define TRANS(stringLiteral) \
  11300. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  11301. /**
  11302. Used to convert strings to localised foreign-language versions.
  11303. This is basically a look-up table of strings and their translated equivalents.
  11304. It can be loaded from a text file, so that you can supply a set of localised
  11305. versions of strings that you use in your app.
  11306. To use it in your code, simply call the translate() method on each string that
  11307. might have foreign versions, and if none is found, the method will just return
  11308. the original string.
  11309. The translation file should start with some lines specifying a description of
  11310. the language it contains, and also a list of ISO country codes where it might
  11311. be appropriate to use the file. After that, each line of the file should contain
  11312. a pair of quoted strings with an '=' sign.
  11313. E.g. for a french translation, the file might be:
  11314. @code
  11315. language: French
  11316. countries: fr be mc ch lu
  11317. "hello" = "bonjour"
  11318. "goodbye" = "au revoir"
  11319. @endcode
  11320. If the strings need to contain a quote character, they can use '\"' instead, and
  11321. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  11322. (you can use this to add comments).
  11323. Note that this is a singleton class, so don't create or destroy the object directly.
  11324. There's also a TRANS(text) macro defined to make it easy to use the this.
  11325. E.g. @code
  11326. printSomething (TRANS("hello"));
  11327. @endcode
  11328. This macro is used in the Juce classes themselves, so your application has a chance to
  11329. intercept and translate any internal Juce text strings that might be shown. (You can easily
  11330. get a list of all the messages by searching for the TRANS() macro in the Juce source
  11331. code).
  11332. */
  11333. class JUCE_API LocalisedStrings
  11334. {
  11335. public:
  11336. /** Creates a set of translations from the text of a translation file.
  11337. When you create one of these, you can call setCurrentMappings() to make it
  11338. the set of mappings that the system's using.
  11339. */
  11340. LocalisedStrings (const String& fileContents) throw();
  11341. /** Creates a set of translations from a file.
  11342. When you create one of these, you can call setCurrentMappings() to make it
  11343. the set of mappings that the system's using.
  11344. */
  11345. LocalisedStrings (const File& fileToLoad) throw();
  11346. /** Destructor. */
  11347. ~LocalisedStrings() throw();
  11348. /** Selects the current set of mappings to be used by the system.
  11349. The object you pass in will be automatically deleted when no longer needed, so
  11350. don't keep a pointer to it. You can also pass in zero to remove the current
  11351. mappings.
  11352. See also the TRANS() macro, which uses the current set to do its translation.
  11353. @see translateWithCurrentMappings
  11354. */
  11355. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  11356. /** Returns the currently selected set of mappings.
  11357. This is the object that was last passed to setCurrentMappings(). It may
  11358. be 0 if none has been created.
  11359. */
  11360. static LocalisedStrings* getCurrentMappings() throw();
  11361. /** Tries to translate a string using the currently selected set of mappings.
  11362. If no mapping has been set, or if the mapping doesn't contain a translation
  11363. for the string, this will just return the original string.
  11364. See also the TRANS() macro, which uses this method to do its translation.
  11365. @see setCurrentMappings, getCurrentMappings
  11366. */
  11367. static const String translateWithCurrentMappings (const String& text) throw();
  11368. /** Tries to translate a string using the currently selected set of mappings.
  11369. If no mapping has been set, or if the mapping doesn't contain a translation
  11370. for the string, this will just return the original string.
  11371. See also the TRANS() macro, which uses this method to do its translation.
  11372. @see setCurrentMappings, getCurrentMappings
  11373. */
  11374. static const String translateWithCurrentMappings (const char* text) throw();
  11375. /** Attempts to look up a string and return its localised version.
  11376. If the string isn't found in the list, the original string will be returned.
  11377. */
  11378. const String translate (const String& text) const throw();
  11379. /** Returns the name of the language specified in the translation file.
  11380. This is specified in the file using a line starting with "language:", e.g.
  11381. @code
  11382. language: german
  11383. @endcode
  11384. */
  11385. const String getLanguageName() const throw() { return languageName; }
  11386. /** Returns the list of suitable country codes listed in the translation file.
  11387. These is specified in the file using a line starting with "countries:", e.g.
  11388. @code
  11389. countries: fr be mc ch lu
  11390. @endcode
  11391. The country codes are supposed to be 2-character ISO complient codes.
  11392. */
  11393. const StringArray getCountryCodes() const throw() { return countryCodes; }
  11394. /** Indicates whether to use a case-insensitive search when looking up a string.
  11395. This defaults to true.
  11396. */
  11397. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  11398. juce_UseDebuggingNewOperator
  11399. private:
  11400. String languageName;
  11401. StringArray countryCodes;
  11402. StringPairArray translations;
  11403. void loadFromText (const String& fileContents) throw();
  11404. };
  11405. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11406. /********* End of inlined file: juce_LocalisedStrings.h *********/
  11407. #endif
  11408. #ifndef __JUCE_STRING_JUCEHEADER__
  11409. #endif
  11410. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  11411. #endif
  11412. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  11413. #endif
  11414. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  11415. #endif
  11416. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  11417. /********* Start of inlined file: juce_XmlDocument.h *********/
  11418. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  11419. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  11420. /**
  11421. Parses a text-based XML document and creates an XmlElement object from it.
  11422. The parser will parse DTDs to load external entities but won't
  11423. check the document for validity against the DTD.
  11424. e.g.
  11425. @code
  11426. XmlDocument myDocument (File ("myfile.xml"));
  11427. XmlElement* mainElement = myDocument.getDocumentElement();
  11428. if (mainElement == 0)
  11429. {
  11430. String error = myDocument.getLastParseError();
  11431. }
  11432. else
  11433. {
  11434. ..use the element
  11435. }
  11436. @endcode
  11437. @see XmlElement
  11438. */
  11439. class JUCE_API XmlDocument
  11440. {
  11441. public:
  11442. /** Creates an XmlDocument from the xml text.
  11443. The text doesn't actually get parsed until the getDocumentElement() method is
  11444. called.
  11445. */
  11446. XmlDocument (const String& documentText) throw();
  11447. /** Creates an XmlDocument from a file.
  11448. The text doesn't actually get parsed until the getDocumentElement() method is
  11449. called.
  11450. */
  11451. XmlDocument (const File& file);
  11452. /** Destructor. */
  11453. ~XmlDocument() throw();
  11454. /** Creates an XmlElement object to represent the main document node.
  11455. This method will do the actual parsing of the text, and if there's a
  11456. parse error, it may returns 0 (and you can find out the error using
  11457. the getLastParseError() method).
  11458. @param onlyReadOuterDocumentElement if true, the parser will only read the
  11459. first section of the file, and will only
  11460. return the outer document element - this
  11461. allows quick checking of large files to
  11462. see if they contain the correct type of
  11463. tag, without having to parse the entire file
  11464. @returns a new XmlElement which the caller will need to delete, or null if
  11465. there was an error.
  11466. @see getLastParseError
  11467. */
  11468. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  11469. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  11470. @returns the error, or an empty string if there was no error.
  11471. */
  11472. const String& getLastParseError() const throw();
  11473. /** Sets an input source object to use for parsing documents that reference external entities.
  11474. If the document has been created from a file, this probably won't be needed, but
  11475. if you're parsing some text and there might be a DTD that references external
  11476. files, you may need to create a custom input source that can retrieve the
  11477. other files it needs.
  11478. The object that is passed-in will be deleted automatically when no longer needed.
  11479. @see InputSource
  11480. */
  11481. void setInputSource (InputSource* const newSource) throw();
  11482. /** Sets a flag to change the treatment of empty text elements.
  11483. If this is true (the default state), then any text elements that contain only
  11484. whitespace characters will be ingored during parsing. If you need to catch
  11485. whitespace-only text, then you should set this to false before calling the
  11486. getDocumentElement() method.
  11487. */
  11488. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  11489. juce_UseDebuggingNewOperator
  11490. private:
  11491. String originalText;
  11492. const tchar* input;
  11493. bool outOfData, errorOccurred;
  11494. bool identifierLookupTable [128];
  11495. String lastError, dtdText;
  11496. StringArray tokenisedDTD;
  11497. bool needToLoadDTD, ignoreEmptyTextElements;
  11498. InputSource* inputSource;
  11499. void setLastError (const String& desc, const bool carryOn) throw();
  11500. void skipHeader() throw();
  11501. void skipNextWhiteSpace() throw();
  11502. tchar readNextChar() throw();
  11503. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  11504. void readChildElements (XmlElement* parent) throw();
  11505. int findNextTokenLength() throw();
  11506. void readQuotedString (String& result) throw();
  11507. void readEntity (String& result) throw();
  11508. const String getFileContents (const String& filename) const;
  11509. const String expandEntity (const String& entity);
  11510. const String expandExternalEntity (const String& entity);
  11511. const String getParameterEntity (const String& entity);
  11512. };
  11513. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  11514. /********* End of inlined file: juce_XmlDocument.h *********/
  11515. #endif
  11516. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  11517. #endif
  11518. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  11519. #endif
  11520. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11521. /********* Start of inlined file: juce_InterProcessLock.h *********/
  11522. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11523. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11524. /**
  11525. Acts as a critical section which processes can use to block each other.
  11526. @see CriticalSection
  11527. */
  11528. class JUCE_API InterProcessLock
  11529. {
  11530. public:
  11531. /** Creates a lock object.
  11532. @param name a name that processes will use to identify this lock object
  11533. */
  11534. InterProcessLock (const String& name) throw();
  11535. /** Destructor.
  11536. This will also release the lock if it's currently held by this process.
  11537. */
  11538. ~InterProcessLock() throw();
  11539. /** Attempts to lock the critical section.
  11540. @param timeOutMillisecs how many milliseconds to wait if the lock
  11541. is already held by another process - a value of
  11542. 0 will return immediately, negative values will wait
  11543. forever
  11544. @returns true if the lock could be gained within the timeout period, or
  11545. false if the timeout expired.
  11546. */
  11547. bool enter (int timeOutMillisecs = -1) throw();
  11548. /** Releases the lock if it's currently held by this process.
  11549. */
  11550. void exit() throw();
  11551. juce_UseDebuggingNewOperator
  11552. private:
  11553. void* internal;
  11554. String name;
  11555. int reentrancyLevel;
  11556. InterProcessLock (const InterProcessLock&);
  11557. const InterProcessLock& operator= (const InterProcessLock&);
  11558. };
  11559. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11560. /********* End of inlined file: juce_InterProcessLock.h *********/
  11561. #endif
  11562. #ifndef __JUCE_PROCESS_JUCEHEADER__
  11563. /********* Start of inlined file: juce_Process.h *********/
  11564. #ifndef __JUCE_PROCESS_JUCEHEADER__
  11565. #define __JUCE_PROCESS_JUCEHEADER__
  11566. /** Represents the current executable's process.
  11567. This contains methods for controlling the current application at the
  11568. process-level.
  11569. @see Thread, JUCEApplication
  11570. */
  11571. class JUCE_API Process
  11572. {
  11573. public:
  11574. enum ProcessPriority
  11575. {
  11576. LowPriority = 0,
  11577. NormalPriority = 1,
  11578. HighPriority = 2,
  11579. RealtimePriority = 3
  11580. };
  11581. /** Changes the current process's priority.
  11582. @param priority the process priority, where
  11583. 0=low, 1=normal, 2=high, 3=realtime
  11584. */
  11585. static void setPriority (const ProcessPriority priority);
  11586. /** Kills the current process immediately.
  11587. This is an emergency process terminator that kills the application
  11588. immediately - it's intended only for use only when something goes
  11589. horribly wrong.
  11590. @see JUCEApplication::quit
  11591. */
  11592. static void terminate();
  11593. /** Returns true if this application process is the one that the user is
  11594. currently using.
  11595. */
  11596. static bool isForegroundProcess() throw();
  11597. /** Raises the current process's privilege level.
  11598. Does nothing if this isn't supported by the current OS, or if process
  11599. privilege level is fixed.
  11600. */
  11601. static void raisePrivilege();
  11602. /** Lowers the current process's privilege level.
  11603. Does nothing if this isn't supported by the current OS, or if process
  11604. privilege level is fixed.
  11605. */
  11606. static void lowerPrivilege();
  11607. /** Returns true if this process is being hosted by a debugger.
  11608. */
  11609. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  11610. };
  11611. #endif // __JUCE_PROCESS_JUCEHEADER__
  11612. /********* End of inlined file: juce_Process.h *********/
  11613. #endif
  11614. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11615. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  11616. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11617. #define __JUCE_READWRITELOCK_JUCEHEADER__
  11618. /********* Start of inlined file: juce_WaitableEvent.h *********/
  11619. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11620. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  11621. /**
  11622. Allows threads to wait for events triggered by other threads.
  11623. A thread can call wait() on a WaitableObject, and this will suspend the
  11624. calling thread until another thread wakes it up by calling the signal()
  11625. method.
  11626. */
  11627. class JUCE_API WaitableEvent
  11628. {
  11629. public:
  11630. /** Creates a WaitableEvent object. */
  11631. WaitableEvent() throw();
  11632. /** Destructor.
  11633. If other threads are waiting on this object when it gets deleted, this
  11634. can cause nasty errors, so be careful!
  11635. */
  11636. ~WaitableEvent() throw();
  11637. /** Suspends the calling thread until the event has been signalled.
  11638. This will wait until the object's signal() method is called by another thread,
  11639. or until the timeout expires.
  11640. After the event has been signalled, this method will return true and reset
  11641. the event.
  11642. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  11643. value will cause it to wait forever.
  11644. @returns true if the object has been signalled, false if the timeout expires first.
  11645. @see signal, reset
  11646. */
  11647. bool wait (const int timeOutMilliseconds = -1) const throw();
  11648. /** Wakes up any threads that are currently waiting on this object.
  11649. If signal() is called when nothing is waiting, the next thread to call wait()
  11650. will return immediately and reset the signal.
  11651. @see wait, reset
  11652. */
  11653. void signal() const throw();
  11654. /** Resets the event to an unsignalled state.
  11655. If it's not already signalled, this does nothing.
  11656. */
  11657. void reset() const throw();
  11658. juce_UseDebuggingNewOperator
  11659. private:
  11660. void* internal;
  11661. WaitableEvent (const WaitableEvent&);
  11662. const WaitableEvent& operator= (const WaitableEvent&);
  11663. };
  11664. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  11665. /********* End of inlined file: juce_WaitableEvent.h *********/
  11666. /********* Start of inlined file: juce_Thread.h *********/
  11667. #ifndef __JUCE_THREAD_JUCEHEADER__
  11668. #define __JUCE_THREAD_JUCEHEADER__
  11669. /**
  11670. Encapsulates a thread.
  11671. Subclasses derive from Thread and implement the run() method, in which they
  11672. do their business. The thread can then be started with the startThread() method
  11673. and controlled with various other methods.
  11674. This class also contains some thread-related static methods, such
  11675. as sleep(), yield(), getCurrentThreadId() etc.
  11676. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  11677. MessageManagerLock
  11678. */
  11679. class JUCE_API Thread
  11680. {
  11681. public:
  11682. /**
  11683. Creates a thread.
  11684. When first created, the thread is not running. Use the startThread()
  11685. method to start it.
  11686. */
  11687. Thread (const String& threadName);
  11688. /** Destructor.
  11689. Deleting a Thread object that is running will only give the thread a
  11690. brief opportunity to stop itself cleanly, so it's recommended that you
  11691. should always call stopThread() with a decent timeout before deleting,
  11692. to avoid the thread being forcibly killed (which is a Bad Thing).
  11693. */
  11694. virtual ~Thread();
  11695. /** Must be implemented to perform the thread's actual code.
  11696. Remember that the thread must regularly check the threadShouldExit()
  11697. method whilst running, and if this returns true it should return from
  11698. the run() method as soon as possible to avoid being forcibly killed.
  11699. @see threadShouldExit, startThread
  11700. */
  11701. virtual void run() = 0;
  11702. // Thread control functions..
  11703. /** Starts the thread running.
  11704. This will start the thread's run() method.
  11705. (if it's already started, startThread() won't do anything).
  11706. @see stopThread
  11707. */
  11708. void startThread() throw();
  11709. /** Starts the thread with a given priority.
  11710. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  11711. If the thread is already running, its priority will be changed.
  11712. @see startThread, setPriority
  11713. */
  11714. void startThread (const int priority) throw();
  11715. /** Attempts to stop the thread running.
  11716. This method will cause the threadShouldExit() method to return true
  11717. and call notify() in case the thread is currently waiting.
  11718. Hopefully the thread will then respond to this by exiting cleanly, and
  11719. the stopThread method will wait for a given time-period for this to
  11720. happen.
  11721. If the thread is stuck and fails to respond after the time-out, it gets
  11722. forcibly killed, which is a very bad thing to happen, as it could still
  11723. be holding locks, etc. which are needed by other parts of your program.
  11724. @param timeOutMilliseconds The number of milliseconds to wait for the
  11725. thread to finish before killing it by force. A negative
  11726. value in here will wait forever.
  11727. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  11728. */
  11729. void stopThread (const int timeOutMilliseconds) throw();
  11730. /** Returns true if the thread is currently active */
  11731. bool isThreadRunning() const throw();
  11732. /** Sets a flag to tell the thread it should stop.
  11733. Calling this means that the threadShouldExit() method will then return true.
  11734. The thread should be regularly checking this to see whether it should exit.
  11735. @see threadShouldExit
  11736. @see waitForThreadToExit
  11737. */
  11738. void signalThreadShouldExit() throw();
  11739. /** Checks whether the thread has been told to stop running.
  11740. Threads need to check this regularly, and if it returns true, they should
  11741. return from their run() method at the first possible opportunity.
  11742. @see signalThreadShouldExit
  11743. */
  11744. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  11745. /** Waits for the thread to stop.
  11746. This will waits until isThreadRunning() is false or until a timeout expires.
  11747. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  11748. is less than zero, it will wait forever.
  11749. @returns true if the thread exits, or false if the timeout expires first.
  11750. */
  11751. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  11752. /** Changes the thread's priority.
  11753. May return false if for some reason the priority can't be changed.
  11754. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  11755. of 5 is normal.
  11756. */
  11757. bool setPriority (const int priority) throw();
  11758. /** Changes the priority of the caller thread.
  11759. Similar to setPriority(), but this static method acts on the caller thread.
  11760. May return false if for some reason the priority can't be changed.
  11761. @see setPriority
  11762. */
  11763. static bool setCurrentThreadPriority (const int priority) throw();
  11764. /** Sets the affinity mask for the thread.
  11765. This will only have an effect next time the thread is started - i.e. if the
  11766. thread is already running when called, it'll have no effect.
  11767. @see setCurrentThreadAffinityMask
  11768. */
  11769. void setAffinityMask (const uint32 affinityMask) throw();
  11770. /** Changes the affinity mask for the caller thread.
  11771. This will change the affinity mask for the thread that calls this static method.
  11772. @see setAffinityMask
  11773. */
  11774. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  11775. // this can be called from any thread that needs to pause..
  11776. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  11777. /** Yields the calling thread's current time-slot. */
  11778. static void JUCE_CALLTYPE yield() throw();
  11779. /** Makes the thread wait for a notification.
  11780. This puts the thread to sleep until either the timeout period expires, or
  11781. another thread calls the notify() method to wake it up.
  11782. @returns true if the event has been signalled, false if the timeout expires.
  11783. */
  11784. bool wait (const int timeOutMilliseconds) const throw();
  11785. /** Wakes up the thread.
  11786. If the thread has called the wait() method, this will wake it up.
  11787. @see wait
  11788. */
  11789. void notify() const throw();
  11790. /** A value type used for thread IDs.
  11791. @see getCurrentThreadId(), getThreadId()
  11792. */
  11793. typedef void* ThreadID;
  11794. /** Returns an id that identifies the caller thread.
  11795. To find the ID of a particular thread object, use getThreadId().
  11796. @returns a unique identifier that identifies the calling thread.
  11797. @see getThreadId
  11798. */
  11799. static ThreadID getCurrentThreadId() throw();
  11800. /** Finds the thread object that is currently running.
  11801. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  11802. object associated with them, so this will return 0.
  11803. */
  11804. static Thread* getCurrentThread() throw();
  11805. /** Returns the ID of this thread.
  11806. That means the ID of this thread object - not of the thread that's calling the method.
  11807. This can change when the thread is started and stopped, and will be invalid if the
  11808. thread's not actually running.
  11809. @see getCurrentThreadId
  11810. */
  11811. ThreadID getThreadId() const throw();
  11812. /** Returns the name of the thread.
  11813. This is the name that gets set in the constructor.
  11814. */
  11815. const String getThreadName() const throw() { return threadName_; }
  11816. /** Returns the number of currently-running threads.
  11817. @returns the number of Thread objects known to be currently running.
  11818. @see stopAllThreads
  11819. */
  11820. static int getNumRunningThreads() throw();
  11821. /** Tries to stop all currently-running threads.
  11822. This will attempt to stop all the threads known to be running at the moment.
  11823. */
  11824. static void stopAllThreads (const int timeoutInMillisecs) throw();
  11825. juce_UseDebuggingNewOperator
  11826. private:
  11827. const String threadName_;
  11828. void* volatile threadHandle_;
  11829. CriticalSection startStopLock;
  11830. WaitableEvent startSuspensionEvent_, defaultEvent_;
  11831. int threadPriority_;
  11832. ThreadID threadId_;
  11833. uint32 affinityMask_;
  11834. bool volatile threadShouldExit_;
  11835. friend void JUCE_API juce_threadEntryPoint (void*);
  11836. static void threadEntryPoint (Thread* thread) throw();
  11837. Thread (const Thread&);
  11838. const Thread& operator= (const Thread&);
  11839. };
  11840. #endif // __JUCE_THREAD_JUCEHEADER__
  11841. /********* End of inlined file: juce_Thread.h *********/
  11842. /**
  11843. A critical section that allows multiple simultaneous readers.
  11844. Features of this type of lock are:
  11845. - Multiple readers can hold the lock at the same time, but only one writer
  11846. can hold it at once.
  11847. - Writers trying to gain the lock will be blocked until all readers and writers
  11848. have released it
  11849. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  11850. blocked until the writer has obtained and released it
  11851. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  11852. there are no other readers
  11853. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  11854. - Recursive locking is supported.
  11855. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  11856. */
  11857. class JUCE_API ReadWriteLock
  11858. {
  11859. public:
  11860. /**
  11861. Creates a ReadWriteLock object.
  11862. */
  11863. ReadWriteLock() throw();
  11864. /** Destructor.
  11865. If the object is deleted whilst locked, any subsequent behaviour
  11866. is unpredictable.
  11867. */
  11868. ~ReadWriteLock() throw();
  11869. /** Locks this object for reading.
  11870. Multiple threads can simulaneously lock the object for reading, but if another
  11871. thread has it locked for writing, then this will block until it releases the
  11872. lock.
  11873. @see exitRead, ScopedReadLock
  11874. */
  11875. void enterRead() const throw();
  11876. /** Releases the read-lock.
  11877. If the caller thread hasn't got the lock, this can have unpredictable results.
  11878. If the enterRead() method has been called multiple times by the thread, each
  11879. call must be matched by a call to exitRead() before other threads will be allowed
  11880. to take over the lock.
  11881. @see enterRead, ScopedReadLock
  11882. */
  11883. void exitRead() const throw();
  11884. /** Locks this object for writing.
  11885. This will block until any other threads that have it locked for reading or
  11886. writing have released their lock.
  11887. @see exitWrite, ScopedWriteLock
  11888. */
  11889. void enterWrite() const throw();
  11890. /** Tries to lock this object for writing.
  11891. This is like enterWrite(), but doesn't block - it returns true if it manages
  11892. to obtain the lock.
  11893. @see enterWrite
  11894. */
  11895. bool tryEnterWrite() const throw();
  11896. /** Releases the write-lock.
  11897. If the caller thread hasn't got the lock, this can have unpredictable results.
  11898. If the enterWrite() method has been called multiple times by the thread, each
  11899. call must be matched by a call to exit() before other threads will be allowed
  11900. to take over the lock.
  11901. @see enterWrite, ScopedWriteLock
  11902. */
  11903. void exitWrite() const throw();
  11904. juce_UseDebuggingNewOperator
  11905. private:
  11906. CriticalSection accessLock;
  11907. WaitableEvent waitEvent;
  11908. mutable int numWaitingWriters, numWriters;
  11909. mutable Thread::ThreadID writerThreadId;
  11910. mutable Array <Thread::ThreadID> readerThreads;
  11911. ReadWriteLock (const ReadWriteLock&);
  11912. const ReadWriteLock& operator= (const ReadWriteLock&);
  11913. };
  11914. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  11915. /********* End of inlined file: juce_ReadWriteLock.h *********/
  11916. #endif
  11917. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  11918. #endif
  11919. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11920. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  11921. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11922. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11923. /**
  11924. Automatically locks and unlocks a ReadWriteLock object.
  11925. Use one of these as a local variable to control access to a ReadWriteLock.
  11926. e.g. @code
  11927. ReadWriteLock myLock;
  11928. for (;;)
  11929. {
  11930. const ScopedReadLock myScopedLock (myLock);
  11931. // myLock is now locked
  11932. ...do some stuff...
  11933. // myLock gets unlocked here.
  11934. }
  11935. @endcode
  11936. @see ReadWriteLock, ScopedWriteLock
  11937. */
  11938. class JUCE_API ScopedReadLock
  11939. {
  11940. public:
  11941. /** Creates a ScopedReadLock.
  11942. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  11943. when the ScopedReadLock object is deleted, the ReadWriteLock will
  11944. be unlocked.
  11945. Make sure this object is created and deleted by the same thread,
  11946. otherwise there are no guarantees what will happen! Best just to use it
  11947. as a local stack object, rather than creating one with the new() operator.
  11948. */
  11949. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  11950. /** Destructor.
  11951. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  11952. Make sure this object is created and deleted by the same thread,
  11953. otherwise there are no guarantees what will happen!
  11954. */
  11955. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  11956. private:
  11957. const ReadWriteLock& lock_;
  11958. ScopedReadLock (const ScopedReadLock&);
  11959. const ScopedReadLock& operator= (const ScopedReadLock&);
  11960. };
  11961. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11962. /********* End of inlined file: juce_ScopedReadLock.h *********/
  11963. #endif
  11964. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11965. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  11966. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11967. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11968. /**
  11969. Automatically tries to lock and unlock a CriticalSection object.
  11970. Use one of these as a local variable to control access to a CriticalSection.
  11971. e.g. @code
  11972. CriticalSection myCriticalSection;
  11973. for (;;)
  11974. {
  11975. const ScopedTryLock myScopedTryLock (myCriticalSection);
  11976. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  11977. // should test this with the isLocked() method before doing your thread-unsafe
  11978. // action..
  11979. if (myScopedTryLock.isLocked())
  11980. {
  11981. ...do some stuff...
  11982. }
  11983. else
  11984. {
  11985. ..our attempt at locking failed because another thread had already locked it..
  11986. }
  11987. // myCriticalSection gets unlocked here (if it was locked)
  11988. }
  11989. @endcode
  11990. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  11991. */
  11992. class JUCE_API ScopedTryLock
  11993. {
  11994. public:
  11995. /** Creates a ScopedTryLock.
  11996. As soon as it is created, this will try to lock the CriticalSection, and
  11997. when the ScopedTryLock object is deleted, the CriticalSection will
  11998. be unlocked if the lock was successful.
  11999. Make sure this object is created and deleted by the same thread,
  12000. otherwise there are no guarantees what will happen! Best just to use it
  12001. as a local stack object, rather than creating one with the new() operator.
  12002. */
  12003. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  12004. /** Destructor.
  12005. The CriticalSection will be unlocked (if locked) when the destructor is called.
  12006. Make sure this object is created and deleted by the same thread,
  12007. otherwise there are no guarantees what will happen!
  12008. */
  12009. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  12010. /** Lock state
  12011. @return True if the CriticalSection is locked.
  12012. */
  12013. bool isLocked() const throw() { return lockWasSuccessful; }
  12014. private:
  12015. const CriticalSection& lock_;
  12016. const bool lockWasSuccessful;
  12017. ScopedTryLock (const ScopedTryLock&);
  12018. const ScopedTryLock& operator= (const ScopedTryLock&);
  12019. };
  12020. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12021. /********* End of inlined file: juce_ScopedTryLock.h *********/
  12022. #endif
  12023. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12024. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  12025. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12026. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12027. /**
  12028. Automatically locks and unlocks a ReadWriteLock object.
  12029. Use one of these as a local variable to control access to a ReadWriteLock.
  12030. e.g. @code
  12031. ReadWriteLock myLock;
  12032. for (;;)
  12033. {
  12034. const ScopedWriteLock myScopedLock (myLock);
  12035. // myLock is now locked
  12036. ...do some stuff...
  12037. // myLock gets unlocked here.
  12038. }
  12039. @endcode
  12040. @see ReadWriteLock, ScopedReadLock
  12041. */
  12042. class JUCE_API ScopedWriteLock
  12043. {
  12044. public:
  12045. /** Creates a ScopedWriteLock.
  12046. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  12047. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  12048. be unlocked.
  12049. Make sure this object is created and deleted by the same thread,
  12050. otherwise there are no guarantees what will happen! Best just to use it
  12051. as a local stack object, rather than creating one with the new() operator.
  12052. */
  12053. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  12054. /** Destructor.
  12055. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  12056. Make sure this object is created and deleted by the same thread,
  12057. otherwise there are no guarantees what will happen!
  12058. */
  12059. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  12060. private:
  12061. const ReadWriteLock& lock_;
  12062. ScopedWriteLock (const ScopedWriteLock&);
  12063. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  12064. };
  12065. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12066. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  12067. #endif
  12068. #ifndef __JUCE_THREAD_JUCEHEADER__
  12069. #endif
  12070. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  12071. /********* Start of inlined file: juce_ThreadPool.h *********/
  12072. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  12073. #define __JUCE_THREADPOOL_JUCEHEADER__
  12074. class ThreadPool;
  12075. class ThreadPoolThread;
  12076. /**
  12077. A task that is executed by a ThreadPool object.
  12078. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  12079. its threads.
  12080. The runJob() method needs to be implemented to do the task, and if the code that
  12081. does the work takes a significant time to run, it must keep checking the shouldExit()
  12082. method to see if something is trying to interrupt the job. If shouldExit() returns
  12083. true, the runJob() method must return immediately.
  12084. @see ThreadPool, Thread
  12085. */
  12086. class JUCE_API ThreadPoolJob
  12087. {
  12088. public:
  12089. /** Creates a thread pool job object.
  12090. After creating your job, add it to a thread pool with ThreadPool::addJob().
  12091. */
  12092. ThreadPoolJob (const String& name);
  12093. /** Destructor. */
  12094. virtual ~ThreadPoolJob();
  12095. /** Returns the name of this job.
  12096. @see setJobName
  12097. */
  12098. const String getJobName() const throw();
  12099. /** Changes the job's name.
  12100. @see getJobName
  12101. */
  12102. void setJobName (const String& newName) throw();
  12103. /** These are the values that can be returned by the runJob() method.
  12104. */
  12105. enum JobStatus
  12106. {
  12107. jobHasFinished = 0, /**< indicates that the job has finished and can be
  12108. removed from the pool. */
  12109. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  12110. should be automatically deleted by the pool. */
  12111. jobNeedsRunningAgain /**< indicates that the job would like to be called
  12112. again when a thread is free. */
  12113. };
  12114. /** Peforms the actual work that this job needs to do.
  12115. Your subclass must implement this method, in which is does its work.
  12116. If the code in this method takes a significant time to run, it must repeatedly check
  12117. the shouldExit() method to see if something is trying to interrupt the job.
  12118. If shouldExit() ever returns true, the runJob() method must return immediately.
  12119. If this method returns jobHasFinished, then the job will be removed from the pool
  12120. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  12121. pool and will get a chance to run again as soon as a thread is free.
  12122. @see shouldExit()
  12123. */
  12124. virtual JobStatus runJob() = 0;
  12125. /** Returns true if this job is currently running its runJob() method. */
  12126. bool isRunning() const throw() { return isActive; }
  12127. /** Returns true if something is trying to interrupt this job and make it stop.
  12128. Your runJob() method must call this whenever it gets a chance, and if it ever
  12129. returns true, the runJob() method must return immediately.
  12130. @see signalJobShouldExit()
  12131. */
  12132. bool shouldExit() const throw() { return shouldStop; }
  12133. /** Calling this will cause the shouldExit() method to return true, and the job
  12134. should (if it's been implemented correctly) stop as soon as possible.
  12135. @see shouldExit()
  12136. */
  12137. void signalJobShouldExit() throw();
  12138. juce_UseDebuggingNewOperator
  12139. private:
  12140. friend class ThreadPool;
  12141. friend class ThreadPoolThread;
  12142. String jobName;
  12143. ThreadPool* pool;
  12144. bool shouldStop, isActive, shouldBeDeleted;
  12145. ThreadPoolJob (const ThreadPoolJob&);
  12146. const ThreadPoolJob& operator= (const ThreadPoolJob&);
  12147. };
  12148. /**
  12149. A set of threads that will run a list of jobs.
  12150. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  12151. will be called by the next pooled thread that becomes free.
  12152. @see ThreadPoolJob, Thread
  12153. */
  12154. class JUCE_API ThreadPool
  12155. {
  12156. public:
  12157. /** Creates a thread pool.
  12158. Once you've created a pool, you can give it some things to do with the addJob()
  12159. method.
  12160. @param numberOfThreads the maximum number of actual threads to run.
  12161. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  12162. until there are some jobs to run. If false, then
  12163. all the threads will be fired-up immediately so that
  12164. they're ready for action
  12165. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  12166. inactive for this length of time, they will automatically
  12167. be stopped until more jobs come along and they're needed
  12168. */
  12169. ThreadPool (const int numberOfThreads,
  12170. const bool startThreadsOnlyWhenNeeded = true,
  12171. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  12172. /** Destructor.
  12173. This will attempt to remove all the jobs before deleting, but if you want to
  12174. specify a timeout, you should call removeAllJobs() explicitly before deleting
  12175. the pool.
  12176. */
  12177. ~ThreadPool();
  12178. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  12179. for some kind of operation.
  12180. @see ThreadPool::removeAllJobs
  12181. */
  12182. class JUCE_API JobSelector
  12183. {
  12184. public:
  12185. virtual ~JobSelector() {}
  12186. /** Should return true if the specified thread matches your criteria for whatever
  12187. operation that this object is being used for.
  12188. Any implementation of this method must be extremely fast and thread-safe!
  12189. */
  12190. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  12191. };
  12192. /** Adds a job to the queue.
  12193. Once a job has been added, then the next time a thread is free, it will run
  12194. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  12195. runJob() method, the pool will either remove the job from the pool or add it to
  12196. the back of the queue to be run again.
  12197. */
  12198. void addJob (ThreadPoolJob* const job);
  12199. /** Tries to remove a job from the pool.
  12200. If the job isn't yet running, this will simply remove it. If it is running, it
  12201. will wait for it to finish.
  12202. If the timeout period expires before the job finishes running, then the job will be
  12203. left in the pool and this will return false. It returns true if the job is sucessfully
  12204. stopped and removed.
  12205. @param job the job to remove
  12206. @param interruptIfRunning if true, then if the job is currently busy, its
  12207. ThreadPoolJob::signalJobShouldExit() method will be called to try
  12208. to interrupt it. If false, then if the job will be allowed to run
  12209. until it stops normally (or the timeout expires)
  12210. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  12211. before giving up and returning false
  12212. */
  12213. bool removeJob (ThreadPoolJob* const job,
  12214. const bool interruptIfRunning,
  12215. const int timeOutMilliseconds);
  12216. /** Tries to remove all jobs from the pool.
  12217. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  12218. methods called to try to interrupt them
  12219. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  12220. before giving up and returning false
  12221. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  12222. they will simply be removed from the pool. Jobs that are already running when
  12223. this method is called can choose whether they should be deleted by
  12224. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  12225. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  12226. jobs should be removed. If it is zero, all jobs are removed
  12227. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  12228. expires while waiting for one or more jobs to stop
  12229. */
  12230. bool removeAllJobs (const bool interruptRunningJobs,
  12231. const int timeOutMilliseconds,
  12232. const bool deleteInactiveJobs = false,
  12233. JobSelector* selectedJobsToRemove = 0);
  12234. /** Returns the number of jobs currently running or queued.
  12235. */
  12236. int getNumJobs() const throw();
  12237. /** Returns one of the jobs in the queue.
  12238. Note that this can be a very volatile list as jobs might be continuously getting shifted
  12239. around in the list, and this method may return 0 if the index is currently out-of-range.
  12240. */
  12241. ThreadPoolJob* getJob (const int index) const throw();
  12242. /** Returns true if the given job is currently queued or running.
  12243. @see isJobRunning()
  12244. */
  12245. bool contains (const ThreadPoolJob* const job) const throw();
  12246. /** Returns true if the given job is currently being run by a thread.
  12247. */
  12248. bool isJobRunning (const ThreadPoolJob* const job) const;
  12249. /** Waits until a job has finished running and has been removed from the pool.
  12250. This will wait until the job is no longer in the pool - i.e. until its
  12251. runJob() method returns ThreadPoolJob::jobHasFinished.
  12252. If the timeout period expires before the job finishes, this will return false;
  12253. it returns true if the job has finished successfully.
  12254. */
  12255. bool waitForJobToFinish (const ThreadPoolJob* const job,
  12256. const int timeOutMilliseconds) const;
  12257. /** Returns a list of the names of all the jobs currently running or queued.
  12258. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  12259. */
  12260. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const throw();
  12261. /** Changes the priority of all the threads.
  12262. This will call Thread::setPriority() for each thread in the pool.
  12263. May return false if for some reason the priority can't be changed.
  12264. */
  12265. bool setThreadPriorities (const int newPriority);
  12266. juce_UseDebuggingNewOperator
  12267. private:
  12268. const int numThreads, threadStopTimeout;
  12269. int priority;
  12270. Thread** threads;
  12271. VoidArray jobs;
  12272. CriticalSection lock;
  12273. uint32 lastJobEndTime;
  12274. WaitableEvent jobFinishedSignal;
  12275. friend class ThreadPoolThread;
  12276. bool runNextJob();
  12277. ThreadPool (const ThreadPool&);
  12278. const ThreadPool& operator= (const ThreadPool&);
  12279. };
  12280. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  12281. /********* End of inlined file: juce_ThreadPool.h *********/
  12282. #endif
  12283. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12284. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  12285. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12286. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12287. /**
  12288. Used by the TimeSliceThread class.
  12289. To register your class with a TimeSliceThread, derive from this class and
  12290. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  12291. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  12292. deleting your client!
  12293. @see TimeSliceThread
  12294. */
  12295. class JUCE_API TimeSliceClient
  12296. {
  12297. public:
  12298. /** Destructor. */
  12299. virtual ~TimeSliceClient() {}
  12300. /** Called back by a TimeSliceThread.
  12301. When you register this class with it, a TimeSliceThread will repeatedly call
  12302. this method.
  12303. The implementation of this method should use its time-slice to do something that's
  12304. quick - never block for longer than absolutely necessary.
  12305. @returns Your method should return true if it needs more time, or false if it's
  12306. not too busy and doesn't need calling back urgently. If all the thread's
  12307. clients indicate that they're not busy, then it'll save CPU by sleeping for
  12308. up to half a second in between callbacks. You can force the TimeSliceThread
  12309. to wake up and poll again immediately by calling its notify() method.
  12310. */
  12311. virtual bool useTimeSlice() = 0;
  12312. };
  12313. /**
  12314. A thread that keeps a list of clients, and calls each one in turn, giving them
  12315. all a chance to run some sort of short task.
  12316. @see TimeSliceClient, Thread
  12317. */
  12318. class JUCE_API TimeSliceThread : public Thread
  12319. {
  12320. public:
  12321. /**
  12322. Creates a TimeSliceThread.
  12323. When first created, the thread is not running. Use the startThread()
  12324. method to start it.
  12325. */
  12326. TimeSliceThread (const String& threadName);
  12327. /** Destructor.
  12328. Deleting a Thread object that is running will only give the thread a
  12329. brief opportunity to stop itself cleanly, so it's recommended that you
  12330. should always call stopThread() with a decent timeout before deleting,
  12331. to avoid the thread being forcibly killed (which is a Bad Thing).
  12332. */
  12333. ~TimeSliceThread();
  12334. /** Adds a client to the list.
  12335. The client's callbacks will start immediately (possibly before the method
  12336. has returned).
  12337. */
  12338. void addTimeSliceClient (TimeSliceClient* const client);
  12339. /** Removes a client from the list.
  12340. This method will make sure that all callbacks to the client have completely
  12341. finished before the method returns.
  12342. */
  12343. void removeTimeSliceClient (TimeSliceClient* const client);
  12344. /** Returns the number of registered clients. */
  12345. int getNumClients() const throw();
  12346. /** Returns one of the registered clients. */
  12347. TimeSliceClient* getClient (const int index) const throw();
  12348. /** @internal */
  12349. void run();
  12350. juce_UseDebuggingNewOperator
  12351. private:
  12352. CriticalSection callbackLock, listLock;
  12353. Array <TimeSliceClient*> clients;
  12354. int index;
  12355. TimeSliceClient* clientBeingCalled;
  12356. bool clientsChanged;
  12357. TimeSliceThread (const TimeSliceThread&);
  12358. const TimeSliceThread& operator= (const TimeSliceThread&);
  12359. };
  12360. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12361. /********* End of inlined file: juce_TimeSliceThread.h *********/
  12362. #endif
  12363. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  12364. #endif
  12365. #endif
  12366. /********* End of inlined file: juce_core_includes.h *********/
  12367. // if you're compiling a command-line app, you might want to just include the core headers,
  12368. // so you can set this macro before including juce.h
  12369. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12370. /********* Start of inlined file: juce_app_includes.h *********/
  12371. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  12372. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  12373. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  12374. /********* Start of inlined file: juce_Application.h *********/
  12375. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  12376. #define __JUCE_APPLICATION_JUCEHEADER__
  12377. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  12378. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  12379. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  12380. /********* Start of inlined file: juce_Component.h *********/
  12381. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  12382. #define __JUCE_COMPONENT_JUCEHEADER__
  12383. /********* Start of inlined file: juce_MouseCursor.h *********/
  12384. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  12385. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  12386. class Image;
  12387. class RefCountedMouseCursor;
  12388. class ComponentPeer;
  12389. class Component;
  12390. /**
  12391. Represents a mouse cursor image.
  12392. This object can either be used to represent one of the standard mouse
  12393. cursor shapes, or a custom one generated from an image.
  12394. */
  12395. class JUCE_API MouseCursor
  12396. {
  12397. public:
  12398. /** The set of available standard mouse cursors. */
  12399. enum StandardCursorType
  12400. {
  12401. NoCursor = 0, /**< An invisible cursor. */
  12402. NormalCursor, /**< The stardard arrow cursor. */
  12403. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  12404. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  12405. CrosshairCursor, /**< A pair of crosshairs. */
  12406. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  12407. that you're dragging a copy of something. */
  12408. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  12409. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  12410. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  12411. UpDownResizeCursor, /**< an arrow pointing up and down. */
  12412. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  12413. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  12414. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  12415. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  12416. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  12417. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  12418. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  12419. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  12420. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  12421. };
  12422. /** Creates the standard arrow cursor. */
  12423. MouseCursor() throw();
  12424. /** Creates one of the standard mouse cursor */
  12425. MouseCursor (const StandardCursorType type) throw();
  12426. /** Creates a custom cursor from an image.
  12427. @param image the image to use for the cursor - if this is bigger than the
  12428. system can manage, it might get scaled down first, and might
  12429. also have to be turned to black-and-white if it can't do colour
  12430. cursors.
  12431. @param hotSpotX the x position of the cursor's hotspot within the image
  12432. @param hotSpotY the y position of the cursor's hotspot within the image
  12433. */
  12434. MouseCursor (Image& image,
  12435. const int hotSpotX,
  12436. const int hotSpotY) throw();
  12437. /** Creates a copy of another cursor object. */
  12438. MouseCursor (const MouseCursor& other) throw();
  12439. /** Copies this cursor from another object. */
  12440. const MouseCursor& operator= (const MouseCursor& other) throw();
  12441. /** Destructor. */
  12442. ~MouseCursor() throw();
  12443. /** Checks whether two mouse cursors are the same.
  12444. For custom cursors, two cursors created from the same image won't be
  12445. recognised as the same, only MouseCursor objects that have been
  12446. copied from the same object.
  12447. */
  12448. bool operator== (const MouseCursor& other) const throw();
  12449. /** Checks whether two mouse cursors are the same.
  12450. For custom cursors, two cursors created from the same image won't be
  12451. recognised as the same, only MouseCursor objects that have been
  12452. copied from the same object.
  12453. */
  12454. bool operator!= (const MouseCursor& other) const throw();
  12455. /** Makes the system show its default 'busy' cursor.
  12456. This will turn the system cursor to an hourglass or spinning beachball
  12457. until the next time the mouse is moved, or hideWaitCursor() is called.
  12458. This is handy if the message loop is about to block for a couple of
  12459. seconds while busy and you want to give the user feedback about this.
  12460. @see MessageManager::setTimeBeforeShowingWaitCursor
  12461. */
  12462. static void showWaitCursor() throw();
  12463. /** If showWaitCursor has been called, this will return the mouse to its
  12464. normal state.
  12465. This will look at what component is under the mouse, and update the
  12466. cursor to be the correct one for that component.
  12467. @see showWaitCursor
  12468. */
  12469. static void hideWaitCursor() throw();
  12470. juce_UseDebuggingNewOperator
  12471. private:
  12472. RefCountedMouseCursor* cursorHandle;
  12473. friend class Component;
  12474. void showInWindow (ComponentPeer* window) const throw();
  12475. void showInAllWindows() const throw();
  12476. void* getHandle() const throw();
  12477. };
  12478. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  12479. /********* End of inlined file: juce_MouseCursor.h *********/
  12480. /********* Start of inlined file: juce_MouseListener.h *********/
  12481. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  12482. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  12483. /********* Start of inlined file: juce_MouseEvent.h *********/
  12484. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  12485. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  12486. class Component;
  12487. /********* Start of inlined file: juce_ModifierKeys.h *********/
  12488. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  12489. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  12490. /**
  12491. Represents the state of the mouse buttons and modifier keys.
  12492. This is used both by mouse events and by KeyPress objects to describe
  12493. the state of keys such as shift, control, alt, etc.
  12494. @see KeyPress, MouseEvent::mods
  12495. */
  12496. class JUCE_API ModifierKeys
  12497. {
  12498. public:
  12499. /** Creates a ModifierKeys object from a raw set of flags.
  12500. @param flags to represent the keys that are down
  12501. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  12502. rightButtonModifier, commandModifier, popupMenuClickModifier
  12503. */
  12504. ModifierKeys (const int flags = 0) throw();
  12505. /** Creates a copy of another object. */
  12506. ModifierKeys (const ModifierKeys& other) throw();
  12507. /** Copies this object from another one. */
  12508. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  12509. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  12510. This is a platform-agnostic way of checking for the operating system's
  12511. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  12512. Windows/Linux, it's actually checking for the CTRL key.
  12513. */
  12514. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  12515. /** Checks whether the user is trying to launch a pop-up menu.
  12516. This checks for platform-specific modifiers that might indicate that the user
  12517. is following the operating system's normal method of showing a pop-up menu.
  12518. So on Windows/Linux, this method is really testing for a right-click.
  12519. On the Mac, it tests for either the CTRL key being down, or a right-click.
  12520. */
  12521. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  12522. /** Checks whether the flag is set for the left mouse-button. */
  12523. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  12524. /** Checks whether the flag is set for the right mouse-button.
  12525. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  12526. this is platform-independent (and makes your code more explanatory too).
  12527. */
  12528. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  12529. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  12530. /** Tests for any of the mouse-button flags. */
  12531. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  12532. /** Tests for any of the modifier key flags. */
  12533. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  12534. /** Checks whether the shift key's flag is set. */
  12535. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  12536. /** Checks whether the CTRL key's flag is set.
  12537. Remember that it's better to use the platform-agnostic routines to test for command-key and
  12538. popup-menu modifiers.
  12539. @see isCommandDown, isPopupMenu
  12540. */
  12541. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  12542. /** Checks whether the shift key's flag is set. */
  12543. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  12544. /** Flags that represent the different keys. */
  12545. enum Flags
  12546. {
  12547. /** Shift key flag. */
  12548. shiftModifier = 1,
  12549. /** CTRL key flag. */
  12550. ctrlModifier = 2,
  12551. /** ALT key flag. */
  12552. altModifier = 4,
  12553. /** Left mouse button flag. */
  12554. leftButtonModifier = 16,
  12555. /** Right mouse button flag. */
  12556. rightButtonModifier = 32,
  12557. /** Middle mouse button flag. */
  12558. middleButtonModifier = 64,
  12559. #if JUCE_MAC
  12560. /** Command key flag - on windows this is the same as the CTRL key flag. */
  12561. commandModifier = 8,
  12562. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  12563. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  12564. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  12565. #else
  12566. /** Command key flag - on windows this is the same as the CTRL key flag. */
  12567. commandModifier = ctrlModifier,
  12568. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  12569. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  12570. popupMenuClickModifier = rightButtonModifier,
  12571. #endif
  12572. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  12573. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  12574. /** Represents a combination of all the mouse buttons at once. */
  12575. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  12576. };
  12577. /** Returns the raw flags for direct testing. */
  12578. inline int getRawFlags() const throw() { return flags; }
  12579. /** Tests a combination of flags and returns true if any of them are set. */
  12580. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12581. /** Creates a ModifierKeys object to represent the last-known state of the
  12582. keyboard and mouse buttons.
  12583. @see getCurrentModifiersRealtime
  12584. */
  12585. static const ModifierKeys getCurrentModifiers() throw();
  12586. /** Creates a ModifierKeys object to represent the current state of the
  12587. keyboard and mouse buttons.
  12588. This isn't often needed and isn't recommended, but will actively check all the
  12589. mouse and key states rather than just returning their last-known state like
  12590. getCurrentModifiers() does.
  12591. This is only needed in special circumstances for up-to-date modifier information
  12592. at times when the app's event loop isn't running normally.
  12593. */
  12594. static const ModifierKeys getCurrentModifiersRealtime() throw();
  12595. private:
  12596. int flags;
  12597. static int currentModifierFlags;
  12598. friend class ComponentPeer;
  12599. static void updateCurrentModifiers() throw();
  12600. };
  12601. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  12602. /********* End of inlined file: juce_ModifierKeys.h *********/
  12603. /**
  12604. Contains position and status information about a mouse event.
  12605. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  12606. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  12607. */
  12608. class JUCE_API MouseEvent
  12609. {
  12610. public:
  12611. /** Creates a MouseEvent.
  12612. Normally an application will never need to use this.
  12613. @param x the x position of the mouse, relative to the component that is passed-in
  12614. @param y the y position of the mouse, relative to the component that is passed-in
  12615. @param modifiers the key modifiers at the time of the event
  12616. @param originator the component that the mouse event applies to
  12617. @param eventTime the time the event happened
  12618. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  12619. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  12620. the same as the current mouse-x position.
  12621. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  12622. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  12623. the same as the current mouse-y position.
  12624. @param mouseDownTime the time at which the corresponding mouse-down event happened
  12625. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  12626. the same as the current mouse-event time.
  12627. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  12628. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  12629. */
  12630. MouseEvent (const int x, const int y,
  12631. const ModifierKeys& modifiers,
  12632. Component* const originator,
  12633. const Time& eventTime,
  12634. const int mouseDownX,
  12635. const int mouseDownY,
  12636. const Time& mouseDownTime,
  12637. const int numberOfClicks,
  12638. const bool mouseWasDragged) throw();
  12639. /** Destructor. */
  12640. ~MouseEvent() throw();
  12641. /** The x-position of the mouse when the event occurred.
  12642. This value is relative to the top-left of the component to which the
  12643. event applies (as indicated by the MouseEvent::eventComponent field).
  12644. */
  12645. int x;
  12646. /** The y-position of the mouse when the event occurred.
  12647. This value is relative to the top-left of the component to which the
  12648. event applies (as indicated by the MouseEvent::eventComponent field).
  12649. */
  12650. int y;
  12651. /** The key modifiers associated with the event.
  12652. This will let you find out which mouse buttons were down, as well as which
  12653. modifier keys were held down.
  12654. When used for mouse-up events, this will indicate the state of the mouse buttons
  12655. just before they were released, so that you can tell which button they let go of.
  12656. */
  12657. ModifierKeys mods;
  12658. /** The component that this event applies to.
  12659. This is usually the component that the mouse was over at the time, but for mouse-drag
  12660. events the mouse could actually be over a different component and the events are
  12661. still sent to the component that the button was originally pressed on.
  12662. The x and y member variables are relative to this component's position.
  12663. If you use getEventRelativeTo() to retarget this object to be relative to a different
  12664. component, this pointer will be updated, but originalComponent remains unchanged.
  12665. @see originalComponent
  12666. */
  12667. Component* eventComponent;
  12668. /** The component that the event first occurred on.
  12669. If you use getEventRelativeTo() to retarget this object to be relative to a different
  12670. component, this value remains unchanged to indicate the first component that received it.
  12671. @see eventComponent
  12672. */
  12673. Component* originalComponent;
  12674. /** The time that this mouse-event occurred.
  12675. */
  12676. Time eventTime;
  12677. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  12678. The co-ordinate is relative to the component specified in MouseEvent::component.
  12679. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  12680. */
  12681. int getMouseDownX() const throw();
  12682. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  12683. The co-ordinate is relative to the component specified in MouseEvent::component.
  12684. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  12685. */
  12686. int getMouseDownY() const throw();
  12687. /** Returns the straight-line distance between where the mouse is now and where it
  12688. was the last time the button was pressed.
  12689. This is quite handy for things like deciding whether the user has moved far enough
  12690. for it to be considered a drag operation.
  12691. @see getDistanceFromDragStartX
  12692. */
  12693. int getDistanceFromDragStart() const throw();
  12694. /** Returns the difference between the mouse's current x postion and where it was
  12695. when the button was last pressed.
  12696. @see getDistanceFromDragStart
  12697. */
  12698. int getDistanceFromDragStartX() const throw();
  12699. /** Returns the difference between the mouse's current y postion and where it was
  12700. when the button was last pressed.
  12701. @see getDistanceFromDragStart
  12702. */
  12703. int getDistanceFromDragStartY() const throw();
  12704. /** Returns true if the mouse has just been clicked.
  12705. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  12706. the user has dragged the mouse more than a few pixels from the place where the
  12707. mouse-down occurred.
  12708. Once they have dragged it far enough for this method to return false, it will continue
  12709. to return false until the mouse-up, even if they move the mouse back to the same
  12710. position where they originally pressed it. This means that it's very handy for
  12711. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  12712. callback to ignore any small movements they might make while clicking.
  12713. @returns true if the mouse wasn't dragged by more than a few pixels between
  12714. the last time the button was pressed and released.
  12715. */
  12716. bool mouseWasClicked() const throw();
  12717. /** For a click event, the number of times the mouse was clicked in succession.
  12718. So for example a double-click event will return 2, a triple-click 3, etc.
  12719. */
  12720. int getNumberOfClicks() const throw() { return numberOfClicks; }
  12721. /** Returns the time that the mouse button has been held down for.
  12722. If called from a mouseDrag or mouseUp callback, this will return the
  12723. number of milliseconds since the corresponding mouseDown event occurred.
  12724. If called in other contexts, e.g. a mouseMove, then the returned value
  12725. may be 0 or an undefined value.
  12726. */
  12727. int getLengthOfMousePress() const throw();
  12728. /** Returns the mouse x position of this event, in global screen co-ordinates.
  12729. The co-ordinates are relative to the top-left of the main monitor.
  12730. @see getMouseDownScreenX, Desktop::getMousePosition
  12731. */
  12732. int getScreenX() const throw();
  12733. /** Returns the mouse y position of this event, in global screen co-ordinates.
  12734. The co-ordinates are relative to the top-left of the main monitor.
  12735. @see getMouseDownScreenY, Desktop::getMousePosition
  12736. */
  12737. int getScreenY() const throw();
  12738. /** Returns the x co-ordinate at which the mouse button was last pressed.
  12739. The co-ordinates are relative to the top-left of the main monitor.
  12740. @see getScreenX, Desktop::getMousePosition
  12741. */
  12742. int getMouseDownScreenX() const throw();
  12743. /** Returns the y co-ordinate at which the mouse button was last pressed.
  12744. The co-ordinates are relative to the top-left of the main monitor.
  12745. @see getScreenY, Desktop::getMousePosition
  12746. */
  12747. int getMouseDownScreenY() const throw();
  12748. /** Creates a version of this event that is relative to a different component.
  12749. The x and y positions of the event that is returned will have been
  12750. adjusted to be relative to the new component.
  12751. */
  12752. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  12753. /** Changes the application-wide setting for the double-click time limit.
  12754. This is the maximum length of time between mouse-clicks for it to be
  12755. considered a double-click. It's used by the Component class.
  12756. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  12757. */
  12758. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  12759. /** Returns the application-wide setting for the double-click time limit.
  12760. This is the maximum length of time between mouse-clicks for it to be
  12761. considered a double-click. It's used by the Component class.
  12762. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  12763. */
  12764. static int getDoubleClickTimeout() throw();
  12765. juce_UseDebuggingNewOperator
  12766. private:
  12767. int mouseDownX, mouseDownY;
  12768. Time mouseDownTime;
  12769. int numberOfClicks;
  12770. bool wasMovedSinceMouseDown;
  12771. };
  12772. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  12773. /********* End of inlined file: juce_MouseEvent.h *********/
  12774. /**
  12775. A MouseListener can be registered with a component to receive callbacks
  12776. about mouse events that happen to that component.
  12777. @see Component::addMouseListener, Component::removeMouseListener
  12778. */
  12779. class JUCE_API MouseListener
  12780. {
  12781. public:
  12782. /** Destructor. */
  12783. virtual ~MouseListener() {}
  12784. /** Called when the mouse moves inside a component.
  12785. If the mouse button isn't pressed and the mouse moves over a component,
  12786. this will be called to let the component react to this.
  12787. A component will always get a mouseEnter callback before a mouseMove.
  12788. @param e details about the position and status of the mouse event, including
  12789. the source component in which it occurred
  12790. @see mouseEnter, mouseExit, mouseDrag, contains
  12791. */
  12792. virtual void mouseMove (const MouseEvent& e);
  12793. /** Called when the mouse first enters a component.
  12794. If the mouse button isn't pressed and the mouse moves into a component,
  12795. this will be called to let the component react to this.
  12796. When the mouse button is pressed and held down while being moved in
  12797. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  12798. mouseDrag messages are sent to the component that the mouse was originally
  12799. clicked on, until the button is released.
  12800. @param e details about the position and status of the mouse event, including
  12801. the source component in which it occurred
  12802. @see mouseExit, mouseDrag, mouseMove, contains
  12803. */
  12804. virtual void mouseEnter (const MouseEvent& e);
  12805. /** Called when the mouse moves out of a component.
  12806. This will be called when the mouse moves off the edge of this
  12807. component.
  12808. If the mouse button was pressed, and it was then dragged off the
  12809. edge of the component and released, then this callback will happen
  12810. when the button is released, after the mouseUp callback.
  12811. @param e details about the position and status of the mouse event, including
  12812. the source component in which it occurred
  12813. @see mouseEnter, mouseDrag, mouseMove, contains
  12814. */
  12815. virtual void mouseExit (const MouseEvent& e);
  12816. /** Called when a mouse button is pressed.
  12817. The MouseEvent object passed in contains lots of methods for finding out
  12818. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  12819. were held down at the time.
  12820. Once a button is held down, the mouseDrag method will be called when the
  12821. mouse moves, until the button is released.
  12822. @param e details about the position and status of the mouse event, including
  12823. the source component in which it occurred
  12824. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  12825. */
  12826. virtual void mouseDown (const MouseEvent& e);
  12827. /** Called when the mouse is moved while a button is held down.
  12828. When a mouse button is pressed inside a component, that component
  12829. receives mouseDrag callbacks each time the mouse moves, even if the
  12830. mouse strays outside the component's bounds.
  12831. @param e details about the position and status of the mouse event, including
  12832. the source component in which it occurred
  12833. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  12834. */
  12835. virtual void mouseDrag (const MouseEvent& e);
  12836. /** Called when a mouse button is released.
  12837. A mouseUp callback is sent to the component in which a button was pressed
  12838. even if the mouse is actually over a different component when the
  12839. button is released.
  12840. The MouseEvent object passed in contains lots of methods for finding out
  12841. which buttons were down just before they were released.
  12842. @param e details about the position and status of the mouse event, including
  12843. the source component in which it occurred
  12844. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  12845. */
  12846. virtual void mouseUp (const MouseEvent& e);
  12847. /** Called when a mouse button has been double-clicked on a component.
  12848. The MouseEvent object passed in contains lots of methods for finding out
  12849. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  12850. were held down at the time.
  12851. @param e details about the position and status of the mouse event, including
  12852. the source component in which it occurred
  12853. @see mouseDown, mouseUp
  12854. */
  12855. virtual void mouseDoubleClick (const MouseEvent& e);
  12856. /** Called when the mouse-wheel is moved.
  12857. This callback is sent to the component that the mouse is over when the
  12858. wheel is moved.
  12859. If not overridden, the component will forward this message to its parent, so
  12860. that parent components can collect mouse-wheel messages that happen to
  12861. child components which aren't interested in them.
  12862. @param e details about the position and status of the mouse event, including
  12863. the source component in which it occurred
  12864. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  12865. value means the wheel has been pushed to the right, negative means it
  12866. was pushed to the left
  12867. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  12868. value means the wheel has been pushed upwards, negative means it
  12869. was pushed downwards
  12870. */
  12871. virtual void mouseWheelMove (const MouseEvent& e,
  12872. float wheelIncrementX,
  12873. float wheelIncrementY);
  12874. };
  12875. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  12876. /********* End of inlined file: juce_MouseListener.h *********/
  12877. /********* Start of inlined file: juce_ComponentListener.h *********/
  12878. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12879. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12880. class Component;
  12881. /**
  12882. Gets informed about changes to a component's hierarchy or position.
  12883. To monitor a component for changes, register a subclass of ComponentListener
  12884. with the component using Component::addComponentListener().
  12885. Be sure to deregister listeners before you delete them!
  12886. @see Component::addComponentListener, Component::removeComponentListener
  12887. */
  12888. class JUCE_API ComponentListener
  12889. {
  12890. public:
  12891. /** Destructor. */
  12892. virtual ~ComponentListener() {}
  12893. /** Called when the component's position or size changes.
  12894. @param component the component that was moved or resized
  12895. @param wasMoved true if the component's top-left corner has just moved
  12896. @param wasResized true if the component's width or height has just changed
  12897. @see Component::setBounds, Component::resized, Component::moved
  12898. */
  12899. virtual void componentMovedOrResized (Component& component,
  12900. bool wasMoved,
  12901. bool wasResized);
  12902. /** Called when the component is brought to the top of the z-order.
  12903. @param component the component that was moved
  12904. @see Component::toFront, Component::broughtToFront
  12905. */
  12906. virtual void componentBroughtToFront (Component& component);
  12907. /** Called when the component is made visible or invisible.
  12908. @param component the component that changed
  12909. @see Component::setVisible
  12910. */
  12911. virtual void componentVisibilityChanged (Component& component);
  12912. /** Called when the component has children added or removed.
  12913. @param component the component whose children were changed
  12914. @see Component::childrenChanged, Component::addChildComponent,
  12915. Component::removeChildComponent
  12916. */
  12917. virtual void componentChildrenChanged (Component& component);
  12918. /** Called to indicate that the component's parents have changed.
  12919. When a component is added or removed from its parent, all of its children
  12920. will produce this notification (recursively - so all children of its
  12921. children will also be called as well).
  12922. @param component the component that this listener is registered with
  12923. @see Component::parentHierarchyChanged
  12924. */
  12925. virtual void componentParentHierarchyChanged (Component& component);
  12926. /** Called when the component's name is changed.
  12927. @see Component::setName, Component::getName
  12928. */
  12929. virtual void componentNameChanged (Component& component);
  12930. };
  12931. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12932. /********* End of inlined file: juce_ComponentListener.h *********/
  12933. /********* Start of inlined file: juce_KeyListener.h *********/
  12934. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  12935. #define __JUCE_KEYLISTENER_JUCEHEADER__
  12936. /********* Start of inlined file: juce_KeyPress.h *********/
  12937. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  12938. #define __JUCE_KEYPRESS_JUCEHEADER__
  12939. /**
  12940. Represents a key press, including any modifier keys that are needed.
  12941. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  12942. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  12943. */
  12944. class JUCE_API KeyPress
  12945. {
  12946. public:
  12947. /** Creates an (invalid) KeyPress.
  12948. @see isValid
  12949. */
  12950. KeyPress() throw();
  12951. /** Creates a KeyPress for a key and some modifiers.
  12952. e.g.
  12953. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  12954. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  12955. @param keyCode a code that represents the key - this value must be
  12956. one of special constants listed in this class, or an
  12957. 8-bit character code such as a letter (case is ignored),
  12958. digit or a simple key like "," or ".". Note that this
  12959. isn't the same as the textCharacter parameter, so for example
  12960. a keyCode of 'a' and a shift-key modifier should have a
  12961. textCharacter value of 'A'.
  12962. @param modifiers the modifiers to associate with the keystroke
  12963. @param textCharacter the character that would be printed if someone typed
  12964. this keypress into a text editor. This value may be
  12965. null if the keypress is a non-printing character
  12966. @see getKeyCode, isKeyCode, getModifiers
  12967. */
  12968. KeyPress (const int keyCode,
  12969. const ModifierKeys& modifiers,
  12970. const juce_wchar textCharacter) throw();
  12971. /** Creates a keypress with a keyCode but no modifiers or text character.
  12972. */
  12973. KeyPress (const int keyCode) throw();
  12974. /** Creates a copy of another KeyPress. */
  12975. KeyPress (const KeyPress& other) throw();
  12976. /** Copies this KeyPress from another one. */
  12977. const KeyPress& operator= (const KeyPress& other) throw();
  12978. /** Compares two KeyPress objects. */
  12979. bool operator== (const KeyPress& other) const throw();
  12980. /** Compares two KeyPress objects. */
  12981. bool operator!= (const KeyPress& other) const throw();
  12982. /** Returns true if this is a valid KeyPress.
  12983. A null keypress can be created by the default constructor, in case it's
  12984. needed.
  12985. */
  12986. bool isValid() const throw() { return keyCode != 0; }
  12987. /** Returns the key code itself.
  12988. This will either be one of the special constants defined in this class,
  12989. or an 8-bit character code.
  12990. */
  12991. int getKeyCode() const throw() { return keyCode; }
  12992. /** Returns the key modifiers.
  12993. @see ModifierKeys
  12994. */
  12995. const ModifierKeys getModifiers() const throw() { return mods; }
  12996. /** Returns the character that is associated with this keypress.
  12997. This is the character that you'd expect to see printed if you press this
  12998. keypress in a text editor or similar component.
  12999. */
  13000. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  13001. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  13002. the modifiers.
  13003. The values for key codes can either be one of the special constants defined in
  13004. this class, or an 8-bit character code.
  13005. @see getKeyCode
  13006. */
  13007. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  13008. /** Converts a textual key description to a KeyPress.
  13009. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  13010. This isn't designed to cope with any kind of input, but should be given the
  13011. strings that are created by the getTextDescription() method.
  13012. If the string can't be parsed, the object returned will be invalid.
  13013. @see getTextDescription
  13014. */
  13015. static const KeyPress createFromDescription (const String& textVersion) throw();
  13016. /** Creates a textual description of the key combination.
  13017. e.g. "CTRL + C" or "DELETE".
  13018. To store a keypress in a file, use this method, along with createFromDescription()
  13019. to retrieve it later.
  13020. */
  13021. const String getTextDescription() const throw();
  13022. /** Checks whether the user is currently holding down the keys that make up this
  13023. KeyPress.
  13024. Note that this will return false if any extra modifier keys are
  13025. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  13026. then it will be false.
  13027. */
  13028. bool isCurrentlyDown() const throw();
  13029. /** Checks whether a particular key is held down, irrespective of modifiers.
  13030. The values for key codes can either be one of the special constants defined in
  13031. this class, or an 8-bit character code.
  13032. */
  13033. static bool isKeyCurrentlyDown (int keyCode) throw();
  13034. // Key codes
  13035. //
  13036. // Note that the actual values of these are platform-specific and may change
  13037. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  13038. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  13039. //
  13040. static const int spaceKey; /**< key-code for the space bar */
  13041. static const int escapeKey; /**< key-code for the escape key */
  13042. static const int returnKey; /**< key-code for the return key*/
  13043. static const int tabKey; /**< key-code for the tab key*/
  13044. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  13045. static const int backspaceKey; /**< key-code for the backspace key */
  13046. static const int insertKey; /**< key-code for the insert key */
  13047. static const int upKey; /**< key-code for the cursor-up key */
  13048. static const int downKey; /**< key-code for the cursor-down key */
  13049. static const int leftKey; /**< key-code for the cursor-left key */
  13050. static const int rightKey; /**< key-code for the cursor-right key */
  13051. static const int pageUpKey; /**< key-code for the page-up key */
  13052. static const int pageDownKey; /**< key-code for the page-down key */
  13053. static const int homeKey; /**< key-code for the home key */
  13054. static const int endKey; /**< key-code for the end key */
  13055. static const int F1Key; /**< key-code for the F1 key */
  13056. static const int F2Key; /**< key-code for the F2 key */
  13057. static const int F3Key; /**< key-code for the F3 key */
  13058. static const int F4Key; /**< key-code for the F4 key */
  13059. static const int F5Key; /**< key-code for the F5 key */
  13060. static const int F6Key; /**< key-code for the F6 key */
  13061. static const int F7Key; /**< key-code for the F7 key */
  13062. static const int F8Key; /**< key-code for the F8 key */
  13063. static const int F9Key; /**< key-code for the F9 key */
  13064. static const int F10Key; /**< key-code for the F10 key */
  13065. static const int F11Key; /**< key-code for the F11 key */
  13066. static const int F12Key; /**< key-code for the F12 key */
  13067. static const int F13Key; /**< key-code for the F13 key */
  13068. static const int F14Key; /**< key-code for the F14 key */
  13069. static const int F15Key; /**< key-code for the F15 key */
  13070. static const int F16Key; /**< key-code for the F16 key */
  13071. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  13072. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  13073. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  13074. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  13075. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  13076. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  13077. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  13078. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  13079. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  13080. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  13081. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  13082. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  13083. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  13084. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  13085. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  13086. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  13087. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  13088. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  13089. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  13090. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  13091. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  13092. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  13093. juce_UseDebuggingNewOperator
  13094. private:
  13095. int keyCode;
  13096. ModifierKeys mods;
  13097. juce_wchar textCharacter;
  13098. };
  13099. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  13100. /********* End of inlined file: juce_KeyPress.h *********/
  13101. class Component;
  13102. /**
  13103. Receives callbacks when keys are pressed.
  13104. You can add a key listener to a component to be informed when that component
  13105. gets key events. See the Component::addListener method for more details.
  13106. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  13107. */
  13108. class JUCE_API KeyListener
  13109. {
  13110. public:
  13111. /** Destructor. */
  13112. virtual ~KeyListener() {}
  13113. /** Called to indicate that a key has been pressed.
  13114. If your implementation returns true, then the key event is considered to have
  13115. been consumed, and will not be passed on to any other components. If it returns
  13116. false, then the key will be passed to other components that might want to use it.
  13117. @param key the keystroke, including modifier keys
  13118. @param originatingComponent the component that received the key event
  13119. @see keyStateChanged, Component::keyPressed
  13120. */
  13121. virtual bool keyPressed (const KeyPress& key,
  13122. Component* originatingComponent) = 0;
  13123. /** Called when any key is pressed or released.
  13124. When this is called, classes that might be interested in
  13125. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  13126. check whether their key has changed.
  13127. If your implementation returns true, then the key event is considered to have
  13128. been consumed, and will not be passed on to any other components. If it returns
  13129. false, then the key will be passed to other components that might want to use it.
  13130. @param originatingComponent the component that received the key event
  13131. @param isKeyDown true if a key is being pressed, false if one is being released
  13132. @see KeyPress, Component::keyStateChanged
  13133. */
  13134. virtual bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  13135. };
  13136. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  13137. /********* End of inlined file: juce_KeyListener.h *********/
  13138. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  13139. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13140. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13141. class Component;
  13142. /**
  13143. Controls the order in which focus moves between components.
  13144. The default algorithm used by this class to work out the order of traversal
  13145. is as follows:
  13146. - if two components both have an explicit focus order specified, then the
  13147. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  13148. method).
  13149. - any component with an explicit focus order greater than 0 comes before ones
  13150. that don't have an order specified.
  13151. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  13152. order.
  13153. If you need traversal in a more customised way, you can create a subclass
  13154. of KeyboardFocusTraverser that uses your own algorithm, and use
  13155. Component::createFocusTraverser() to create it.
  13156. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  13157. */
  13158. class JUCE_API KeyboardFocusTraverser
  13159. {
  13160. public:
  13161. KeyboardFocusTraverser();
  13162. /** Destructor. */
  13163. virtual ~KeyboardFocusTraverser();
  13164. /** Returns the component that should be given focus after the specified one
  13165. when moving "forwards".
  13166. The default implementation will return the next component which is to the
  13167. right of or below this one.
  13168. This may return 0 if there's no suitable candidate.
  13169. */
  13170. virtual Component* getNextComponent (Component* current);
  13171. /** Returns the component that should be given focus after the specified one
  13172. when moving "backwards".
  13173. The default implementation will return the next component which is to the
  13174. left of or above this one.
  13175. This may return 0 if there's no suitable candidate.
  13176. */
  13177. virtual Component* getPreviousComponent (Component* current);
  13178. /** Returns the component that should receive focus be default within the given
  13179. parent component.
  13180. The default implementation will just return the foremost child component that
  13181. wants focus.
  13182. This may return 0 if there's no suitable candidate.
  13183. */
  13184. virtual Component* getDefaultComponent (Component* parentComponent);
  13185. };
  13186. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13187. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  13188. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  13189. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  13190. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  13191. /********* Start of inlined file: juce_Graphics.h *********/
  13192. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  13193. #define __JUCE_GRAPHICS_JUCEHEADER__
  13194. /********* Start of inlined file: juce_Font.h *********/
  13195. #ifndef __JUCE_FONT_JUCEHEADER__
  13196. #define __JUCE_FONT_JUCEHEADER__
  13197. /********* Start of inlined file: juce_Typeface.h *********/
  13198. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  13199. #define __JUCE_TYPEFACE_JUCEHEADER__
  13200. /********* Start of inlined file: juce_Path.h *********/
  13201. #ifndef __JUCE_PATH_JUCEHEADER__
  13202. #define __JUCE_PATH_JUCEHEADER__
  13203. /********* Start of inlined file: juce_AffineTransform.h *********/
  13204. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13205. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13206. /**
  13207. Represents a 2D affine-transformation matrix.
  13208. An affine transformation is a transformation such as a rotation, scale, shear,
  13209. resize or translation.
  13210. These are used for various 2D transformation tasks, e.g. with Path objects.
  13211. @see Path, Point, Line
  13212. */
  13213. class JUCE_API AffineTransform
  13214. {
  13215. public:
  13216. /** Creates an identity transform. */
  13217. AffineTransform() throw();
  13218. /** Creates a copy of another transform. */
  13219. AffineTransform (const AffineTransform& other) throw();
  13220. /** Creates a transform from a set of raw matrix values.
  13221. The resulting matrix is:
  13222. (mat00 mat01 mat02)
  13223. (mat10 mat11 mat12)
  13224. ( 0 0 1 )
  13225. */
  13226. AffineTransform (const float mat00, const float mat01, const float mat02,
  13227. const float mat10, const float mat11, const float mat12) throw();
  13228. /** Copies from another AffineTransform object */
  13229. const AffineTransform& operator= (const AffineTransform& other) throw();
  13230. /** Compares two transforms. */
  13231. bool operator== (const AffineTransform& other) const throw();
  13232. /** Compares two transforms. */
  13233. bool operator!= (const AffineTransform& other) const throw();
  13234. /** A ready-to-use identity transform, which you can use to append other
  13235. transformations to.
  13236. e.g. @code
  13237. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  13238. .scaled (2.0f);
  13239. @endcode
  13240. */
  13241. static const AffineTransform identity;
  13242. /** Transforms a 2D co-ordinate using this matrix. */
  13243. void transformPoint (float& x,
  13244. float& y) const throw();
  13245. /** Transforms a 2D co-ordinate using this matrix. */
  13246. void transformPoint (double& x,
  13247. double& y) const throw();
  13248. /** Returns a new transform which is the same as this one followed by a translation. */
  13249. const AffineTransform translated (const float deltaX,
  13250. const float deltaY) const throw();
  13251. /** Returns a new transform which is a translation. */
  13252. static const AffineTransform translation (const float deltaX,
  13253. const float deltaY) throw();
  13254. /** Returns a transform which is the same as this one followed by a rotation.
  13255. The rotation is specified by a number of radians to rotate clockwise, centred around
  13256. the origin (0, 0).
  13257. */
  13258. const AffineTransform rotated (const float angleInRadians) const throw();
  13259. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  13260. The rotation is specified by a number of radians to rotate clockwise, centred around
  13261. the co-ordinates passed in.
  13262. */
  13263. const AffineTransform rotated (const float angleInRadians,
  13264. const float pivotX,
  13265. const float pivotY) const throw();
  13266. /** Returns a new transform which is a rotation about (0, 0). */
  13267. static const AffineTransform rotation (const float angleInRadians) throw();
  13268. /** Returns a new transform which is a rotation about a given point. */
  13269. static const AffineTransform rotation (const float angleInRadians,
  13270. const float pivotX,
  13271. const float pivotY) throw();
  13272. /** Returns a transform which is the same as this one followed by a re-scaling.
  13273. The scaling is centred around the origin (0, 0).
  13274. */
  13275. const AffineTransform scaled (const float factorX,
  13276. const float factorY) const throw();
  13277. /** Returns a new transform which is a re-scale about the origin. */
  13278. static const AffineTransform scale (const float factorX,
  13279. const float factorY) throw();
  13280. /** Returns a transform which is the same as this one followed by a shear.
  13281. The shear is centred around the origin (0, 0).
  13282. */
  13283. const AffineTransform sheared (const float shearX,
  13284. const float shearY) const throw();
  13285. /** Returns a matrix which is the inverse operation of this one.
  13286. Some matrices don't have an inverse - in this case, the method will just return
  13287. an identity transform.
  13288. */
  13289. const AffineTransform inverted() const throw();
  13290. /** Returns the result of concatenating another transformation after this one. */
  13291. const AffineTransform followedBy (const AffineTransform& other) const throw();
  13292. /** Returns true if this transform has no effect on points. */
  13293. bool isIdentity() const throw();
  13294. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  13295. bool isSingularity() const throw();
  13296. /** Returns true if the transform only translates, and doesn't scale or rotate the
  13297. points. */
  13298. bool isOnlyTranslation() const throw();
  13299. /** If this transform is only a translation, this returns the X offset.
  13300. @see isOnlyTranslation
  13301. */
  13302. float getTranslationX() const throw() { return mat02; }
  13303. /** If this transform is only a translation, this returns the X offset.
  13304. @see isOnlyTranslation
  13305. */
  13306. float getTranslationY() const throw() { return mat12; }
  13307. juce_UseDebuggingNewOperator
  13308. /* The transform matrix is:
  13309. (mat00 mat01 mat02)
  13310. (mat10 mat11 mat12)
  13311. ( 0 0 1 )
  13312. */
  13313. float mat00, mat01, mat02;
  13314. float mat10, mat11, mat12;
  13315. private:
  13316. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  13317. const float mat10, const float mat11, const float mat12) const throw();
  13318. };
  13319. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13320. /********* End of inlined file: juce_AffineTransform.h *********/
  13321. /********* Start of inlined file: juce_Point.h *********/
  13322. #ifndef __JUCE_POINT_JUCEHEADER__
  13323. #define __JUCE_POINT_JUCEHEADER__
  13324. /**
  13325. A pair of (x, y) co-ordinates.
  13326. Uses 32-bit floating point accuracy.
  13327. @see Line, Path, AffineTransform
  13328. */
  13329. class JUCE_API Point
  13330. {
  13331. public:
  13332. /** Creates a point with co-ordinates (0, 0). */
  13333. Point() throw();
  13334. /** Creates a copy of another point. */
  13335. Point (const Point& other) throw();
  13336. /** Creates a point from an (x, y) position. */
  13337. Point (const float x, const float y) throw();
  13338. /** Copies this point from another one.
  13339. @see setXY
  13340. */
  13341. const Point& operator= (const Point& other) throw();
  13342. /** Destructor. */
  13343. ~Point() throw();
  13344. /** Returns the point's x co-ordinate. */
  13345. inline float getX() const throw() { return x; }
  13346. /** Returns the point's y co-ordinate. */
  13347. inline float getY() const throw() { return y; }
  13348. /** Changes the point's x and y co-ordinates. */
  13349. void setXY (const float x,
  13350. const float y) throw();
  13351. /** Uses a transform to change the point's co-ordinates.
  13352. @see AffineTransform::transformPoint
  13353. */
  13354. void applyTransform (const AffineTransform& transform) throw();
  13355. juce_UseDebuggingNewOperator
  13356. private:
  13357. float x, y;
  13358. };
  13359. #endif // __JUCE_POINT_JUCEHEADER__
  13360. /********* End of inlined file: juce_Point.h *********/
  13361. /********* Start of inlined file: juce_Rectangle.h *********/
  13362. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13363. #define __JUCE_RECTANGLE_JUCEHEADER__
  13364. /**
  13365. A rectangle, specified using integer co-ordinates.
  13366. @see RectangleList, Path, Line, Point
  13367. */
  13368. class JUCE_API Rectangle
  13369. {
  13370. public:
  13371. /** Creates a rectangle of zero size.
  13372. The default co-ordinates will be (0, 0, 0, 0).
  13373. */
  13374. Rectangle() throw();
  13375. /** Creates a copy of another rectangle. */
  13376. Rectangle (const Rectangle& other) throw();
  13377. /** Creates a rectangle with a given position and size. */
  13378. Rectangle (const int x, const int y,
  13379. const int width, const int height) throw();
  13380. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13381. Rectangle (const int width, const int height) throw();
  13382. /** Destructor. */
  13383. ~Rectangle() throw();
  13384. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13385. inline int getX() const throw() { return x; }
  13386. /** Returns the y co-ordinate of the rectangle's top edge. */
  13387. inline int getY() const throw() { return y; }
  13388. /** Returns the width of the rectangle. */
  13389. inline int getWidth() const throw() { return w; }
  13390. /** Returns the height of the rectangle. */
  13391. inline int getHeight() const throw() { return h; }
  13392. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13393. inline int getRight() const throw() { return x + w; }
  13394. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13395. inline int getBottom() const throw() { return y + h; }
  13396. /** Returns the x co-ordinate of the rectangle's centre. */
  13397. inline int getCentreX() const throw() { return x + (w >> 1); }
  13398. /** Returns the y co-ordinate of the rectangle's centre. */
  13399. inline int getCentreY() const throw() { return y + (h >> 1); }
  13400. /** Returns true if the rectangle's width and height are both zero or less */
  13401. bool isEmpty() const throw();
  13402. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13403. void setPosition (const int x, const int y) throw();
  13404. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13405. void setSize (const int w, const int h) throw();
  13406. /** Changes all the rectangle's co-ordinates. */
  13407. void setBounds (const int newX, const int newY,
  13408. const int newWidth, const int newHeight) throw();
  13409. /** Changes the rectangle's width */
  13410. void setWidth (const int newWidth) throw();
  13411. /** Changes the rectangle's height */
  13412. void setHeight (const int newHeight) throw();
  13413. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  13414. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  13415. */
  13416. void setLeft (const int newLeft) throw();
  13417. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  13418. If the y is moved to be below the current bottom edge, the height will be set to zero.
  13419. */
  13420. void setTop (const int newTop) throw();
  13421. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  13422. If the new right is below the current X value, the X will be pushed down to match it.
  13423. @see getRight
  13424. */
  13425. void setRight (const int newRight) throw();
  13426. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  13427. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  13428. @see getBottom
  13429. */
  13430. void setBottom (const int newBottom) throw();
  13431. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13432. void translate (const int deltaX,
  13433. const int deltaY) throw();
  13434. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13435. const Rectangle translated (const int deltaX,
  13436. const int deltaY) const throw();
  13437. /** Expands the rectangle by a given amount.
  13438. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13439. @see expanded, reduce, reduced
  13440. */
  13441. void expand (const int deltaX,
  13442. const int deltaY) throw();
  13443. /** Returns a rectangle that is larger than this one by a given amount.
  13444. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13445. @see expand, reduce, reduced
  13446. */
  13447. const Rectangle expanded (const int deltaX,
  13448. const int deltaY) const throw();
  13449. /** Shrinks the rectangle by a given amount.
  13450. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13451. @see reduced, expand, expanded
  13452. */
  13453. void reduce (const int deltaX,
  13454. const int deltaY) throw();
  13455. /** Returns a rectangle that is smaller than this one by a given amount.
  13456. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13457. @see reduce, expand, expanded
  13458. */
  13459. const Rectangle reduced (const int deltaX,
  13460. const int deltaY) const throw();
  13461. /** Returns true if the two rectangles are identical. */
  13462. bool operator== (const Rectangle& other) const throw();
  13463. /** Returns true if the two rectangles are not identical. */
  13464. bool operator!= (const Rectangle& other) const throw();
  13465. /** Returns true if this co-ordinate is inside the rectangle. */
  13466. bool contains (const int x, const int y) const throw();
  13467. /** Returns true if this other rectangle is completely inside this one. */
  13468. bool contains (const Rectangle& other) const throw();
  13469. /** Returns true if any part of another rectangle overlaps this one. */
  13470. bool intersects (const Rectangle& other) const throw();
  13471. /** Returns the region that is the overlap between this and another rectangle.
  13472. If the two rectangles don't overlap, the rectangle returned will be empty.
  13473. */
  13474. const Rectangle getIntersection (const Rectangle& other) const throw();
  13475. /** Clips a rectangle so that it lies only within this one.
  13476. This is a non-static version of intersectRectangles().
  13477. Returns false if the two regions didn't overlap.
  13478. */
  13479. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13480. /** Returns the smallest rectangle that contains both this one and the one
  13481. passed-in.
  13482. */
  13483. const Rectangle getUnion (const Rectangle& other) const throw();
  13484. /** If this rectangle merged with another one results in a simple rectangle, this
  13485. will set this rectangle to the result, and return true.
  13486. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13487. or if they form a complex region.
  13488. */
  13489. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13490. /** If after removing another rectangle from this one the result is a simple rectangle,
  13491. this will set this object's bounds to be the result, and return true.
  13492. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13493. or if removing the other one would form a complex region.
  13494. */
  13495. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13496. /** Static utility to intersect two sets of rectangular co-ordinates.
  13497. Returns false if the two regions didn't overlap.
  13498. @see intersectRectangle
  13499. */
  13500. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13501. int x2, int y2, int w2, int h2) throw();
  13502. /** Creates a string describing this rectangle.
  13503. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13504. Coupled with the fromString() method, this is very handy for things like
  13505. storing rectangles (particularly component positions) in XML attributes.
  13506. @see fromString
  13507. */
  13508. const String toString() const throw();
  13509. /** Parses a string containing a rectangle's details.
  13510. The string should contain 4 integer tokens, in the form "x y width height". They
  13511. can be comma or whitespace separated.
  13512. This method is intended to go with the toString() method, to form an easy way
  13513. of saving/loading rectangles as strings.
  13514. @see toString
  13515. */
  13516. static const Rectangle fromString (const String& stringVersion);
  13517. juce_UseDebuggingNewOperator
  13518. private:
  13519. friend class RectangleList;
  13520. int x, y, w, h;
  13521. };
  13522. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13523. /********* End of inlined file: juce_Rectangle.h *********/
  13524. /********* Start of inlined file: juce_Justification.h *********/
  13525. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  13526. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  13527. /**
  13528. Represents a type of justification to be used when positioning graphical items.
  13529. e.g. it indicates whether something should be placed top-left, top-right,
  13530. centred, etc.
  13531. It is used in various places wherever this kind of information is needed.
  13532. */
  13533. class JUCE_API Justification
  13534. {
  13535. public:
  13536. /** Creates a Justification object using a combination of flags. */
  13537. inline Justification (const int flags_) throw() : flags (flags_) {}
  13538. /** Creates a copy of another Justification object. */
  13539. Justification (const Justification& other) throw();
  13540. /** Copies another Justification object. */
  13541. const Justification& operator= (const Justification& other) throw();
  13542. /** Returns the raw flags that are set for this Justification object. */
  13543. inline int getFlags() const throw() { return flags; }
  13544. /** Tests a set of flags for this object.
  13545. @returns true if any of the flags passed in are set on this object.
  13546. */
  13547. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  13548. /** Returns just the flags from this object that deal with vertical layout. */
  13549. int getOnlyVerticalFlags() const throw();
  13550. /** Returns just the flags from this object that deal with horizontal layout. */
  13551. int getOnlyHorizontalFlags() const throw();
  13552. /** Adjusts the position of a rectangle to fit it into a space.
  13553. The (x, y) position of the rectangle will be updated to position it inside the
  13554. given space according to the justification flags.
  13555. */
  13556. void applyToRectangle (int& x, int& y,
  13557. const int w, const int h,
  13558. const int spaceX, const int spaceY,
  13559. const int spaceW, const int spaceH) const throw();
  13560. /** Flag values that can be combined and used in the constructor. */
  13561. enum
  13562. {
  13563. /** Indicates that the item should be aligned against the left edge of the available space. */
  13564. left = 1,
  13565. /** Indicates that the item should be aligned against the right edge of the available space. */
  13566. right = 2,
  13567. /** Indicates that the item should be placed in the centre between the left and right
  13568. sides of the available space. */
  13569. horizontallyCentred = 4,
  13570. /** Indicates that the item should be aligned against the top edge of the available space. */
  13571. top = 8,
  13572. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  13573. bottom = 16,
  13574. /** Indicates that the item should be placed in the centre between the top and bottom
  13575. sides of the available space. */
  13576. verticallyCentred = 32,
  13577. /** Indicates that lines of text should be spread out to fill the maximum width
  13578. available, so that both margins are aligned vertically.
  13579. */
  13580. horizontallyJustified = 64,
  13581. /** Indicates that the item should be centred vertically and horizontally.
  13582. This is equivalent to (horizontallyCentred | verticallyCentred)
  13583. */
  13584. centred = 36,
  13585. /** Indicates that the item should be centred vertically but placed on the left hand side.
  13586. This is equivalent to (left | verticallyCentred)
  13587. */
  13588. centredLeft = 33,
  13589. /** Indicates that the item should be centred vertically but placed on the right hand side.
  13590. This is equivalent to (right | verticallyCentred)
  13591. */
  13592. centredRight = 34,
  13593. /** Indicates that the item should be centred horizontally and placed at the top.
  13594. This is equivalent to (horizontallyCentred | top)
  13595. */
  13596. centredTop = 12,
  13597. /** Indicates that the item should be centred horizontally and placed at the bottom.
  13598. This is equivalent to (horizontallyCentred | bottom)
  13599. */
  13600. centredBottom = 20,
  13601. /** Indicates that the item should be placed in the top-left corner.
  13602. This is equivalent to (left | top)
  13603. */
  13604. topLeft = 9,
  13605. /** Indicates that the item should be placed in the top-right corner.
  13606. This is equivalent to (right | top)
  13607. */
  13608. topRight = 10,
  13609. /** Indicates that the item should be placed in the bottom-left corner.
  13610. This is equivalent to (left | bottom)
  13611. */
  13612. bottomLeft = 17,
  13613. /** Indicates that the item should be placed in the bottom-left corner.
  13614. This is equivalent to (right | bottom)
  13615. */
  13616. bottomRight = 18
  13617. };
  13618. private:
  13619. int flags;
  13620. };
  13621. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  13622. /********* End of inlined file: juce_Justification.h *********/
  13623. /********* Start of inlined file: juce_EdgeTable.h *********/
  13624. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  13625. #define __JUCE_EDGETABLE_JUCEHEADER__
  13626. class Path;
  13627. class Image;
  13628. /**
  13629. A table of horizontal scan-line segments - used for rasterising Paths.
  13630. @see Path, Graphics
  13631. */
  13632. class JUCE_API EdgeTable
  13633. {
  13634. public:
  13635. /** Creates an edge table containing a path.
  13636. A table is created with a fixed vertical range, and only sections of the path
  13637. which lie within this range will be added to the table.
  13638. @param clipLimits only the region of the path that lies within this area will be added
  13639. @param pathToAdd the path to add to the table
  13640. @param transform a transform to apply to the path being added
  13641. */
  13642. EdgeTable (const Rectangle& clipLimits,
  13643. const Path& pathToAdd,
  13644. const AffineTransform& transform) throw();
  13645. /** Creates an edge table containing a rectangle.
  13646. */
  13647. EdgeTable (const Rectangle& rectangleToAdd) throw();
  13648. /** Creates an edge table containing a rectangle.
  13649. */
  13650. EdgeTable (const float x, const float y,
  13651. const float w, const float h) throw();
  13652. /** Creates a copy of another edge table. */
  13653. EdgeTable (const EdgeTable& other) throw();
  13654. /** Copies from another edge table. */
  13655. const EdgeTable& operator= (const EdgeTable& other) throw();
  13656. /** Destructor. */
  13657. ~EdgeTable() throw();
  13658. void clipToRectangle (const Rectangle& r) throw();
  13659. void excludeRectangle (const Rectangle& r) throw();
  13660. void clipToEdgeTable (const EdgeTable& other);
  13661. void clipLineToMask (int x, int y, uint8* mask, int maskStride, int numPixels) throw();
  13662. bool isEmpty() throw();
  13663. const Rectangle& getMaximumBounds() const throw() { return bounds; }
  13664. void translate (float dx, int dy) throw();
  13665. /** Reduces the amount of space the table has allocated.
  13666. This will shrink the table down to use as little memory as possible - useful for
  13667. read-only tables that get stored and re-used for rendering.
  13668. */
  13669. void optimiseTable() throw();
  13670. /** Iterates the lines in the table, for rendering.
  13671. This function will iterate each line in the table, and call a user-defined class
  13672. to render each pixel or continuous line of pixels that the table contains.
  13673. @param iterationCallback this templated class must contain the following methods:
  13674. @code
  13675. inline void setEdgeTableYPos (int y);
  13676. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  13677. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  13678. @endcode
  13679. (these don't necessarily have to be 'const', but it might help it go faster)
  13680. */
  13681. template <class EdgeTableIterationCallback>
  13682. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  13683. {
  13684. const int* lineStart = table;
  13685. for (int y = 0; y < bounds.getHeight(); ++y)
  13686. {
  13687. const int* line = lineStart;
  13688. lineStart += lineStrideElements;
  13689. int numPoints = line[0];
  13690. if (--numPoints > 0)
  13691. {
  13692. int x = *++line;
  13693. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  13694. int levelAccumulator = 0;
  13695. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  13696. while (--numPoints >= 0)
  13697. {
  13698. const int level = *++line;
  13699. jassert (((unsigned int) level) < (unsigned int) 256);
  13700. const int endX = *++line;
  13701. jassert (endX >= x);
  13702. const int endOfRun = (endX >> 8);
  13703. if (endOfRun == (x >> 8))
  13704. {
  13705. // small segment within the same pixel, so just save it for the next
  13706. // time round..
  13707. levelAccumulator += (endX - x) * level;
  13708. }
  13709. else
  13710. {
  13711. // plot the fist pixel of this segment, including any accumulated
  13712. // levels from smaller segments that haven't been drawn yet
  13713. levelAccumulator += (0xff - (x & 0xff)) * level;
  13714. levelAccumulator >>= 8;
  13715. x >>= 8;
  13716. if (levelAccumulator > 0)
  13717. {
  13718. if (levelAccumulator >> 8)
  13719. levelAccumulator = 0xff;
  13720. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  13721. }
  13722. // if there's a run of similar pixels, do it all in one go..
  13723. if (level > 0)
  13724. {
  13725. jassert (endOfRun <= bounds.getRight());
  13726. const int numPix = endOfRun - ++x;
  13727. if (numPix > 0)
  13728. iterationCallback.handleEdgeTableLine (x, numPix, level);
  13729. }
  13730. // save the bit at the end to be drawn next time round the loop.
  13731. levelAccumulator = (endX & 0xff) * level;
  13732. }
  13733. x = endX;
  13734. }
  13735. if (levelAccumulator > 0)
  13736. {
  13737. levelAccumulator >>= 8;
  13738. if (levelAccumulator >> 8)
  13739. levelAccumulator = 0xff;
  13740. x >>= 8;
  13741. jassert (x >= bounds.getX() && x < bounds.getRight());
  13742. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  13743. }
  13744. }
  13745. }
  13746. }
  13747. juce_UseDebuggingNewOperator
  13748. private:
  13749. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  13750. int* table;
  13751. Rectangle bounds;
  13752. int maxEdgesPerLine, lineStrideElements;
  13753. bool needToCheckEmptinesss;
  13754. void addEdgePoint (const int x, const int y, const int winding) throw();
  13755. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  13756. void intersectWithEdgeTableLine (const int y, const int* otherLine) throw();
  13757. };
  13758. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  13759. /********* End of inlined file: juce_EdgeTable.h *********/
  13760. class Image;
  13761. /**
  13762. A path is a sequence of lines and curves that may either form a closed shape
  13763. or be open-ended.
  13764. To use a path, you can create an empty one, then add lines and curves to it
  13765. to create shapes, then it can be rendered by a Graphics context or used
  13766. for geometric operations.
  13767. e.g. @code
  13768. Path myPath;
  13769. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  13770. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  13771. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  13772. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  13773. // add an ellipse as well, which will form a second sub-path within the path..
  13774. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  13775. // double the width of the whole thing..
  13776. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  13777. // and draw it to a graphics context with a 5-pixel thick outline.
  13778. g.strokePath (myPath, PathStrokeType (5.0f));
  13779. @endcode
  13780. A path object can actually contain multiple sub-paths, which may themselves
  13781. be open or closed.
  13782. @see PathFlatteningIterator, PathStrokeType, Graphics
  13783. */
  13784. class JUCE_API Path
  13785. {
  13786. public:
  13787. /** Creates an empty path. */
  13788. Path() throw();
  13789. /** Creates a copy of another path. */
  13790. Path (const Path& other) throw();
  13791. /** Destructor. */
  13792. ~Path() throw();
  13793. /** Copies this path from another one. */
  13794. const Path& operator= (const Path& other) throw();
  13795. /** Returns true if the path doesn't contain any lines or curves. */
  13796. bool isEmpty() const throw();
  13797. /** Returns the smallest rectangle that contains all points within the path.
  13798. */
  13799. void getBounds (float& x, float& y,
  13800. float& w, float& h) const throw();
  13801. /** Returns the smallest rectangle that contains all points within the path
  13802. after it's been transformed with the given tranasform matrix.
  13803. */
  13804. void getBoundsTransformed (const AffineTransform& transform,
  13805. float& x, float& y,
  13806. float& w, float& h) const throw();
  13807. /** Checks whether a point lies within the path.
  13808. This is only relevent for closed paths (see closeSubPath()), and
  13809. may produce false results if used on a path which has open sub-paths.
  13810. The path's winding rule is taken into account by this method.
  13811. The tolerence parameter is passed to the PathFlatteningIterator that
  13812. is used to trace the path - for more info about it, see the notes for
  13813. the PathFlatteningIterator constructor.
  13814. @see closeSubPath, setUsingNonZeroWinding
  13815. */
  13816. bool contains (const float x,
  13817. const float y,
  13818. const float tolerence = 10.0f) const throw();
  13819. /** Checks whether a line crosses the path.
  13820. This will return positive if the line crosses any of the paths constituent
  13821. lines or curves. It doesn't take into account whether the line is inside
  13822. or outside the path, or whether the path is open or closed.
  13823. The tolerence parameter is passed to the PathFlatteningIterator that
  13824. is used to trace the path - for more info about it, see the notes for
  13825. the PathFlatteningIterator constructor.
  13826. */
  13827. bool intersectsLine (const float x1, const float y1,
  13828. const float x2, const float y2,
  13829. const float tolerence = 10.0f) throw();
  13830. /** Removes all lines and curves, resetting the path completely. */
  13831. void clear() throw();
  13832. /** Begins a new subpath with a given starting position.
  13833. This will move the path's current position to the co-ordinates passed in and
  13834. make it ready to draw lines or curves starting from this position.
  13835. After adding whatever lines and curves are needed, you can either
  13836. close the current sub-path using closeSubPath() or call startNewSubPath()
  13837. to move to a new sub-path, leaving the old one open-ended.
  13838. @see lineTo, quadraticTo, cubicTo, closeSubPath
  13839. */
  13840. void startNewSubPath (const float startX,
  13841. const float startY) throw();
  13842. /** Closes a the current sub-path with a line back to its start-point.
  13843. When creating a closed shape such as a triangle, don't use 3 lineTo()
  13844. calls - instead use two lineTo() calls, followed by a closeSubPath()
  13845. to join the final point back to the start.
  13846. This ensures that closes shapes are recognised as such, and this is
  13847. important for tasks like drawing strokes, which needs to know whether to
  13848. draw end-caps or not.
  13849. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  13850. */
  13851. void closeSubPath() throw();
  13852. /** Adds a line from the shape's last position to a new end-point.
  13853. This will connect the end-point of the last line or curve that was added
  13854. to a new point, using a straight line.
  13855. See the class description for an example of how to add lines and curves to a path.
  13856. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  13857. */
  13858. void lineTo (const float endX,
  13859. const float endY) throw();
  13860. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  13861. This will connect the end-point of the last line or curve that was added
  13862. to a new point, using a quadratic spline with one control-point.
  13863. See the class description for an example of how to add lines and curves to a path.
  13864. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  13865. */
  13866. void quadraticTo (const float controlPointX,
  13867. const float controlPointY,
  13868. const float endPointX,
  13869. const float endPointY) throw();
  13870. /** Adds a cubic bezier curve from the shape's last position to a new position.
  13871. This will connect the end-point of the last line or curve that was added
  13872. to a new point, using a cubic spline with two control-points.
  13873. See the class description for an example of how to add lines and curves to a path.
  13874. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  13875. */
  13876. void cubicTo (const float controlPoint1X,
  13877. const float controlPoint1Y,
  13878. const float controlPoint2X,
  13879. const float controlPoint2Y,
  13880. const float endPointX,
  13881. const float endPointY) throw();
  13882. /** Returns the last point that was added to the path by one of the drawing methods.
  13883. */
  13884. const Point getCurrentPosition() const;
  13885. /** Adds a rectangle to the path.
  13886. The rectangle is added as a new sub-path. (Any currently open paths will be
  13887. left open).
  13888. @see addRoundedRectangle, addTriangle
  13889. */
  13890. void addRectangle (const float x, const float y,
  13891. const float w, const float h) throw();
  13892. /** Adds a rectangle to the path.
  13893. The rectangle is added as a new sub-path. (Any currently open paths will be
  13894. left open).
  13895. @see addRoundedRectangle, addTriangle
  13896. */
  13897. void addRectangle (const Rectangle& rectangle) throw();
  13898. /** Adds a rectangle with rounded corners to the path.
  13899. The rectangle is added as a new sub-path. (Any currently open paths will be
  13900. left open).
  13901. @see addRectangle, addTriangle
  13902. */
  13903. void addRoundedRectangle (const float x, const float y,
  13904. const float w, const float h,
  13905. float cornerSize) throw();
  13906. /** Adds a rectangle with rounded corners to the path.
  13907. The rectangle is added as a new sub-path. (Any currently open paths will be
  13908. left open).
  13909. @see addRectangle, addTriangle
  13910. */
  13911. void addRoundedRectangle (const float x, const float y,
  13912. const float w, const float h,
  13913. float cornerSizeX,
  13914. float cornerSizeY) throw();
  13915. /** Adds a triangle to the path.
  13916. The triangle is added as a new closed sub-path. (Any currently open paths will be
  13917. left open).
  13918. Note that whether the vertices are specified in clockwise or anticlockwise
  13919. order will affect how the triangle is filled when it overlaps other
  13920. shapes (the winding order setting will affect this of course).
  13921. */
  13922. void addTriangle (const float x1, const float y1,
  13923. const float x2, const float y2,
  13924. const float x3, const float y3) throw();
  13925. /** Adds a quadrilateral to the path.
  13926. The quad is added as a new closed sub-path. (Any currently open paths will be
  13927. left open).
  13928. Note that whether the vertices are specified in clockwise or anticlockwise
  13929. order will affect how the quad is filled when it overlaps other
  13930. shapes (the winding order setting will affect this of course).
  13931. */
  13932. void addQuadrilateral (const float x1, const float y1,
  13933. const float x2, const float y2,
  13934. const float x3, const float y3,
  13935. const float x4, const float y4) throw();
  13936. /** Adds an ellipse to the path.
  13937. The shape is added as a new sub-path. (Any currently open paths will be
  13938. left open).
  13939. @see addArc
  13940. */
  13941. void addEllipse (const float x, const float y,
  13942. const float width, const float height) throw();
  13943. /** Adds an elliptical arc to the current path.
  13944. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  13945. or anti-clockwise according to whether the end angle is greater than the start. This means
  13946. that sometimes you may need to use values greater than 2*Pi for the end angle.
  13947. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  13948. @param y the top edge of the rectangle in which the elliptical outline fits
  13949. @param width the width of the rectangle in which the elliptical outline fits
  13950. @param height the height of the rectangle in which the elliptical outline fits
  13951. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  13952. top-centre of the ellipse)
  13953. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  13954. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  13955. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  13956. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  13957. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  13958. it will be added to the current sub-path, continuing from the current postition
  13959. @see addCentredArc, arcTo, addPieSegment, addEllipse
  13960. */
  13961. void addArc (const float x, const float y,
  13962. const float width, const float height,
  13963. const float fromRadians,
  13964. const float toRadians,
  13965. const bool startAsNewSubPath = false) throw();
  13966. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  13967. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  13968. or anti-clockwise according to whether the end angle is greater than the start. This means
  13969. that sometimes you may need to use values greater than 2*Pi for the end angle.
  13970. @param centreX the centre x of the ellipse
  13971. @param centreY the centre y of the ellipse
  13972. @param radiusX the horizontal radius of the ellipse
  13973. @param radiusY the vertical radius of the ellipse
  13974. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  13975. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  13976. top-centre of the ellipse)
  13977. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  13978. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  13979. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  13980. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  13981. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  13982. it will be added to the current sub-path, continuing from the current postition
  13983. @see addArc, arcTo
  13984. */
  13985. void addCentredArc (const float centreX, const float centreY,
  13986. const float radiusX, const float radiusY,
  13987. const float rotationOfEllipse,
  13988. const float fromRadians,
  13989. const float toRadians,
  13990. const bool startAsNewSubPath = false) throw();
  13991. /** Adds a "pie-chart" shape to the path.
  13992. The shape is added as a new sub-path. (Any currently open paths will be
  13993. left open).
  13994. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  13995. or anti-clockwise according to whether the end angle is greater than the start. This means
  13996. that sometimes you may need to use values greater than 2*Pi for the end angle.
  13997. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  13998. @param y the top edge of the rectangle in which the elliptical outline fits
  13999. @param width the width of the rectangle in which the elliptical outline fits
  14000. @param height the height of the rectangle in which the elliptical outline fits
  14001. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14002. top-centre of the ellipse)
  14003. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14004. top-centre of the ellipse)
  14005. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  14006. ellipse at its centre, where this value indicates the inner ellipse's size with
  14007. respect to the outer one.
  14008. @see addArc
  14009. */
  14010. void addPieSegment (const float x, const float y,
  14011. const float width, const float height,
  14012. const float fromRadians,
  14013. const float toRadians,
  14014. const float innerCircleProportionalSize);
  14015. /** Adds a line with a specified thickness.
  14016. The line is added as a new closed sub-path. (Any currently open paths will be
  14017. left open).
  14018. @see addArrow
  14019. */
  14020. void addLineSegment (const float startX, const float startY,
  14021. const float endX, const float endY,
  14022. float lineThickness) throw();
  14023. /** Adds a line with an arrowhead on the end.
  14024. The arrow is added as a new closed sub-path. (Any currently open paths will be
  14025. left open).
  14026. */
  14027. void addArrow (const float startX, const float startY,
  14028. const float endX, const float endY,
  14029. float lineThickness,
  14030. float arrowheadWidth,
  14031. float arrowheadLength) throw();
  14032. /** Adds a star shape to the path.
  14033. */
  14034. void addStar (const float centreX,
  14035. const float centreY,
  14036. const int numberOfPoints,
  14037. const float innerRadius,
  14038. const float outerRadius,
  14039. const float startAngle = 0.0f);
  14040. /** Adds a speech-bubble shape to the path.
  14041. @param bodyX the left of the main body area of the bubble
  14042. @param bodyY the top of the main body area of the bubble
  14043. @param bodyW the width of the main body area of the bubble
  14044. @param bodyH the height of the main body area of the bubble
  14045. @param cornerSize the amount by which to round off the corners of the main body rectangle
  14046. @param arrowTipX the x position that the tip of the arrow should connect to
  14047. @param arrowTipY the y position that the tip of the arrow should connect to
  14048. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  14049. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  14050. arrow's base should be - this is a proportional distance between 0 and 1.0
  14051. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  14052. */
  14053. void addBubble (float bodyX, float bodyY,
  14054. float bodyW, float bodyH,
  14055. float cornerSize,
  14056. float arrowTipX,
  14057. float arrowTipY,
  14058. int whichSide,
  14059. float arrowPositionAlongEdgeProportional,
  14060. float arrowWidth);
  14061. /** Adds another path to this one.
  14062. The new path is added as a new sub-path. (Any currently open paths in this
  14063. path will be left open).
  14064. @param pathToAppend the path to add
  14065. */
  14066. void addPath (const Path& pathToAppend) throw();
  14067. /** Adds another path to this one, transforming it on the way in.
  14068. The new path is added as a new sub-path, its points being transformed by the given
  14069. matrix before being added.
  14070. @param pathToAppend the path to add
  14071. @param transformToApply an optional transform to apply to the incoming vertices
  14072. */
  14073. void addPath (const Path& pathToAppend,
  14074. const AffineTransform& transformToApply) throw();
  14075. /** Swaps the contents of this path with another one.
  14076. The internal data of the two paths is swapped over, so this is much faster than
  14077. copying it to a temp variable and back.
  14078. */
  14079. void swapWithPath (Path& other);
  14080. /** Applies a 2D transform to all the vertices in the path.
  14081. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  14082. */
  14083. void applyTransform (const AffineTransform& transform) throw();
  14084. /** Rescales this path to make it fit neatly into a given space.
  14085. This is effectively a quick way of calling
  14086. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  14087. @param x the x position of the rectangle to fit the path inside
  14088. @param y the y position of the rectangle to fit the path inside
  14089. @param width the width of the rectangle to fit the path inside
  14090. @param height the height of the rectangle to fit the path inside
  14091. @param preserveProportions if true, it will fit the path into the space without altering its
  14092. horizontal/vertical scale ratio; if false, it will distort the
  14093. path to fill the specified ratio both horizontally and vertically
  14094. @see applyTransform, getTransformToScaleToFit
  14095. */
  14096. void scaleToFit (const float x, const float y,
  14097. const float width, const float height,
  14098. const bool preserveProportions) throw();
  14099. /** Returns a transform that can be used to rescale the path to fit into a given space.
  14100. @param x the x position of the rectangle to fit the path inside
  14101. @param y the y position of the rectangle to fit the path inside
  14102. @param width the width of the rectangle to fit the path inside
  14103. @param height the height of the rectangle to fit the path inside
  14104. @param preserveProportions if true, it will fit the path into the space without altering its
  14105. horizontal/vertical scale ratio; if false, it will distort the
  14106. path to fill the specified ratio both horizontally and vertically
  14107. @param justificationType if the proportions are preseved, the resultant path may be smaller
  14108. than the available rectangle, so this describes how it should be
  14109. positioned within the space.
  14110. @returns an appropriate transformation
  14111. @see applyTransform, scaleToFit
  14112. */
  14113. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  14114. const float width, const float height,
  14115. const bool preserveProportions,
  14116. const Justification& justificationType = Justification::centred) const throw();
  14117. /** Creates a version of this path where all sharp corners have been replaced by curves.
  14118. Wherever two lines meet at an angle, this will replace the corner with a curve
  14119. of the given radius.
  14120. */
  14121. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  14122. /** Changes the winding-rule to be used when filling the path.
  14123. If set to true (which is the default), then the path uses a non-zero-winding rule
  14124. to determine which points are inside the path. If set to false, it uses an
  14125. alternate-winding rule.
  14126. The winding-rule comes into play when areas of the shape overlap other
  14127. areas, and determines whether the overlapping regions are considered to be
  14128. inside or outside.
  14129. Changing this value just sets a flag - it doesn't affect the contents of the
  14130. path.
  14131. @see isUsingNonZeroWinding
  14132. */
  14133. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  14134. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  14135. The default for a new path is true.
  14136. @see setUsingNonZeroWinding
  14137. */
  14138. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  14139. /** Iterates the lines and curves that a path contains.
  14140. @see Path, PathFlatteningIterator
  14141. */
  14142. class JUCE_API Iterator
  14143. {
  14144. public:
  14145. Iterator (const Path& path);
  14146. ~Iterator();
  14147. /** Moves onto the next element in the path.
  14148. If this returns false, there are no more elements. If it returns true,
  14149. the elementType variable will be set to the type of the current element,
  14150. and some of the x and y variables will be filled in with values.
  14151. */
  14152. bool next();
  14153. enum PathElementType
  14154. {
  14155. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  14156. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  14157. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  14158. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  14159. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  14160. };
  14161. PathElementType elementType;
  14162. float x1, y1, x2, y2, x3, y3;
  14163. private:
  14164. const Path& path;
  14165. int index;
  14166. Iterator (const Iterator&);
  14167. const Iterator& operator= (const Iterator&);
  14168. };
  14169. /** Loads a stored path from a data stream.
  14170. The data in the stream must have been written using writePathToStream().
  14171. Note that this will append the stored path to whatever is currently in
  14172. this path, so you might need to call clear() beforehand.
  14173. @see loadPathFromData, writePathToStream
  14174. */
  14175. void loadPathFromStream (InputStream& source);
  14176. /** Loads a stored path from a block of data.
  14177. This is similar to loadPathFromStream(), but just reads from a block
  14178. of data. Useful if you're including stored shapes in your code as a
  14179. block of static data.
  14180. @see loadPathFromStream, writePathToStream
  14181. */
  14182. void loadPathFromData (const unsigned char* const data,
  14183. const int numberOfBytes) throw();
  14184. /** Stores the path by writing it out to a stream.
  14185. After writing out a path, you can reload it using loadPathFromStream().
  14186. @see loadPathFromStream, loadPathFromData
  14187. */
  14188. void writePathToStream (OutputStream& destination) const;
  14189. /** Creates a string containing a textual representation of this path.
  14190. @see restoreFromString
  14191. */
  14192. const String toString() const;
  14193. /** Restores this path from a string that was created with the toString() method.
  14194. @see toString()
  14195. */
  14196. void restoreFromString (const String& stringVersion);
  14197. juce_UseDebuggingNewOperator
  14198. private:
  14199. friend class PathFlatteningIterator;
  14200. friend class Path::Iterator;
  14201. ArrayAllocationBase <float> data;
  14202. int numElements;
  14203. float pathXMin, pathXMax, pathYMin, pathYMax;
  14204. bool useNonZeroWinding;
  14205. static const float lineMarker;
  14206. static const float moveMarker;
  14207. static const float quadMarker;
  14208. static const float cubicMarker;
  14209. static const float closeSubPathMarker;
  14210. };
  14211. #endif // __JUCE_PATH_JUCEHEADER__
  14212. /********* End of inlined file: juce_Path.h *********/
  14213. class Font;
  14214. class CustomTypefaceGlyphInfo;
  14215. /** A typeface represents a size-independent font.
  14216. This base class is abstract, but calling createSystemTypefaceFor() will return
  14217. a platform-specific subclass that can be used.
  14218. The CustomTypeface subclass allow you to build your own typeface, and to
  14219. load and save it in the Juce typeface format.
  14220. Normally you should never need to deal directly with Typeface objects - the Font
  14221. class does everything you typically need for rendering text.
  14222. @see CustomTypeface, Font
  14223. */
  14224. class JUCE_API Typeface : public ReferenceCountedObject
  14225. {
  14226. public:
  14227. /** A handy typedef for a pointer to a typeface. */
  14228. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  14229. /** Returns the name of the typeface.
  14230. @see Font::getTypefaceName
  14231. */
  14232. const String getName() const throw() { return name; }
  14233. /** Creates a new system typeface. */
  14234. static const Ptr createSystemTypefaceFor (const Font& font);
  14235. /** Destructor. */
  14236. virtual ~Typeface();
  14237. /** Returns the ascent of the font, as a proportion of its height.
  14238. The height is considered to always be normalised as 1.0, so this will be a
  14239. value less that 1.0, indicating the proportion of the font that lies above
  14240. its baseline.
  14241. */
  14242. virtual float getAscent() const = 0;
  14243. /** Returns the descent of the font, as a proportion of its height.
  14244. The height is considered to always be normalised as 1.0, so this will be a
  14245. value less that 1.0, indicating the proportion of the font that lies below
  14246. its baseline.
  14247. */
  14248. virtual float getDescent() const = 0;
  14249. /** Measures the width of a line of text.
  14250. The distance returned is based on the font having an normalised height of 1.0.
  14251. You should never need to call this directly! Use Font::getStringWidth() instead!
  14252. */
  14253. virtual float getStringWidth (const String& text) = 0;
  14254. /** Converts a line of text into its glyph numbers and their positions.
  14255. The distances returned are based on the font having an normalised height of 1.0.
  14256. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  14257. */
  14258. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  14259. /** Returns the outline for a glyph.
  14260. The path returned will be normalised to a font height of 1.0.
  14261. */
  14262. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  14263. juce_UseDebuggingNewOperator
  14264. protected:
  14265. String name;
  14266. Typeface (const String& name) throw();
  14267. private:
  14268. Typeface (const Typeface&);
  14269. const Typeface& operator= (const Typeface&);
  14270. };
  14271. /** A typeface that can be populated with custom glyphs.
  14272. You can create a CustomTypeface if you need one that contains your own glyphs,
  14273. or if you need to load a typeface from a Juce-formatted binary stream.
  14274. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  14275. to copy glyphs into this face.
  14276. @see Typeface, Font
  14277. */
  14278. class JUCE_API CustomTypeface : public Typeface
  14279. {
  14280. public:
  14281. /** Creates a new, empty typeface. */
  14282. CustomTypeface();
  14283. /** Loads a typeface from a previously saved stream.
  14284. The stream must have been created by writeToStream().
  14285. @see writeToStream
  14286. */
  14287. CustomTypeface (InputStream& serialisedTypefaceStream);
  14288. /** Destructor. */
  14289. ~CustomTypeface();
  14290. /** Resets this typeface, deleting all its glyphs and settings. */
  14291. void clear();
  14292. /** Sets the vital statistics for the typeface.
  14293. @param name the typeface's name
  14294. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  14295. the value that will be returned by Typeface::getAscent(). The
  14296. descent is assumed to be (1.0 - ascent)
  14297. @param isBold should be true if the typeface is bold
  14298. @param isItalic should be true if the typeface is italic
  14299. @param defaultCharacter the character to be used as a replacement if there's
  14300. no glyph available for the character that's being drawn
  14301. */
  14302. void setCharacteristics (const String& name, const float ascent,
  14303. const bool isBold, const bool isItalic,
  14304. const juce_wchar defaultCharacter) throw();
  14305. /** Adds a glyph to the typeface.
  14306. The path that is passed in is normalised so that the font height is 1.0, and its
  14307. origin is the anchor point of the character on its baseline.
  14308. The width is the nominal width of the character, and any extra kerning values that
  14309. are specified will be added to this width.
  14310. */
  14311. void addGlyph (const juce_wchar character, const Path& path, const float width) throw();
  14312. /** Specifies an extra kerning amount to be used between a pair of characters.
  14313. The amount will be added to the nominal width of the first character when laying out a string.
  14314. */
  14315. void addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw();
  14316. /** Adds a range of glyphs from another typeface.
  14317. This will attempt to pull in the paths and kerning information from another typeface and
  14318. add it to this one.
  14319. */
  14320. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  14321. /** Saves this typeface as a Juce-formatted font file.
  14322. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  14323. constructor.
  14324. */
  14325. bool writeToStream (OutputStream& outputStream);
  14326. // The following methods implement the basic Typeface behaviour.
  14327. float getAscent() const;
  14328. float getDescent() const;
  14329. float getStringWidth (const String& text);
  14330. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  14331. bool getOutlineForGlyph (int glyphNumber, Path& path);
  14332. int getGlyphForCharacter (juce_wchar character);
  14333. juce_UseDebuggingNewOperator
  14334. protected:
  14335. juce_wchar defaultCharacter;
  14336. float ascent;
  14337. bool isBold, isItalic;
  14338. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  14339. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  14340. particular character and there's no corresponding glyph, they'll call this
  14341. method so that a subclass can try to add that glyph, returning true if it
  14342. manages to do so.
  14343. */
  14344. virtual bool loadGlyphIfPossible (const juce_wchar characterNeeded);
  14345. private:
  14346. OwnedArray <CustomTypefaceGlyphInfo> glyphs;
  14347. short lookupTable [128];
  14348. CustomTypeface (const CustomTypeface&);
  14349. const CustomTypeface& operator= (const CustomTypeface&);
  14350. CustomTypefaceGlyphInfo* findGlyph (const juce_wchar character, const bool loadIfNeeded) throw();
  14351. CustomTypefaceGlyphInfo* findGlyphSubstituting (const juce_wchar character) throw();
  14352. };
  14353. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  14354. /********* End of inlined file: juce_Typeface.h *********/
  14355. class LowLevelGraphicsContext;
  14356. /**
  14357. Represents a particular font, including its size, style, etc.
  14358. Apart from the typeface to be used, a Font object also dictates whether
  14359. the font is bold, italic, underlined, how big it is, and its kerning and
  14360. horizontal scale factor.
  14361. @see Typeface
  14362. */
  14363. class JUCE_API Font
  14364. {
  14365. public:
  14366. /** A combination of these values is used by the constructor to specify the
  14367. style of font to use.
  14368. */
  14369. enum FontStyleFlags
  14370. {
  14371. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  14372. bold = 1, /**< boldens the font. @see setStyleFlags */
  14373. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  14374. underlined = 4 /**< underlines the font. @see setStyleFlags */
  14375. };
  14376. /** Creates a sans-serif font in a given size.
  14377. @param fontHeight the height in pixels (can be fractional)
  14378. @param styleFlags the style to use - this can be a combination of the
  14379. Font::bold, Font::italic and Font::underlined, or
  14380. just Font::plain for the normal style.
  14381. @see FontStyleFlags, getDefaultSansSerifFontName
  14382. */
  14383. Font (const float fontHeight,
  14384. const int styleFlags = plain) throw();
  14385. /** Creates a font with a given typeface and parameters.
  14386. @param typefaceName the name of the typeface to use
  14387. @param fontHeight the height in pixels (can be fractional)
  14388. @param styleFlags the style to use - this can be a combination of the
  14389. Font::bold, Font::italic and Font::underlined, or
  14390. just Font::plain for the normal style.
  14391. @see FontStyleFlags, getDefaultSansSerifFontName
  14392. */
  14393. Font (const String& typefaceName,
  14394. const float fontHeight,
  14395. const int styleFlags) throw();
  14396. /** Creates a copy of another Font object. */
  14397. Font (const Font& other) throw();
  14398. /** Creates a font for a typeface. */
  14399. Font (const Typeface::Ptr& typeface) throw();
  14400. /** Creates a basic sans-serif font at a default height.
  14401. You should use one of the other constructors for creating a font that you're planning
  14402. on drawing with - this constructor is here to help initialise objects before changing
  14403. the font's settings later.
  14404. */
  14405. Font() throw();
  14406. /** Copies this font from another one. */
  14407. const Font& operator= (const Font& other) throw();
  14408. bool operator== (const Font& other) const throw();
  14409. bool operator!= (const Font& other) const throw();
  14410. /** Destructor. */
  14411. ~Font() throw();
  14412. /** Changes the name of the typeface family.
  14413. e.g. "Arial", "Courier", etc.
  14414. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  14415. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  14416. but are generic names that are used to represent the various default fonts.
  14417. If you need to know the exact typeface name being used, you can call
  14418. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  14419. If a suitable font isn't found on the machine, it'll just use a default instead.
  14420. */
  14421. void setTypefaceName (const String& faceName) throw();
  14422. /** Returns the name of the typeface family that this font uses.
  14423. e.g. "Arial", "Courier", etc.
  14424. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  14425. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  14426. but are generic names that are used to represent the various default fonts.
  14427. If you need to know the exact typeface name being used, you can call
  14428. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  14429. */
  14430. const String& getTypefaceName() const throw() { return font->typefaceName; }
  14431. /** Returns a typeface name that represents the default sans-serif font.
  14432. This is also the typeface that will be used when a font is created without
  14433. specifying any typeface details.
  14434. Note that this method just returns a generic placeholder string that means "the default
  14435. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  14436. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  14437. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  14438. */
  14439. static const String getDefaultSansSerifFontName() throw();
  14440. /** Returns a typeface name that represents the default sans-serif font.
  14441. Note that this method just returns a generic placeholder string that means "the default
  14442. serif font" - it's not the actual name of this font. To get the actual name, use
  14443. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  14444. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  14445. */
  14446. static const String getDefaultSerifFontName() throw();
  14447. /** Returns a typeface name that represents the default sans-serif font.
  14448. Note that this method just returns a generic placeholder string that means "the default
  14449. monospaced font" - it's not the actual name of this font. To get the actual name, use
  14450. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  14451. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  14452. */
  14453. static const String getDefaultMonospacedFontName() throw();
  14454. /** Returns the typeface names of the default fonts on the current platform. */
  14455. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  14456. /** Returns the total height of this font.
  14457. This is the maximum height, from the top of the ascent to the bottom of the
  14458. descenders.
  14459. @see setHeight, setHeightWithoutChangingWidth, getAscent
  14460. */
  14461. float getHeight() const throw() { return font->height; }
  14462. /** Changes the font's height.
  14463. @see getHeight, setHeightWithoutChangingWidth
  14464. */
  14465. void setHeight (float newHeight) throw();
  14466. /** Changes the font's height without changing its width.
  14467. This alters the horizontal scale to compensate for the change in height.
  14468. */
  14469. void setHeightWithoutChangingWidth (float newHeight) throw();
  14470. /** Returns the height of the font above its baseline.
  14471. This is the maximum height from the baseline to the top.
  14472. @see getHeight, getDescent
  14473. */
  14474. float getAscent() const throw();
  14475. /** Returns the amount that the font descends below its baseline.
  14476. This is calculated as (getHeight() - getAscent()).
  14477. @see getAscent, getHeight
  14478. */
  14479. float getDescent() const throw();
  14480. /** Returns the font's style flags.
  14481. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  14482. enum, to describe whether the font is bold, italic, etc.
  14483. @see FontStyleFlags
  14484. */
  14485. int getStyleFlags() const throw() { return font->styleFlags; }
  14486. /** Changes the font's style.
  14487. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  14488. enum, to set the font's properties
  14489. @see FontStyleFlags
  14490. */
  14491. void setStyleFlags (const int newFlags) throw();
  14492. /** Makes the font bold or non-bold. */
  14493. void setBold (const bool shouldBeBold) throw();
  14494. /** Returns true if the font is bold. */
  14495. bool isBold() const throw();
  14496. /** Makes the font italic or non-italic. */
  14497. void setItalic (const bool shouldBeItalic) throw();
  14498. /** Returns true if the font is italic. */
  14499. bool isItalic() const throw();
  14500. /** Makes the font underlined or non-underlined. */
  14501. void setUnderline (const bool shouldBeUnderlined) throw();
  14502. /** Returns true if the font is underlined. */
  14503. bool isUnderlined() const throw();
  14504. /** Changes the font's horizontal scale factor.
  14505. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  14506. narrower, greater than 1.0 will be stretched out.
  14507. */
  14508. void setHorizontalScale (const float scaleFactor) throw();
  14509. /** Returns the font's horizontal scale.
  14510. A value of 1.0 is the normal scale, less than this will be narrower, greater
  14511. than 1.0 will be stretched out.
  14512. @see setHorizontalScale
  14513. */
  14514. float getHorizontalScale() const throw() { return font->horizontalScale; }
  14515. /** Changes the font's kerning.
  14516. @param extraKerning a multiple of the font's height that will be added
  14517. to space between the characters. So a value of zero is
  14518. normal spacing, positive values spread the letters out,
  14519. negative values make them closer together.
  14520. */
  14521. void setExtraKerningFactor (const float extraKerning) throw();
  14522. /** Returns the font's kerning.
  14523. This is the extra space added between adjacent characters, as a proportion
  14524. of the font's height.
  14525. A value of zero is normal spacing, positive values will spread the letters
  14526. out more, and negative values make them closer together.
  14527. */
  14528. float getExtraKerningFactor() const throw() { return font->kerning; }
  14529. /** Changes all the font's characteristics with one call. */
  14530. void setSizeAndStyle (float newHeight,
  14531. const int newStyleFlags,
  14532. const float newHorizontalScale,
  14533. const float newKerningAmount) throw();
  14534. /** Returns the total width of a string as it would be drawn using this font.
  14535. For a more accurate floating-point result, use getStringWidthFloat().
  14536. */
  14537. int getStringWidth (const String& text) const throw();
  14538. /** Returns the total width of a string as it would be drawn using this font.
  14539. @see getStringWidth
  14540. */
  14541. float getStringWidthFloat (const String& text) const throw();
  14542. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  14543. An extra x offset is added at the end of the run, to indicate where the right hand
  14544. edge of the last character is.
  14545. */
  14546. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  14547. /** Returns the typeface used by this font.
  14548. Note that the object returned may go out of scope if this font is deleted
  14549. or has its style changed.
  14550. */
  14551. Typeface* getTypeface() const throw();
  14552. /** Creates an array of Font objects to represent all the fonts on the system.
  14553. If you just need the names of the typefaces, you can also use
  14554. findAllTypefaceNames() instead.
  14555. @param results the array to which new Font objects will be added.
  14556. */
  14557. static void findFonts (OwnedArray<Font>& results) throw();
  14558. /** Returns a list of all the available typeface names.
  14559. The names returned can be passed into setTypefaceName().
  14560. You can use this instead of findFonts() if you only need their names, and not
  14561. font objects.
  14562. */
  14563. static const StringArray findAllTypefaceNames() throw();
  14564. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  14565. in the requested typeface.
  14566. */
  14567. static const String getFallbackFontName() throw();
  14568. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  14569. available in whatever font you're trying to use.
  14570. */
  14571. static void setFallbackFontName (const String& name) throw();
  14572. juce_UseDebuggingNewOperator
  14573. private:
  14574. friend class FontGlyphAlphaMap;
  14575. friend class TypefaceCache;
  14576. class SharedFontInternal : public ReferenceCountedObject
  14577. {
  14578. public:
  14579. SharedFontInternal (const String& typefaceName, const float height, const float horizontalScale,
  14580. const float kerning, const float ascent, const int styleFlags,
  14581. Typeface* const typeface) throw();
  14582. SharedFontInternal (const SharedFontInternal& other) throw();
  14583. String typefaceName;
  14584. float height, horizontalScale, kerning, ascent;
  14585. int styleFlags;
  14586. Typeface::Ptr typeface;
  14587. };
  14588. ReferenceCountedObjectPtr <SharedFontInternal> font;
  14589. void dupeInternalIfShared() throw();
  14590. };
  14591. #endif // __JUCE_FONT_JUCEHEADER__
  14592. /********* End of inlined file: juce_Font.h *********/
  14593. /********* Start of inlined file: juce_PathStrokeType.h *********/
  14594. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  14595. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  14596. /**
  14597. Describes a type of stroke used to render a solid outline along a path.
  14598. A PathStrokeType object can be used directly to create the shape of an outline
  14599. around a path, and is used by Graphics::strokePath to specify the type of
  14600. stroke to draw.
  14601. @see Path, Graphics::strokePath
  14602. */
  14603. class JUCE_API PathStrokeType
  14604. {
  14605. public:
  14606. /** The type of shape to use for the corners between two adjacent line segments. */
  14607. enum JointStyle
  14608. {
  14609. mitered, /**< Indicates that corners should be drawn with sharp joints.
  14610. Note that for angles that curve back on themselves, drawing a
  14611. mitre could require extending the point too far away from the
  14612. path, so a mitre limit is imposed and any corners that exceed it
  14613. are drawn as bevelled instead. */
  14614. curved, /**< Indicates that corners should be drawn as rounded-off. */
  14615. beveled /**< Indicates that corners should be drawn with a line flattening their
  14616. outside edge. */
  14617. };
  14618. /** The type shape to use for the ends of lines. */
  14619. enum EndCapStyle
  14620. {
  14621. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  14622. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  14623. the thickness of the stroke. */
  14624. rounded /**< Ends of lines are rounded-off with a circular shape. */
  14625. };
  14626. /** Creates a stroke type.
  14627. @param strokeThickness the width of the line to use
  14628. @param jointStyle the type of joints to use for corners
  14629. @param endStyle the type of end-caps to use for the ends of open paths.
  14630. */
  14631. PathStrokeType (const float strokeThickness,
  14632. const JointStyle jointStyle = mitered,
  14633. const EndCapStyle endStyle = butt) throw();
  14634. /** Createes a copy of another stroke type. */
  14635. PathStrokeType (const PathStrokeType& other) throw();
  14636. /** Copies another stroke onto this one. */
  14637. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  14638. /** Destructor. */
  14639. ~PathStrokeType() throw();
  14640. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  14641. @param destPath the resultant stroked outline shape will be copied into this path.
  14642. Note that it's ok for the source and destination Paths to be
  14643. the same object, so you can easily turn a path into a stroked version
  14644. of itself.
  14645. @param sourcePath the path to use as the source
  14646. @param transform an optional transform to apply to the points from the source path
  14647. as they are being used
  14648. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  14649. a higher resolution, which improved the quality if you'll later want
  14650. to enlarge the stroked path
  14651. @see createDashedStroke
  14652. */
  14653. void createStrokedPath (Path& destPath,
  14654. const Path& sourcePath,
  14655. const AffineTransform& transform = AffineTransform::identity,
  14656. const float extraAccuracy = 1.0f) const throw();
  14657. /** Applies this stroke type to a path, creating a dashed line.
  14658. This is similar to createStrokedPath, but uses the array passed in to
  14659. break the stroke up into a series of dashes.
  14660. @param destPath the resultant stroked outline shape will be copied into this path.
  14661. Note that it's ok for the source and destination Paths to be
  14662. the same object, so you can easily turn a path into a stroked version
  14663. of itself.
  14664. @param sourcePath the path to use as the source
  14665. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  14666. a line of length 2, then skip a length of 3, then add a line of length 4,
  14667. skip 5, and keep repeating this pattern.
  14668. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  14669. an even number, otherwise the pattern will get out of step as it
  14670. repeats.
  14671. @param transform an optional transform to apply to the points from the source path
  14672. as they are being used
  14673. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  14674. a higher resolution, which improved the quality if you'll later want
  14675. to enlarge the stroked path
  14676. */
  14677. void createDashedStroke (Path& destPath,
  14678. const Path& sourcePath,
  14679. const float* dashLengths,
  14680. int numDashLengths,
  14681. const AffineTransform& transform = AffineTransform::identity,
  14682. const float extraAccuracy = 1.0f) const throw();
  14683. /** Returns the stroke thickness. */
  14684. float getStrokeThickness() const throw() { return thickness; }
  14685. /** Returns the joint style. */
  14686. JointStyle getJointStyle() const throw() { return jointStyle; }
  14687. /** Returns the end-cap style. */
  14688. EndCapStyle getEndStyle() const throw() { return endStyle; }
  14689. juce_UseDebuggingNewOperator
  14690. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  14691. bool operator== (const PathStrokeType& other) const throw();
  14692. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  14693. bool operator!= (const PathStrokeType& other) const throw();
  14694. private:
  14695. float thickness;
  14696. JointStyle jointStyle;
  14697. EndCapStyle endStyle;
  14698. };
  14699. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  14700. /********* End of inlined file: juce_PathStrokeType.h *********/
  14701. /********* Start of inlined file: juce_Line.h *********/
  14702. #ifndef __JUCE_LINE_JUCEHEADER__
  14703. #define __JUCE_LINE_JUCEHEADER__
  14704. /**
  14705. Represents a line, using 32-bit float co-ordinates.
  14706. This class contains a bunch of useful methods for various geometric
  14707. tasks.
  14708. @see Point, Rectangle, Path, Graphics::drawLine
  14709. */
  14710. class JUCE_API Line
  14711. {
  14712. public:
  14713. /** Creates a line, using (0, 0) as its start and end points. */
  14714. Line() throw();
  14715. /** Creates a copy of another line. */
  14716. Line (const Line& other) throw();
  14717. /** Creates a line based on the co-ordinates of its start and end points. */
  14718. Line (const float startX,
  14719. const float startY,
  14720. const float endX,
  14721. const float endY) throw();
  14722. /** Creates a line from its start and end points. */
  14723. Line (const Point& start,
  14724. const Point& end) throw();
  14725. /** Copies a line from another one. */
  14726. const Line& operator= (const Line& other) throw();
  14727. /** Destructor. */
  14728. ~Line() throw();
  14729. /** Returns the x co-ordinate of the line's start point. */
  14730. inline float getStartX() const throw() { return startX; }
  14731. /** Returns the y co-ordinate of the line's start point. */
  14732. inline float getStartY() const throw() { return startY; }
  14733. /** Returns the x co-ordinate of the line's end point. */
  14734. inline float getEndX() const throw() { return endX; }
  14735. /** Returns the y co-ordinate of the line's end point. */
  14736. inline float getEndY() const throw() { return endY; }
  14737. /** Returns the line's start point. */
  14738. const Point getStart() const throw();
  14739. /** Returns the line's end point. */
  14740. const Point getEnd() const throw();
  14741. /** Changes this line's start point */
  14742. void setStart (const float newStartX,
  14743. const float newStartY) throw();
  14744. /** Changes this line's end point */
  14745. void setEnd (const float newEndX,
  14746. const float newEndY) throw();
  14747. /** Changes this line's start point */
  14748. void setStart (const Point& newStart) throw();
  14749. /** Changes this line's end point */
  14750. void setEnd (const Point& newEnd) throw();
  14751. /** Applies an affine transform to the line's start and end points. */
  14752. void applyTransform (const AffineTransform& transform) throw();
  14753. /** Returns the length of the line. */
  14754. float getLength() const throw();
  14755. /** Returns true if the line's start and end x co-ordinates are the same. */
  14756. bool isVertical() const throw();
  14757. /** Returns true if the line's start and end y co-ordinates are the same. */
  14758. bool isHorizontal() const throw();
  14759. /** Returns the line's angle.
  14760. This value is the number of radians clockwise from the 3 o'clock direction,
  14761. where the line's start point is considered to be at the centre.
  14762. */
  14763. float getAngle() const throw();
  14764. /** Compares two lines. */
  14765. bool operator== (const Line& other) const throw();
  14766. /** Compares two lines. */
  14767. bool operator!= (const Line& other) const throw();
  14768. /** Finds the intersection between two lines.
  14769. @param line the other line
  14770. @param intersectionX the x co-ordinate of the point where the lines meet (or
  14771. where they would meet if they were infinitely long)
  14772. the intersection (if the lines intersect). If the lines
  14773. are parallel, this will just be set to the position
  14774. of one of the line's endpoints.
  14775. @param intersectionY the y co-ordinate of the point where the lines meet
  14776. @returns true if the line segments intersect; false if they dont. Even if they
  14777. don't intersect, the intersection co-ordinates returned will still
  14778. be valid
  14779. */
  14780. bool intersects (const Line& line,
  14781. float& intersectionX,
  14782. float& intersectionY) const throw();
  14783. /** Returns the location of the point which is a given distance along this line.
  14784. @param distanceFromStart the distance to move along the line from its
  14785. start point. This value can be negative or longer
  14786. than the line itself
  14787. @see getPointAlongLineProportionally
  14788. */
  14789. const Point getPointAlongLine (const float distanceFromStart) const throw();
  14790. /** Returns a point which is a certain distance along and to the side of this line.
  14791. This effectively moves a given distance along the line, then another distance
  14792. perpendicularly to this, and returns the resulting position.
  14793. @param distanceFromStart the distance to move along the line from its
  14794. start point. This value can be negative or longer
  14795. than the line itself
  14796. @param perpendicularDistance how far to move sideways from the line. If you're
  14797. looking along the line from its start towards its
  14798. end, then a positive value here will move to the
  14799. right, negative value move to the left.
  14800. */
  14801. const Point getPointAlongLine (const float distanceFromStart,
  14802. const float perpendicularDistance) const throw();
  14803. /** Returns the location of the point which is a given distance along this line
  14804. proportional to the line's length.
  14805. @param proportionOfLength the distance to move along the line from its
  14806. start point, in multiples of the line's length.
  14807. So a value of 0.0 will return the line's start point
  14808. and a value of 1.0 will return its end point. (This value
  14809. can be negative or greater than 1.0).
  14810. @see getPointAlongLine
  14811. */
  14812. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  14813. /** Returns the smallest distance between this line segment and a given point.
  14814. So if the point is close to the line, this will return the perpendicular
  14815. distance from the line; if the point is a long way beyond one of the line's
  14816. end-point's, it'll return the straight-line distance to the nearest end-point.
  14817. @param x x position of the point to test
  14818. @param y y position of the point to test
  14819. @returns the point's distance from the line
  14820. @see getPositionAlongLineOfNearestPoint
  14821. */
  14822. float getDistanceFromLine (const float x,
  14823. const float y) const throw();
  14824. /** Finds the point on this line which is nearest to a given point, and
  14825. returns its position as a proportional position along the line.
  14826. @param x x position of the point to test
  14827. @param y y position of the point to test
  14828. @returns a value 0 to 1.0 which is the distance along this line from the
  14829. line's start to the point which is nearest to the point passed-in. To
  14830. turn this number into a position, use getPointAlongLineProportionally().
  14831. @see getDistanceFromLine, getPointAlongLineProportionally
  14832. */
  14833. float findNearestPointTo (const float x,
  14834. const float y) const throw();
  14835. /** Returns true if the given point lies above this line.
  14836. The return value is true if the point's y coordinate is less than the y
  14837. coordinate of this line at the given x (assuming the line extends infinitely
  14838. in both directions).
  14839. */
  14840. bool isPointAbove (const float x, const float y) const throw();
  14841. /** Returns a shortened copy of this line.
  14842. This will chop off part of the start of this line by a certain amount, (leaving the
  14843. end-point the same), and return the new line.
  14844. */
  14845. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  14846. /** Returns a shortened copy of this line.
  14847. This will chop off part of the end of this line by a certain amount, (leaving the
  14848. start-point the same), and return the new line.
  14849. */
  14850. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  14851. /** Cuts off parts of this line to keep the parts that are either inside or
  14852. outside a path.
  14853. Note that this isn't smart enough to cope with situations where the
  14854. line would need to be cut into multiple pieces to correctly clip against
  14855. a re-entrant shape.
  14856. @param path the path to clip against
  14857. @param keepSectionOutsidePath if true, it's the section outside the path
  14858. that will be kept; if false its the section inside
  14859. the path
  14860. @returns true if the line was changed.
  14861. */
  14862. bool clipToPath (const Path& path,
  14863. const bool keepSectionOutsidePath) throw();
  14864. juce_UseDebuggingNewOperator
  14865. private:
  14866. float startX, startY, endX, endY;
  14867. };
  14868. #endif // __JUCE_LINE_JUCEHEADER__
  14869. /********* End of inlined file: juce_Line.h *********/
  14870. /********* Start of inlined file: juce_Colours.h *********/
  14871. #ifndef __JUCE_COLOURS_JUCEHEADER__
  14872. #define __JUCE_COLOURS_JUCEHEADER__
  14873. /********* Start of inlined file: juce_Colour.h *********/
  14874. #ifndef __JUCE_COLOUR_JUCEHEADER__
  14875. #define __JUCE_COLOUR_JUCEHEADER__
  14876. /********* Start of inlined file: juce_PixelFormats.h *********/
  14877. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  14878. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  14879. #if JUCE_MSVC
  14880. #pragma pack (push, 1)
  14881. #define PACKED
  14882. #elif JUCE_GCC
  14883. #define PACKED __attribute__((packed))
  14884. #else
  14885. #define PACKED
  14886. #endif
  14887. class PixelRGB;
  14888. class PixelAlpha;
  14889. /**
  14890. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  14891. operations with it.
  14892. This is used internally by the imaging classes.
  14893. @see PixelRGB
  14894. */
  14895. class JUCE_API PixelARGB
  14896. {
  14897. public:
  14898. /** Creates a pixel without defining its colour. */
  14899. PixelARGB() throw() {}
  14900. ~PixelARGB() throw() {}
  14901. /** Creates a pixel from a 32-bit argb value.
  14902. */
  14903. PixelARGB (const uint32 argb_) throw()
  14904. : argb (argb_)
  14905. {
  14906. }
  14907. forcedinline uint32 getARGB() const throw() { return argb; }
  14908. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  14909. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  14910. forcedinline uint8 getAlpha() const throw() { return components.a; }
  14911. forcedinline uint8 getRed() const throw() { return components.r; }
  14912. forcedinline uint8 getGreen() const throw() { return components.g; }
  14913. forcedinline uint8 getBlue() const throw() { return components.b; }
  14914. /** Blends another pixel onto this one.
  14915. This takes into account the opacity of the pixel being overlaid, and blends
  14916. it accordingly.
  14917. */
  14918. forcedinline void blend (const PixelARGB& src) throw()
  14919. {
  14920. uint32 sargb = src.getARGB();
  14921. const uint32 alpha = 0x100 - (sargb >> 24);
  14922. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14923. sargb += 0xff00ff00 & (getAG() * alpha);
  14924. argb = sargb;
  14925. }
  14926. /** Blends another pixel onto this one.
  14927. This takes into account the opacity of the pixel being overlaid, and blends
  14928. it accordingly.
  14929. */
  14930. forcedinline void blend (const PixelAlpha& src) throw();
  14931. /** Blends another pixel onto this one.
  14932. This takes into account the opacity of the pixel being overlaid, and blends
  14933. it accordingly.
  14934. */
  14935. forcedinline void blend (const PixelRGB& src) throw();
  14936. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  14937. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  14938. being used, so this can blend semi-transparently from a PixelRGB argument.
  14939. */
  14940. template <class Pixel>
  14941. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  14942. {
  14943. ++extraAlpha;
  14944. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  14945. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  14946. const uint32 alpha = 0x100 - (sargb >> 24);
  14947. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14948. sargb += 0xff00ff00 & (getAG() * alpha);
  14949. argb = sargb;
  14950. }
  14951. /** Blends another pixel with this one, creating a colour that is somewhere
  14952. between the two, as specified by the amount.
  14953. */
  14954. template <class Pixel>
  14955. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  14956. {
  14957. uint32 drb = getRB();
  14958. drb += (((src.getRB() - drb) * amount) >> 8);
  14959. drb &= 0x00ff00ff;
  14960. uint32 dag = getAG();
  14961. dag += (((src.getAG() - dag) * amount) >> 8);
  14962. dag &= 0x00ff00ff;
  14963. dag <<= 8;
  14964. dag |= drb;
  14965. argb = dag;
  14966. }
  14967. /** Copies another pixel colour over this one.
  14968. This doesn't blend it - this colour is simply replaced by the other one.
  14969. */
  14970. template <class Pixel>
  14971. forcedinline void set (const Pixel& src) throw()
  14972. {
  14973. argb = src.getARGB();
  14974. }
  14975. /** Replaces the colour's alpha value with another one. */
  14976. forcedinline void setAlpha (const uint8 newAlpha) throw()
  14977. {
  14978. components.a = newAlpha;
  14979. }
  14980. /** Multiplies the colour's alpha value with another one. */
  14981. forcedinline void multiplyAlpha (int multiplier) throw()
  14982. {
  14983. ++multiplier;
  14984. argb = ((multiplier * getAG()) & 0xff00ff00)
  14985. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  14986. }
  14987. forcedinline void multiplyAlpha (const float multiplier) throw()
  14988. {
  14989. multiplyAlpha ((int) (multiplier * 256.0f));
  14990. }
  14991. /** Sets the pixel's colour from individual components. */
  14992. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  14993. {
  14994. components.b = b;
  14995. components.g = g;
  14996. components.r = r;
  14997. components.a = a;
  14998. }
  14999. /** Premultiplies the pixel's RGB values by its alpha. */
  15000. forcedinline void premultiply() throw()
  15001. {
  15002. const uint32 alpha = components.a;
  15003. if (alpha < 0xff)
  15004. {
  15005. if (alpha == 0)
  15006. {
  15007. components.b = 0;
  15008. components.g = 0;
  15009. components.r = 0;
  15010. }
  15011. else
  15012. {
  15013. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  15014. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  15015. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  15016. }
  15017. }
  15018. }
  15019. /** Unpremultiplies the pixel's RGB values. */
  15020. forcedinline void unpremultiply() throw()
  15021. {
  15022. const uint32 alpha = components.a;
  15023. if (alpha < 0xff)
  15024. {
  15025. if (alpha == 0)
  15026. {
  15027. components.b = 0;
  15028. components.g = 0;
  15029. components.r = 0;
  15030. }
  15031. else
  15032. {
  15033. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  15034. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  15035. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  15036. }
  15037. }
  15038. }
  15039. forcedinline void desaturate() throw()
  15040. {
  15041. if (components.a < 0xff && components.a > 0)
  15042. {
  15043. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  15044. components.r = components.g = components.b
  15045. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  15046. }
  15047. else
  15048. {
  15049. components.r = components.g = components.b
  15050. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  15051. }
  15052. }
  15053. /** The indexes of the different components in the byte layout of this type of colour. */
  15054. #if JUCE_BIG_ENDIAN
  15055. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  15056. #else
  15057. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  15058. #endif
  15059. private:
  15060. union
  15061. {
  15062. uint32 argb;
  15063. struct
  15064. {
  15065. #if JUCE_BIG_ENDIAN
  15066. uint8 a : 8, r : 8, g : 8, b : 8;
  15067. #else
  15068. uint8 b, g, r, a;
  15069. #endif
  15070. } PACKED components;
  15071. };
  15072. } PACKED;
  15073. /**
  15074. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  15075. This is used internally by the imaging classes.
  15076. @see PixelARGB
  15077. */
  15078. class JUCE_API PixelRGB
  15079. {
  15080. public:
  15081. /** Creates a pixel without defining its colour. */
  15082. PixelRGB() throw() {}
  15083. ~PixelRGB() throw() {}
  15084. /** Creates a pixel from a 32-bit argb value.
  15085. (The argb format is that used by PixelARGB)
  15086. */
  15087. PixelRGB (const uint32 argb) throw()
  15088. {
  15089. r = (uint8) (argb >> 16);
  15090. g = (uint8) (argb >> 8);
  15091. b = (uint8) (argb);
  15092. }
  15093. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  15094. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  15095. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  15096. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  15097. forcedinline uint8 getRed() const throw() { return r; }
  15098. forcedinline uint8 getGreen() const throw() { return g; }
  15099. forcedinline uint8 getBlue() const throw() { return b; }
  15100. /** Blends another pixel onto this one.
  15101. This takes into account the opacity of the pixel being overlaid, and blends
  15102. it accordingly.
  15103. */
  15104. forcedinline void blend (const PixelARGB& src) throw()
  15105. {
  15106. uint32 sargb = src.getARGB();
  15107. const uint32 alpha = 0x100 - (sargb >> 24);
  15108. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15109. sargb += 0x0000ff00 & (g * alpha);
  15110. r = (uint8) (sargb >> 16);
  15111. g = (uint8) (sargb >> 8);
  15112. b = (uint8) sargb;
  15113. }
  15114. forcedinline void blend (const PixelRGB& src) throw()
  15115. {
  15116. set (src);
  15117. }
  15118. forcedinline void blend (const PixelAlpha& src) throw();
  15119. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15120. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15121. being used, so this can blend semi-transparently from a PixelRGB argument.
  15122. */
  15123. template <class Pixel>
  15124. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15125. {
  15126. ++extraAlpha;
  15127. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  15128. const uint32 sag = extraAlpha * src.getAG();
  15129. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  15130. const uint32 alpha = 0x100 - (sargb >> 24);
  15131. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15132. sargb += 0x0000ff00 & (g * alpha);
  15133. b = (uint8) sargb;
  15134. g = (uint8) (sargb >> 8);
  15135. r = (uint8) (sargb >> 16);
  15136. }
  15137. /** Blends another pixel with this one, creating a colour that is somewhere
  15138. between the two, as specified by the amount.
  15139. */
  15140. template <class Pixel>
  15141. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15142. {
  15143. uint32 drb = getRB();
  15144. drb += (((src.getRB() - drb) * amount) >> 8);
  15145. uint32 dag = getAG();
  15146. dag += (((src.getAG() - dag) * amount) >> 8);
  15147. b = (uint8) drb;
  15148. g = (uint8) dag;
  15149. r = (uint8) (drb >> 16);
  15150. }
  15151. /** Copies another pixel colour over this one.
  15152. This doesn't blend it - this colour is simply replaced by the other one.
  15153. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  15154. is thrown away.
  15155. */
  15156. template <class Pixel>
  15157. forcedinline void set (const Pixel& src) throw()
  15158. {
  15159. b = src.getBlue();
  15160. g = src.getGreen();
  15161. r = src.getRed();
  15162. }
  15163. /** This method is included for compatibility with the PixelARGB class. */
  15164. forcedinline void setAlpha (const uint8) throw() {}
  15165. /** Multiplies the colour's alpha value with another one. */
  15166. forcedinline void multiplyAlpha (int) throw() {}
  15167. /** Sets the pixel's colour from individual components. */
  15168. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  15169. {
  15170. r = r_;
  15171. g = g_;
  15172. b = b_;
  15173. }
  15174. /** Premultiplies the pixel's RGB values by its alpha. */
  15175. forcedinline void premultiply() throw() {}
  15176. /** Unpremultiplies the pixel's RGB values. */
  15177. forcedinline void unpremultiply() throw() {}
  15178. forcedinline void desaturate() throw()
  15179. {
  15180. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  15181. }
  15182. /** The indexes of the different components in the byte layout of this type of colour. */
  15183. #if JUCE_MAC
  15184. enum { indexR = 0, indexG = 1, indexB = 2 };
  15185. #else
  15186. enum { indexR = 2, indexG = 1, indexB = 0 };
  15187. #endif
  15188. private:
  15189. #if JUCE_MAC
  15190. uint8 r, g, b;
  15191. #else
  15192. uint8 b, g, r;
  15193. #endif
  15194. } PACKED;
  15195. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  15196. {
  15197. set (src);
  15198. }
  15199. /**
  15200. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  15201. This is used internally by the imaging classes.
  15202. @see PixelARGB, PixelRGB
  15203. */
  15204. class JUCE_API PixelAlpha
  15205. {
  15206. public:
  15207. /** Creates a pixel without defining its colour. */
  15208. PixelAlpha() throw() {}
  15209. ~PixelAlpha() throw() {}
  15210. /** Creates a pixel from a 32-bit argb value.
  15211. (The argb format is that used by PixelARGB)
  15212. */
  15213. PixelAlpha (const uint32 argb) throw()
  15214. {
  15215. a = (uint8) (argb >> 24);
  15216. }
  15217. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  15218. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  15219. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  15220. forcedinline uint8 getAlpha() const throw() { return a; }
  15221. forcedinline uint8 getRed() const throw() { return 0; }
  15222. forcedinline uint8 getGreen() const throw() { return 0; }
  15223. forcedinline uint8 getBlue() const throw() { return 0; }
  15224. /** Blends another pixel onto this one.
  15225. This takes into account the opacity of the pixel being overlaid, and blends
  15226. it accordingly.
  15227. */
  15228. template <class Pixel>
  15229. forcedinline void blend (const Pixel& src) throw()
  15230. {
  15231. const int srcA = src.getAlpha();
  15232. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  15233. }
  15234. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15235. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15236. being used, so this can blend semi-transparently from a PixelRGB argument.
  15237. */
  15238. template <class Pixel>
  15239. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15240. {
  15241. ++extraAlpha;
  15242. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  15243. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  15244. }
  15245. /** Blends another pixel with this one, creating a colour that is somewhere
  15246. between the two, as specified by the amount.
  15247. */
  15248. template <class Pixel>
  15249. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15250. {
  15251. a += ((src,getAlpha() - a) * amount) >> 8;
  15252. }
  15253. /** Copies another pixel colour over this one.
  15254. This doesn't blend it - this colour is simply replaced by the other one.
  15255. */
  15256. template <class Pixel>
  15257. forcedinline void set (const Pixel& src) throw()
  15258. {
  15259. a = src.getAlpha();
  15260. }
  15261. /** Replaces the colour's alpha value with another one. */
  15262. forcedinline void setAlpha (const uint8 newAlpha) throw()
  15263. {
  15264. a = newAlpha;
  15265. }
  15266. /** Multiplies the colour's alpha value with another one. */
  15267. forcedinline void multiplyAlpha (int multiplier) throw()
  15268. {
  15269. ++multiplier;
  15270. a = (uint8) ((a * multiplier) >> 8);
  15271. }
  15272. forcedinline void multiplyAlpha (const float multiplier) throw()
  15273. {
  15274. a = (uint8) (a * multiplier);
  15275. }
  15276. /** Sets the pixel's colour from individual components. */
  15277. forcedinline void setARGB (const uint8 a_, const uint8 r, const uint8 g, const uint8 b) throw()
  15278. {
  15279. a = a_;
  15280. }
  15281. /** Premultiplies the pixel's RGB values by its alpha. */
  15282. forcedinline void premultiply() throw()
  15283. {
  15284. }
  15285. /** Unpremultiplies the pixel's RGB values. */
  15286. forcedinline void unpremultiply() throw()
  15287. {
  15288. }
  15289. forcedinline void desaturate() throw()
  15290. {
  15291. }
  15292. private:
  15293. uint8 a : 8;
  15294. } PACKED;
  15295. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  15296. {
  15297. blend (PixelARGB (src.getARGB()));
  15298. }
  15299. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  15300. {
  15301. uint32 sargb = src.getARGB();
  15302. const uint32 alpha = 0x100 - (sargb >> 24);
  15303. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15304. sargb += 0xff00ff00 & (getAG() * alpha);
  15305. argb = sargb;
  15306. }
  15307. #if JUCE_MSVC
  15308. #pragma pack (pop)
  15309. #endif
  15310. #undef PACKED
  15311. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  15312. /********* End of inlined file: juce_PixelFormats.h *********/
  15313. /**
  15314. Represents a colour, also including a transparency value.
  15315. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  15316. */
  15317. class JUCE_API Colour
  15318. {
  15319. public:
  15320. /** Creates a transparent black colour. */
  15321. Colour() throw();
  15322. /** Creates a copy of another Colour object. */
  15323. Colour (const Colour& other) throw();
  15324. /** Creates a colour from a 32-bit ARGB value.
  15325. The format of this number is:
  15326. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  15327. All components in the range 0x00 to 0xff.
  15328. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15329. @see getPixelARGB
  15330. */
  15331. explicit Colour (const uint32 argb) throw();
  15332. /** Creates an opaque colour using 8-bit red, green and blue values */
  15333. Colour (const uint8 red,
  15334. const uint8 green,
  15335. const uint8 blue) throw();
  15336. /** Creates an opaque colour using 8-bit red, green and blue values */
  15337. static const Colour fromRGB (const uint8 red,
  15338. const uint8 green,
  15339. const uint8 blue) throw();
  15340. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  15341. Colour (const uint8 red,
  15342. const uint8 green,
  15343. const uint8 blue,
  15344. const uint8 alpha) throw();
  15345. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  15346. static const Colour fromRGBA (const uint8 red,
  15347. const uint8 green,
  15348. const uint8 blue,
  15349. const uint8 alpha) throw();
  15350. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  15351. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  15352. Values outside the valid range will be clipped.
  15353. */
  15354. Colour (const uint8 red,
  15355. const uint8 green,
  15356. const uint8 blue,
  15357. const float alpha) throw();
  15358. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  15359. static const Colour fromRGBAFloat (const uint8 red,
  15360. const uint8 green,
  15361. const uint8 blue,
  15362. const float alpha) throw();
  15363. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  15364. The floating point values must be between 0.0 and 1.0.
  15365. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15366. Values outside the valid range will be clipped.
  15367. */
  15368. Colour (const float hue,
  15369. const float saturation,
  15370. const float brightness,
  15371. const uint8 alpha) throw();
  15372. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  15373. All values must be between 0.0 and 1.0.
  15374. Numbers outside the valid range will be clipped.
  15375. */
  15376. Colour (const float hue,
  15377. const float saturation,
  15378. const float brightness,
  15379. const float alpha) throw();
  15380. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  15381. The floating point values must be between 0.0 and 1.0.
  15382. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15383. Values outside the valid range will be clipped.
  15384. */
  15385. static const Colour fromHSV (const float hue,
  15386. const float saturation,
  15387. const float brightness,
  15388. const float alpha) throw();
  15389. /** Destructor. */
  15390. ~Colour() throw();
  15391. /** Copies another Colour object. */
  15392. const Colour& operator= (const Colour& other) throw();
  15393. /** Compares two colours. */
  15394. bool operator== (const Colour& other) const throw();
  15395. /** Compares two colours. */
  15396. bool operator!= (const Colour& other) const throw();
  15397. /** Returns the red component of this colour.
  15398. @returns a value between 0x00 and 0xff.
  15399. */
  15400. uint8 getRed() const throw() { return argb.getRed(); }
  15401. /** Returns the green component of this colour.
  15402. @returns a value between 0x00 and 0xff.
  15403. */
  15404. uint8 getGreen() const throw() { return argb.getGreen(); }
  15405. /** Returns the blue component of this colour.
  15406. @returns a value between 0x00 and 0xff.
  15407. */
  15408. uint8 getBlue() const throw() { return argb.getBlue(); }
  15409. /** Returns the red component of this colour as a floating point value.
  15410. @returns a value between 0.0 and 1.0
  15411. */
  15412. float getFloatRed() const throw();
  15413. /** Returns the green component of this colour as a floating point value.
  15414. @returns a value between 0.0 and 1.0
  15415. */
  15416. float getFloatGreen() const throw();
  15417. /** Returns the blue component of this colour as a floating point value.
  15418. @returns a value between 0.0 and 1.0
  15419. */
  15420. float getFloatBlue() const throw();
  15421. /** Returns a premultiplied ARGB pixel object that represents this colour.
  15422. */
  15423. const PixelARGB getPixelARGB() const throw();
  15424. /** Returns a 32-bit integer that represents this colour.
  15425. The format of this number is:
  15426. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  15427. */
  15428. uint32 getARGB() const throw();
  15429. /** Returns the colour's alpha (opacity).
  15430. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  15431. */
  15432. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  15433. /** Returns the colour's alpha (opacity) as a floating point value.
  15434. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  15435. */
  15436. float getFloatAlpha() const throw();
  15437. /** Returns true if this colour is completely opaque.
  15438. Equivalent to (getAlpha() == 0xff).
  15439. */
  15440. bool isOpaque() const throw();
  15441. /** Returns true if this colour is completely transparent.
  15442. Equivalent to (getAlpha() == 0x00).
  15443. */
  15444. bool isTransparent() const throw();
  15445. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  15446. const Colour withAlpha (const uint8 newAlpha) const throw();
  15447. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  15448. const Colour withAlpha (const float newAlpha) const throw();
  15449. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  15450. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  15451. */
  15452. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  15453. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  15454. If the foreground colour is semi-transparent, it is blended onto this colour
  15455. accordingly.
  15456. */
  15457. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  15458. /** Returns a colour that lies somewhere between this one and another.
  15459. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  15460. is 1.0, the result is 100% of the other colour.
  15461. */
  15462. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  15463. /** Returns the colour's hue component.
  15464. The value returned is in the range 0.0 to 1.0
  15465. */
  15466. float getHue() const throw();
  15467. /** Returns the colour's saturation component.
  15468. The value returned is in the range 0.0 to 1.0
  15469. */
  15470. float getSaturation() const throw();
  15471. /** Returns the colour's brightness component.
  15472. The value returned is in the range 0.0 to 1.0
  15473. */
  15474. float getBrightness() const throw();
  15475. /** Returns the colour's hue, saturation and brightness components all at once.
  15476. The values returned are in the range 0.0 to 1.0
  15477. */
  15478. void getHSB (float& hue,
  15479. float& saturation,
  15480. float& brightness) const throw();
  15481. /** Returns a copy of this colour with a different hue. */
  15482. const Colour withHue (const float newHue) const throw();
  15483. /** Returns a copy of this colour with a different saturation. */
  15484. const Colour withSaturation (const float newSaturation) const throw();
  15485. /** Returns a copy of this colour with a different brightness.
  15486. @see brighter, darker, withMultipliedBrightness
  15487. */
  15488. const Colour withBrightness (const float newBrightness) const throw();
  15489. /** Returns a copy of this colour with it hue rotated.
  15490. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  15491. @see brighter, darker, withMultipliedBrightness
  15492. */
  15493. const Colour withRotatedHue (const float amountToRotate) const throw();
  15494. /** Returns a copy of this colour with its saturation multiplied by the given value.
  15495. The new colour's saturation is (this->getSaturation() * multiplier)
  15496. (the result is clipped to legal limits).
  15497. */
  15498. const Colour withMultipliedSaturation (const float multiplier) const throw();
  15499. /** Returns a copy of this colour with its brightness multiplied by the given value.
  15500. The new colour's saturation is (this->getBrightness() * multiplier)
  15501. (the result is clipped to legal limits).
  15502. */
  15503. const Colour withMultipliedBrightness (const float amount) const throw();
  15504. /** Returns a brighter version of this colour.
  15505. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  15506. unchanged, and higher values make it brighter
  15507. @see withMultipliedBrightness
  15508. */
  15509. const Colour brighter (float amountBrighter = 0.4f) const throw();
  15510. /** Returns a darker version of this colour.
  15511. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  15512. unchanged, and higher values make it darker
  15513. @see withMultipliedBrightness
  15514. */
  15515. const Colour darker (float amountDarker = 0.4f) const throw();
  15516. /** Returns a colour that will be clearly visible against this colour.
  15517. The amount parameter indicates how contrasting the new colour should
  15518. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  15519. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  15520. return white; Colours::white.contrasting (1.0f) will return black, etc.
  15521. */
  15522. const Colour contrasting (const float amount = 1.0f) const throw();
  15523. /** Returns a colour that contrasts against two colours.
  15524. Looks for a colour that contrasts with both of the colours passed-in.
  15525. Handy for things like choosing a highlight colour in text editors, etc.
  15526. */
  15527. static const Colour contrasting (const Colour& colour1,
  15528. const Colour& colour2) throw();
  15529. /** Returns an opaque shade of grey.
  15530. @param brightness the level of grey to return - 0 is black, 1.0 is white
  15531. */
  15532. static const Colour greyLevel (const float brightness) throw();
  15533. /** Returns a stringified version of this colour.
  15534. The string can be turned back into a colour using the fromString() method.
  15535. */
  15536. const String toString() const throw();
  15537. /** Reads the colour from a string that was created with toString().
  15538. */
  15539. static const Colour fromString (const String& encodedColourString);
  15540. juce_UseDebuggingNewOperator
  15541. private:
  15542. PixelARGB argb;
  15543. };
  15544. #endif // __JUCE_COLOUR_JUCEHEADER__
  15545. /********* End of inlined file: juce_Colour.h *********/
  15546. /**
  15547. Contains a set of predefined named colours (mostly standard HTML colours)
  15548. @see Colour, Colours::greyLevel
  15549. */
  15550. class Colours
  15551. {
  15552. public:
  15553. static JUCE_API const Colour
  15554. transparentBlack, /**< ARGB = 0x00000000 */
  15555. transparentWhite, /**< ARGB = 0x00ffffff */
  15556. black, /**< ARGB = 0xff000000 */
  15557. white, /**< ARGB = 0xffffffff */
  15558. blue, /**< ARGB = 0xff0000ff */
  15559. grey, /**< ARGB = 0xff808080 */
  15560. green, /**< ARGB = 0xff008000 */
  15561. red, /**< ARGB = 0xffff0000 */
  15562. yellow, /**< ARGB = 0xffffff00 */
  15563. aliceblue, antiquewhite, aqua, aquamarine,
  15564. azure, beige, bisque, blanchedalmond,
  15565. blueviolet, brown, burlywood, cadetblue,
  15566. chartreuse, chocolate, coral, cornflowerblue,
  15567. cornsilk, crimson, cyan, darkblue,
  15568. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  15569. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  15570. darkorchid, darkred, darksalmon, darkseagreen,
  15571. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  15572. deeppink, deepskyblue, dimgrey, dodgerblue,
  15573. firebrick, floralwhite, forestgreen, fuchsia,
  15574. gainsboro, gold, goldenrod, greenyellow,
  15575. honeydew, hotpink, indianred, indigo,
  15576. ivory, khaki, lavender, lavenderblush,
  15577. lemonchiffon, lightblue, lightcoral, lightcyan,
  15578. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  15579. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  15580. lightsteelblue, lightyellow, lime, limegreen,
  15581. linen, magenta, maroon, mediumaquamarine,
  15582. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  15583. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  15584. midnightblue, mintcream, mistyrose, navajowhite,
  15585. navy, oldlace, olive, olivedrab,
  15586. orange, orangered, orchid, palegoldenrod,
  15587. palegreen, paleturquoise, palevioletred, papayawhip,
  15588. peachpuff, peru, pink, plum,
  15589. powderblue, purple, rosybrown, royalblue,
  15590. saddlebrown, salmon, sandybrown, seagreen,
  15591. seashell, sienna, silver, skyblue,
  15592. slateblue, slategrey, snow, springgreen,
  15593. steelblue, tan, teal, thistle,
  15594. tomato, turquoise, violet, wheat,
  15595. whitesmoke, yellowgreen;
  15596. /** Attempts to look up a string in the list of known colour names, and return
  15597. the appropriate colour.
  15598. A non-case-sensitive search is made of the list of predefined colours, and
  15599. if a match is found, that colour is returned. If no match is found, the
  15600. colour passed in as the defaultColour parameter is returned.
  15601. */
  15602. static JUCE_API const Colour findColourForName (const String& colourName,
  15603. const Colour& defaultColour);
  15604. private:
  15605. // this isn't a class you should ever instantiate - it's just here for the
  15606. // static values in it.
  15607. Colours();
  15608. };
  15609. #endif // __JUCE_COLOURS_JUCEHEADER__
  15610. /********* End of inlined file: juce_Colours.h *********/
  15611. /********* Start of inlined file: juce_FillType.h *********/
  15612. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  15613. #define __JUCE_FILLTYPE_JUCEHEADER__
  15614. /********* Start of inlined file: juce_ColourGradient.h *********/
  15615. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  15616. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  15617. /**
  15618. Describes the layout and colours that should be used to paint a colour gradient.
  15619. @see Graphics::setGradientFill
  15620. */
  15621. class JUCE_API ColourGradient
  15622. {
  15623. public:
  15624. /** Creates a gradient object.
  15625. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  15626. colour2 should be. In between them there's a gradient.
  15627. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  15628. its centre.
  15629. The alpha transparencies of the colours are used, so note that
  15630. if you blend from transparent to a solid colour, the RGB of the transparent
  15631. colour will become visible in parts of the gradient. e.g. blending
  15632. from Colour::transparentBlack to Colours::white will produce a
  15633. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  15634. will be white all the way across.
  15635. @see ColourGradient
  15636. */
  15637. ColourGradient (const Colour& colour1,
  15638. const float x1,
  15639. const float y1,
  15640. const Colour& colour2,
  15641. const float x2,
  15642. const float y2,
  15643. const bool isRadial) throw();
  15644. /** Creates an uninitialised gradient.
  15645. If you use this constructor instead of the other one, be sure to set all the
  15646. object's public member variables before using it!
  15647. */
  15648. ColourGradient() throw();
  15649. /** Destructor */
  15650. ~ColourGradient() throw();
  15651. /** Removes any colours that have been added.
  15652. This will also remove any start and end colours, so the gradient won't work. You'll
  15653. need to add more colours with addColour().
  15654. */
  15655. void clearColours() throw();
  15656. /** Adds a colour at a point along the length of the gradient.
  15657. This allows the gradient to go through a spectrum of colours, instead of just a
  15658. start and end colour.
  15659. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  15660. of the distance along the line between the two points
  15661. at which the colour should occur.
  15662. @param colour the colour that should be used at this point
  15663. */
  15664. void addColour (const double proportionAlongGradient,
  15665. const Colour& colour) throw();
  15666. /** Multiplies the alpha value of all the colours by the given scale factor */
  15667. void multiplyOpacity (const float multiplier) throw();
  15668. /** Returns the number of colour-stops that have been added. */
  15669. int getNumColours() const throw();
  15670. /** Returns the position along the length of the gradient of the colour with this index.
  15671. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  15672. */
  15673. double getColourPosition (const int index) const throw();
  15674. /** Returns the colour that was added with a given index.
  15675. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  15676. */
  15677. const Colour getColour (const int index) const throw();
  15678. /** Returns the an interpolated colour at any position along the gradient.
  15679. @param position the position along the gradient, between 0 and 1
  15680. */
  15681. const Colour getColourAtPosition (const float position) const throw();
  15682. /** Creates a set of interpolated premultiplied ARGB values.
  15683. The caller must delete the array that is returned using juce_free().
  15684. */
  15685. PixelARGB* createLookupTable (const AffineTransform& transform, int& numEntries) const throw();
  15686. /** Returns true if all colours are opaque. */
  15687. bool isOpaque() const throw();
  15688. /** Returns true if all colours are completely transparent. */
  15689. bool isInvisible() const throw();
  15690. float x1;
  15691. float y1;
  15692. float x2;
  15693. float y2;
  15694. /** If true, the gradient should be filled circularly, centred around
  15695. (x1, y1), with (x2, y2) defining a point on the circumference.
  15696. If false, the gradient is linear between the two points.
  15697. */
  15698. bool isRadial;
  15699. juce_UseDebuggingNewOperator
  15700. private:
  15701. Array <uint32> colours;
  15702. };
  15703. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  15704. /********* End of inlined file: juce_ColourGradient.h *********/
  15705. class Image;
  15706. /**
  15707. Represents a colour or fill pattern to use for rendering paths.
  15708. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  15709. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  15710. @see Graphics::setFillType, DrawablePath::setFill
  15711. */
  15712. class JUCE_API FillType
  15713. {
  15714. public:
  15715. /** Creates a default fill type, of solid black. */
  15716. FillType() throw();
  15717. /** Creates a fill type of a solid colour.
  15718. @see setColour
  15719. */
  15720. FillType (const Colour& colour) throw();
  15721. /** Creates a gradient fill type.
  15722. @see setGradient
  15723. */
  15724. FillType (const ColourGradient& gradient) throw();
  15725. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  15726. and rotation of the pattern.
  15727. @see setTiledImage
  15728. */
  15729. FillType (const Image& image, const AffineTransform& transform) throw();
  15730. /** Creates a copy of another FillType. */
  15731. FillType (const FillType& other) throw();
  15732. /** Makes a copy of another FillType. */
  15733. const FillType& operator= (const FillType& other) throw();
  15734. /** Destructor. */
  15735. ~FillType() throw();
  15736. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  15737. bool isColour() const throw() { return gradient == 0 && image == 0; }
  15738. /** Returns true if this is a gradient fill. */
  15739. bool isGradient() const throw() { return gradient != 0; }
  15740. /** Returns true if this is a tiled image pattern fill. */
  15741. bool isTiledImage() const throw() { return image != 0; }
  15742. /** Turns this object into a solid colour fill.
  15743. If the object was an image or gradient, those fields will no longer be valid. */
  15744. void setColour (const Colour& newColour) throw();
  15745. /** Turns this object into a gradient fill. */
  15746. void setGradient (const ColourGradient& newGradient) throw();
  15747. /** Turns this object into a tiled image fill type. The transform allows you to set
  15748. the scaling, offset and rotation of the pattern.
  15749. */
  15750. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  15751. /** Changes the opacity that should be used.
  15752. If the fill is a solid colour, this just changes the opacity of that colour. For
  15753. gradients and image tiles, it changes the opacity that will be used for them.
  15754. */
  15755. void setOpacity (const float newOpacity) throw();
  15756. /** Returns the current opacity to be applied to the colour, gradient, or image.
  15757. @see setOpacity
  15758. */
  15759. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  15760. /** The solid colour being used.
  15761. If the fill type is not a solid colour, the alpha channel of this colour indicates
  15762. the opacity that should be used for the fill, and the RGB channels are ignored.
  15763. */
  15764. Colour colour;
  15765. /** Returns the gradient that should be used for filling.
  15766. This will be zero if the object is some other type of fill.
  15767. If a gradient is active, the overall opacity with which it should be applied
  15768. is indicated by the alpha channel of the colour variable.
  15769. */
  15770. ColourGradient* gradient;
  15771. /** Returns the image that should be used for tiling.
  15772. The FillType object just keeps a pointer to this image, it doesn't own it, so you have to
  15773. be careful to make sure the image doesn't get deleted while it's being used.
  15774. If an image fill is active, the overall opacity with which it should be applied
  15775. is indicated by the alpha channel of the colour variable.
  15776. */
  15777. const Image* image;
  15778. /** The transform that should be applied to the image or gradient that's being drawn.
  15779. */
  15780. AffineTransform transform;
  15781. juce_UseDebuggingNewOperator
  15782. };
  15783. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  15784. /********* End of inlined file: juce_FillType.h *********/
  15785. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  15786. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  15787. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  15788. /**
  15789. Defines the method used to postion some kind of rectangular object within
  15790. a rectangular viewport.
  15791. Although similar to Justification, this is more specific, and has some extra
  15792. options.
  15793. */
  15794. class JUCE_API RectanglePlacement
  15795. {
  15796. public:
  15797. /** Creates a RectanglePlacement object using a combination of flags. */
  15798. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  15799. /** Creates a copy of another Justification object. */
  15800. RectanglePlacement (const RectanglePlacement& other) throw();
  15801. /** Copies another Justification object. */
  15802. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  15803. /** Flag values that can be combined and used in the constructor. */
  15804. enum
  15805. {
  15806. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  15807. xLeft = 1,
  15808. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  15809. xRight = 2,
  15810. /** Indicates that the source should be placed in the centre between the left and right
  15811. sides of the available space. */
  15812. xMid = 4,
  15813. /** Indicates that the source's top edge should be aligned with the top edge of the
  15814. destination rectangle. */
  15815. yTop = 8,
  15816. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  15817. destination rectangle. */
  15818. yBottom = 16,
  15819. /** Indicates that the source should be placed in the centre between the top and bottom
  15820. sides of the available space. */
  15821. yMid = 32,
  15822. /** If this flag is set, then the source rectangle will be resized to completely fill
  15823. the destination rectangle, and all other flags are ignored.
  15824. */
  15825. stretchToFit = 64,
  15826. /** If this flag is set, then the source rectangle will be resized so that it is the
  15827. minimum size to completely fill the destination rectangle, without changing its
  15828. aspect ratio. This means that some of the source rectangle may fall outside
  15829. the destination.
  15830. If this flag is not set, the source will be given the maximum size at which none
  15831. of it falls outside the destination rectangle.
  15832. */
  15833. fillDestination = 128,
  15834. /** Indicates that the source rectangle can be reduced in size if required, but should
  15835. never be made larger than its original size.
  15836. */
  15837. onlyReduceInSize = 256,
  15838. /** Indicates that the source rectangle can be enlarged if required, but should
  15839. never be made smaller than its original size.
  15840. */
  15841. onlyIncreaseInSize = 512,
  15842. /** Indicates that the source rectangle's size should be left unchanged.
  15843. */
  15844. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  15845. /** A shorthand value that is equivalent to (xMid | yMid). */
  15846. centred = 4 + 32
  15847. };
  15848. /** Returns the raw flags that are set for this object. */
  15849. inline int getFlags() const throw() { return flags; }
  15850. /** Tests a set of flags for this object.
  15851. @returns true if any of the flags passed in are set on this object.
  15852. */
  15853. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15854. /** Adjusts the position and size of a rectangle to fit it into a space.
  15855. The source rectangle co-ordinates will be adjusted so that they fit into
  15856. the destination rectangle based on this object's flags.
  15857. */
  15858. void applyTo (double& sourceX,
  15859. double& sourceY,
  15860. double& sourceW,
  15861. double& sourceH,
  15862. const double destinationX,
  15863. const double destinationY,
  15864. const double destinationW,
  15865. const double destinationH) const throw();
  15866. /** Returns the transform that should be applied to these source co-ordinates to fit them
  15867. into the destination rectangle using the current flags.
  15868. */
  15869. const AffineTransform getTransformToFit (float sourceX,
  15870. float sourceY,
  15871. float sourceW,
  15872. float sourceH,
  15873. const float destinationX,
  15874. const float destinationY,
  15875. const float destinationW,
  15876. const float destinationH) const throw();
  15877. private:
  15878. int flags;
  15879. };
  15880. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  15881. /********* End of inlined file: juce_RectanglePlacement.h *********/
  15882. class LowLevelGraphicsContext;
  15883. class Image;
  15884. class RectangleList;
  15885. /**
  15886. A graphics context, used for drawing a component or image.
  15887. When a Component needs painting, a Graphics context is passed to its
  15888. Component::paint() method, and this you then call methods within this
  15889. object to actually draw the component's content.
  15890. A Graphics can also be created from an image, to allow drawing directly onto
  15891. that image.
  15892. @see Component::paint
  15893. */
  15894. class JUCE_API Graphics
  15895. {
  15896. public:
  15897. /** Creates a Graphics object to draw directly onto the given image.
  15898. The graphics object that is created will be set up to draw onto the image,
  15899. with the context's clipping area being the entire size of the image, and its
  15900. origin being the image's origin. To draw into a subsection of an image, use the
  15901. reduceClipRegion() and setOrigin() methods.
  15902. Obviously you shouldn't delete the image before this context is deleted.
  15903. */
  15904. Graphics (Image& imageToDrawOnto) throw();
  15905. /** Destructor. */
  15906. ~Graphics() throw();
  15907. /** Changes the current drawing colour.
  15908. This sets the colour that will now be used for drawing operations - it also
  15909. sets the opacity to that of the colour passed-in.
  15910. If a brush is being used when this method is called, the brush will be deselected,
  15911. and any subsequent drawing will be done with a solid colour brush instead.
  15912. @see setOpacity
  15913. */
  15914. void setColour (const Colour& newColour) throw();
  15915. /** Changes the opacity to use with the current colour.
  15916. If a solid colour is being used for drawing, this changes its opacity
  15917. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  15918. If a gradient is being used, this will have no effect on it.
  15919. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  15920. */
  15921. void setOpacity (const float newOpacity) throw();
  15922. /** Sets the context to use a gradient for its fill pattern.
  15923. */
  15924. void setGradientFill (const ColourGradient& gradient) throw();
  15925. /** Sets the context to use a tiled image pattern for filling.
  15926. Make sure that you don't delete this image while it's still being used by
  15927. this context!
  15928. */
  15929. void setTiledImageFill (const Image& imageToUse,
  15930. const int anchorX,
  15931. const int anchorY,
  15932. const float opacity) throw();
  15933. /** Changes the current fill settings.
  15934. @see setColour, setGradientFill, setTiledImageFill
  15935. */
  15936. void setFillType (const FillType& newFill) throw();
  15937. /** Changes the font to use for subsequent text-drawing functions.
  15938. Note there's also a setFont (float, int) method to quickly change the size and
  15939. style of the current font.
  15940. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  15941. */
  15942. void setFont (const Font& newFont) throw();
  15943. /** Changes the size and style of the currently-selected font.
  15944. This is a convenient shortcut that changes the context's current font to a
  15945. different size or style. The typeface won't be changed.
  15946. @see Font
  15947. */
  15948. void setFont (const float newFontHeight,
  15949. const int fontStyleFlags = Font::plain) throw();
  15950. /** Draws a one-line text string.
  15951. This will use the current colour (or brush) to fill the text. The font is the last
  15952. one specified by setFont().
  15953. @param text the string to draw
  15954. @param startX the position to draw the left-hand edge of the text
  15955. @param baselineY the position of the text's baseline
  15956. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  15957. */
  15958. void drawSingleLineText (const String& text,
  15959. const int startX,
  15960. const int baselineY) const throw();
  15961. /** Draws text across multiple lines.
  15962. This will break the text onto a new line where there's a new-line or
  15963. carriage-return character, or at a word-boundary when the text becomes wider
  15964. than the size specified by the maximumLineWidth parameter.
  15965. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  15966. */
  15967. void drawMultiLineText (const String& text,
  15968. const int startX,
  15969. const int baselineY,
  15970. const int maximumLineWidth) const throw();
  15971. /** Renders a string of text as a vector path.
  15972. This allows a string to be transformed with an arbitrary AffineTransform and
  15973. rendered using the current colour/brush. It's much slower than the normal text methods
  15974. but more accurate.
  15975. @see setFont
  15976. */
  15977. void drawTextAsPath (const String& text,
  15978. const AffineTransform& transform) const throw();
  15979. /** Draws a line of text within a specified rectangle.
  15980. The text will be positioned within the rectangle based on the justification
  15981. flags passed-in. If the string is too long to fit inside the rectangle, it will
  15982. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  15983. flag is true).
  15984. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  15985. */
  15986. void drawText (const String& text,
  15987. const int x,
  15988. const int y,
  15989. const int width,
  15990. const int height,
  15991. const Justification& justificationType,
  15992. const bool useEllipsesIfTooBig) const throw();
  15993. /** Tries to draw a text string inside a given space.
  15994. This does its best to make the given text readable within the specified rectangle,
  15995. so it useful for labelling things.
  15996. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  15997. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  15998. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  15999. it's been truncated.
  16000. A Justification parameter lets you specify how the text is laid out within the rectangle,
  16001. both horizontally and vertically.
  16002. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  16003. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  16004. can set this value to 1.0f.
  16005. @see GlyphArrangement::addFittedText
  16006. */
  16007. void drawFittedText (const String& text,
  16008. const int x,
  16009. const int y,
  16010. const int width,
  16011. const int height,
  16012. const Justification& justificationFlags,
  16013. const int maximumNumberOfLines,
  16014. const float minimumHorizontalScale = 0.7f) const throw();
  16015. /** Fills the context's entire clip region with the current colour or brush.
  16016. (See also the fillAll (const Colour&) method which is a quick way of filling
  16017. it with a given colour).
  16018. */
  16019. void fillAll() const throw();
  16020. /** Fills the context's entire clip region with a given colour.
  16021. This leaves the context's current colour and brush unchanged, it just
  16022. uses the specified colour temporarily.
  16023. */
  16024. void fillAll (const Colour& colourToUse) const throw();
  16025. /** Fills a rectangle with the current colour or brush.
  16026. @see drawRect, fillRoundedRectangle
  16027. */
  16028. void fillRect (int x,
  16029. int y,
  16030. int width,
  16031. int height) const throw();
  16032. /** Fills a rectangle with the current colour or brush. */
  16033. void fillRect (const Rectangle& rectangle) const throw();
  16034. /** Fills a rectangle with the current colour or brush.
  16035. This uses sub-pixel positioning so is slower than the fillRect method which
  16036. takes integer co-ordinates.
  16037. */
  16038. void fillRect (const float x,
  16039. const float y,
  16040. const float width,
  16041. const float height) const throw();
  16042. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  16043. @see drawRoundedRectangle, Path::addRoundedRectangle
  16044. */
  16045. void fillRoundedRectangle (const float x,
  16046. const float y,
  16047. const float width,
  16048. const float height,
  16049. const float cornerSize) const throw();
  16050. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  16051. @see drawRoundedRectangle, Path::addRoundedRectangle
  16052. */
  16053. void fillRoundedRectangle (const Rectangle& rectangle,
  16054. const float cornerSize) const throw();
  16055. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  16056. */
  16057. void fillCheckerBoard (int x, int y,
  16058. int width, int height,
  16059. const int checkWidth,
  16060. const int checkHeight,
  16061. const Colour& colour1,
  16062. const Colour& colour2) const throw();
  16063. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16064. The lines are drawn inside the given rectangle, and greater line thicknesses
  16065. extend inwards.
  16066. @see fillRect
  16067. */
  16068. void drawRect (const int x,
  16069. const int y,
  16070. const int width,
  16071. const int height,
  16072. const int lineThickness = 1) const throw();
  16073. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16074. The lines are drawn inside the given rectangle, and greater line thicknesses
  16075. extend inwards.
  16076. @see fillRect
  16077. */
  16078. void drawRect (const float x,
  16079. const float y,
  16080. const float width,
  16081. const float height,
  16082. const float lineThickness = 1.0f) const throw();
  16083. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16084. The lines are drawn inside the given rectangle, and greater line thicknesses
  16085. extend inwards.
  16086. @see fillRect
  16087. */
  16088. void drawRect (const Rectangle& rectangle,
  16089. const int lineThickness = 1) const throw();
  16090. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  16091. @see fillRoundedRectangle, Path::addRoundedRectangle
  16092. */
  16093. void drawRoundedRectangle (const float x,
  16094. const float y,
  16095. const float width,
  16096. const float height,
  16097. const float cornerSize,
  16098. const float lineThickness) const throw();
  16099. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  16100. @see fillRoundedRectangle, Path::addRoundedRectangle
  16101. */
  16102. void drawRoundedRectangle (const Rectangle& rectangle,
  16103. const float cornerSize,
  16104. const float lineThickness) const throw();
  16105. /** Draws a 3D raised (or indented) bevel using two colours.
  16106. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  16107. extend inwards.
  16108. The top-left colour is used for the top- and left-hand edges of the
  16109. bevel; the bottom-right colour is used for the bottom- and right-hand
  16110. edges.
  16111. If useGradient is true, then the bevel fades out to make it look more curved
  16112. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  16113. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  16114. the centre edges are sharp and it fades towards the outside.
  16115. */
  16116. void drawBevel (const int x,
  16117. const int y,
  16118. const int width,
  16119. const int height,
  16120. const int bevelThickness,
  16121. const Colour& topLeftColour = Colours::white,
  16122. const Colour& bottomRightColour = Colours::black,
  16123. const bool useGradient = true,
  16124. const bool sharpEdgeOnOutside = true) const throw();
  16125. /** Draws a pixel using the current colour or brush.
  16126. */
  16127. void setPixel (int x, int y) const throw();
  16128. /** Fills an ellipse with the current colour or brush.
  16129. The ellipse is drawn to fit inside the given rectangle.
  16130. @see drawEllipse, Path::addEllipse
  16131. */
  16132. void fillEllipse (const float x,
  16133. const float y,
  16134. const float width,
  16135. const float height) const throw();
  16136. /** Draws an elliptical stroke using the current colour or brush.
  16137. @see fillEllipse, Path::addEllipse
  16138. */
  16139. void drawEllipse (const float x,
  16140. const float y,
  16141. const float width,
  16142. const float height,
  16143. const float lineThickness) const throw();
  16144. /** Draws a line between two points.
  16145. The line is 1 pixel wide and drawn with the current colour or brush.
  16146. */
  16147. void drawLine (float startX,
  16148. float startY,
  16149. float endX,
  16150. float endY) const throw();
  16151. /** Draws a line between two points with a given thickness.
  16152. @see Path::addLineSegment
  16153. */
  16154. void drawLine (const float startX,
  16155. const float startY,
  16156. const float endX,
  16157. const float endY,
  16158. const float lineThickness) const throw();
  16159. /** Draws a line between two points.
  16160. The line is 1 pixel wide and drawn with the current colour or brush.
  16161. */
  16162. void drawLine (const Line& line) const throw();
  16163. /** Draws a line between two points with a given thickness.
  16164. @see Path::addLineSegment
  16165. */
  16166. void drawLine (const Line& line,
  16167. const float lineThickness) const throw();
  16168. /** Draws a dashed line using a custom set of dash-lengths.
  16169. @param startX the line's start x co-ordinate
  16170. @param startY the line's start y co-ordinate
  16171. @param endX the line's end x co-ordinate
  16172. @param endY the line's end y co-ordinate
  16173. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  16174. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  16175. draw 6 pixels, skip 7 pixels, and then repeat.
  16176. @param numDashLengths the number of elements in the array (this must be an even number).
  16177. @param lineThickness the thickness of the line to draw
  16178. @see PathStrokeType::createDashedStroke
  16179. */
  16180. void drawDashedLine (const float startX,
  16181. const float startY,
  16182. const float endX,
  16183. const float endY,
  16184. const float* const dashLengths,
  16185. const int numDashLengths,
  16186. const float lineThickness = 1.0f) const throw();
  16187. /** Draws a vertical line of pixels at a given x position.
  16188. The x position is an integer, but the top and bottom of the line can be sub-pixel
  16189. positions, and these will be anti-aliased if necessary.
  16190. */
  16191. void drawVerticalLine (const int x, float top, float bottom) const throw();
  16192. /** Draws a horizontal line of pixels at a given y position.
  16193. The y position is an integer, but the left and right ends of the line can be sub-pixel
  16194. positions, and these will be anti-aliased if necessary.
  16195. */
  16196. void drawHorizontalLine (const int y, float left, float right) const throw();
  16197. /** Fills a path using the currently selected colour or brush.
  16198. */
  16199. void fillPath (const Path& path,
  16200. const AffineTransform& transform = AffineTransform::identity) const throw();
  16201. /** Draws a path's outline using the currently selected colour or brush.
  16202. */
  16203. void strokePath (const Path& path,
  16204. const PathStrokeType& strokeType,
  16205. const AffineTransform& transform = AffineTransform::identity) const throw();
  16206. /** Draws a line with an arrowhead.
  16207. @param startX the line's start x co-ordinate
  16208. @param startY the line's start y co-ordinate
  16209. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  16210. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  16211. @param lineThickness the thickness of the line
  16212. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  16213. @param arrowheadLength the length of the arrow head (along the length of the line)
  16214. */
  16215. void drawArrow (const float startX,
  16216. const float startY,
  16217. const float endX,
  16218. const float endY,
  16219. const float lineThickness,
  16220. const float arrowheadWidth,
  16221. const float arrowheadLength) const throw();
  16222. /** Types of rendering quality that can be specified when drawing images.
  16223. @see blendImage, Graphics::setImageResamplingQuality
  16224. */
  16225. enum ResamplingQuality
  16226. {
  16227. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  16228. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  16229. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  16230. };
  16231. /** Changes the quality that will be used when resampling images.
  16232. By default a Graphics object will be set to mediumRenderingQuality.
  16233. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  16234. */
  16235. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  16236. /** Draws an image.
  16237. This will draw the whole of an image, positioning its top-left corner at the
  16238. given co-ordinates, and keeping its size the same. This is the simplest image
  16239. drawing method - the others give more control over the scaling and clipping
  16240. of the images.
  16241. Images are composited using the context's current opacity, so if you
  16242. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16243. (or setColour() with an opaque colour) before drawing images.
  16244. */
  16245. void drawImageAt (const Image* const imageToDraw,
  16246. const int topLeftX,
  16247. const int topLeftY,
  16248. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16249. /** Draws part of an image, rescaling it to fit in a given target region.
  16250. The specified area of the source image is rescaled and drawn to fill the
  16251. specifed destination rectangle.
  16252. Images are composited using the context's current opacity, so if you
  16253. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16254. (or setColour() with an opaque colour) before drawing images.
  16255. @param imageToDraw the image to overlay
  16256. @param destX the left of the destination rectangle
  16257. @param destY the top of the destination rectangle
  16258. @param destWidth the width of the destination rectangle
  16259. @param destHeight the height of the destination rectangle
  16260. @param sourceX the left of the rectangle to copy from the source image
  16261. @param sourceY the top of the rectangle to copy from the source image
  16262. @param sourceWidth the width of the rectangle to copy from the source image
  16263. @param sourceHeight the height of the rectangle to copy from the source image
  16264. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  16265. the source image's alpha channel is used as a mask with
  16266. which to fill the destination using the current colour
  16267. or brush. (If the source is has no alpha channel, then
  16268. it will just fill the target with a solid rectangle)
  16269. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  16270. */
  16271. void drawImage (const Image* const imageToDraw,
  16272. int destX,
  16273. int destY,
  16274. int destWidth,
  16275. int destHeight,
  16276. int sourceX,
  16277. int sourceY,
  16278. int sourceWidth,
  16279. int sourceHeight,
  16280. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16281. /** Draws part of an image, having applied an affine transform to it.
  16282. This lets you throw the image around in some wacky ways, rotate it, shear,
  16283. scale it, etc.
  16284. A subregion is specified within the source image, and all transformations
  16285. will be treated as relative to the origin of this sub-region. So, for example if
  16286. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  16287. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  16288. your image. If you want to use the whole image, then Image::getBounds() returns a
  16289. suitable rectangle to use as the imageSubRegion parameter.
  16290. Images are composited using the context's current opacity, so if you
  16291. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16292. (or setColour() with an opaque colour) before drawing images.
  16293. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  16294. are ignored and it is filled with the current brush, masked by its alpha channel.
  16295. @see setImageResamplingQuality, drawImage
  16296. */
  16297. void drawImageTransformed (const Image* const imageToDraw,
  16298. const Rectangle& imageSubRegion,
  16299. const AffineTransform& transform,
  16300. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16301. /** Draws an image to fit within a designated rectangle.
  16302. If the image is too big or too small for the space, it will be rescaled
  16303. to fit as nicely as it can do without affecting its aspect ratio. It will
  16304. then be placed within the target rectangle according to the justification flags
  16305. specified.
  16306. @param imageToDraw the source image to draw
  16307. @param destX top-left of the target rectangle to fit it into
  16308. @param destY top-left of the target rectangle to fit it into
  16309. @param destWidth size of the target rectangle to fit the image into
  16310. @param destHeight size of the target rectangle to fit the image into
  16311. @param placementWithinTarget this specifies how the image should be positioned
  16312. within the target rectangle - see the RectanglePlacement
  16313. class for more details about this.
  16314. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  16315. alpha channel will be used as a mask with which to
  16316. draw with the current brush or colour. This is
  16317. similar to fillAlphaMap(), and see also drawImage()
  16318. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  16319. */
  16320. void drawImageWithin (const Image* const imageToDraw,
  16321. const int destX,
  16322. const int destY,
  16323. const int destWidth,
  16324. const int destHeight,
  16325. const RectanglePlacement& placementWithinTarget,
  16326. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16327. /** Returns the position of the bounding box for the current clipping region.
  16328. @see getClipRegion, clipRegionIntersects
  16329. */
  16330. const Rectangle getClipBounds() const throw();
  16331. /** Checks whether a rectangle overlaps the context's clipping region.
  16332. If this returns false, no part of the given area can be drawn onto, so this
  16333. method can be used to optimise a component's paint() method, by letting it
  16334. avoid drawing complex objects that aren't within the region being repainted.
  16335. */
  16336. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  16337. /** Intersects the current clipping region with another region.
  16338. @returns true if the resulting clipping region is non-zero in size
  16339. @see setOrigin, clipRegionIntersects
  16340. */
  16341. bool reduceClipRegion (const int x, const int y,
  16342. const int width, const int height) throw();
  16343. /** Intersects the current clipping region with a rectangle list region.
  16344. @returns true if the resulting clipping region is non-zero in size
  16345. @see setOrigin, clipRegionIntersects
  16346. */
  16347. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  16348. /** Intersects the current clipping region with a path.
  16349. @returns true if the resulting clipping region is non-zero in size
  16350. @see reduceClipRegion
  16351. */
  16352. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity) throw();
  16353. /** Intersects the current clipping region with an image's alpha-channel.
  16354. The current clipping path is intersected with the area covered by this image's
  16355. alpha-channel, after the image has been transformed by the specified matrix.
  16356. @param image the image whose alpha-channel should be used. If the image doesn't
  16357. have an alpha-channel, it is treated as entirely opaque.
  16358. @param sourceClipRegion a subsection of the image that should be used. To use the
  16359. entire image, just pass a rectangle of bounds
  16360. (0, 0, image.getWidth(), image.getHeight()).
  16361. @param transform a matrix to apply to the image
  16362. @returns true if the resulting clipping region is non-zero in size
  16363. @see reduceClipRegion
  16364. */
  16365. bool reduceClipRegion (const Image& image, const Rectangle& sourceClipRegion,
  16366. const AffineTransform& transform) throw();
  16367. /** Excludes a rectangle to stop it being drawn into. */
  16368. void excludeClipRegion (const int x, const int y,
  16369. const int width, const int height) throw();
  16370. /** Returns true if no drawing can be done because the clip region is zero. */
  16371. bool isClipEmpty() const throw();
  16372. /** Saves the current graphics state on an internal stack.
  16373. To restore the state, use restoreState().
  16374. */
  16375. void saveState() throw();
  16376. /** Restores a graphics state that was previously saved with saveState().
  16377. */
  16378. void restoreState() throw();
  16379. /** Moves the position of the context's origin.
  16380. This changes the position that the context considers to be (0, 0) to
  16381. the specified position.
  16382. So if you call setOrigin (100, 100), then the position that was previously
  16383. referred to as (100, 100) will subsequently be considered to be (0, 0).
  16384. @see reduceClipRegion
  16385. */
  16386. void setOrigin (const int newOriginX,
  16387. const int newOriginY) throw();
  16388. /** Resets the current colour, brush, and font to default settings. */
  16389. void resetToDefaultState() throw();
  16390. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  16391. bool isVectorDevice() const throw();
  16392. juce_UseDebuggingNewOperator
  16393. /** Create a graphics that uses a given low-level renderer.
  16394. For internal use only.
  16395. NB. The context will NOT be deleted by this object when it is deleted.
  16396. */
  16397. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  16398. /** @internal */
  16399. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  16400. private:
  16401. LowLevelGraphicsContext* const context;
  16402. const bool ownsContext;
  16403. bool saveStatePending;
  16404. void saveStateIfPending() throw();
  16405. const Graphics& operator= (const Graphics& other);
  16406. Graphics (const Graphics&);
  16407. };
  16408. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  16409. /********* End of inlined file: juce_Graphics.h *********/
  16410. /**
  16411. A graphical effect filter that can be applied to components.
  16412. An ImageEffectFilter can be applied to the image that a component
  16413. paints before it hits the screen.
  16414. This is used for adding effects like shadows, blurs, etc.
  16415. @see Component::setComponentEffect
  16416. */
  16417. class JUCE_API ImageEffectFilter
  16418. {
  16419. public:
  16420. /** Overridden to render the effect.
  16421. The implementation of this method must use the image that is passed in
  16422. as its source, and should render its output to the graphics context passed in.
  16423. @param sourceImage the image that the source component has just rendered with
  16424. its paint() method. The image may or may not have an alpha
  16425. channel, depending on whether the component is opaque.
  16426. @param destContext the graphics context to use to draw the resultant image.
  16427. */
  16428. virtual void applyEffect (Image& sourceImage,
  16429. Graphics& destContext) = 0;
  16430. /** Destructor. */
  16431. virtual ~ImageEffectFilter() {}
  16432. };
  16433. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  16434. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  16435. /********* Start of inlined file: juce_RectangleList.h *********/
  16436. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  16437. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  16438. /**
  16439. Maintains a set of rectangles as a complex region.
  16440. This class allows a set of rectangles to be treated as a solid shape, and can
  16441. add and remove rectangular sections of it, and simplify overlapping or
  16442. adjacent rectangles.
  16443. @see Rectangle
  16444. */
  16445. class JUCE_API RectangleList
  16446. {
  16447. public:
  16448. /** Creates an empty RectangleList */
  16449. RectangleList() throw();
  16450. /** Creates a copy of another list */
  16451. RectangleList (const RectangleList& other) throw();
  16452. /** Creates a list containing just one rectangle. */
  16453. RectangleList (const Rectangle& rect) throw();
  16454. /** Copies this list from another one. */
  16455. const RectangleList& operator= (const RectangleList& other) throw();
  16456. /** Destructor. */
  16457. ~RectangleList() throw();
  16458. /** Returns true if the region is empty. */
  16459. bool isEmpty() const throw();
  16460. /** Returns the number of rectangles in the list. */
  16461. int getNumRectangles() const throw() { return rects.size(); }
  16462. /** Returns one of the rectangles at a particular index.
  16463. @returns the rectangle at the index, or an empty rectangle if the
  16464. index is out-of-range.
  16465. */
  16466. const Rectangle getRectangle (const int index) const throw();
  16467. /** Removes all rectangles to leave an empty region. */
  16468. void clear() throw();
  16469. /** Merges a new rectangle into the list.
  16470. The rectangle being added will first be clipped to remove any parts of it
  16471. that overlap existing rectangles in the list.
  16472. */
  16473. void add (const int x, const int y,
  16474. const int w, const int h) throw();
  16475. /** Merges a new rectangle into the list.
  16476. The rectangle being added will first be clipped to remove any parts of it
  16477. that overlap existing rectangles in the list, and adjacent rectangles will be
  16478. merged into it.
  16479. */
  16480. void add (const Rectangle& rect) throw();
  16481. /** Dumbly adds a rectangle to the list without checking for overlaps.
  16482. This simply adds the rectangle to the end, it doesn't merge it or remove
  16483. any overlapping bits.
  16484. */
  16485. void addWithoutMerging (const Rectangle& rect) throw();
  16486. /** Merges another rectangle list into this one.
  16487. Any overlaps between the two lists will be clipped, so that the result is
  16488. the union of both lists.
  16489. */
  16490. void add (const RectangleList& other) throw();
  16491. /** Removes a rectangular region from the list.
  16492. Any rectangles in the list which overlap this will be clipped and subdivided
  16493. if necessary.
  16494. */
  16495. void subtract (const Rectangle& rect) throw();
  16496. /** Removes all areas in another RectangleList from this one.
  16497. Any rectangles in the list which overlap this will be clipped and subdivided
  16498. if necessary.
  16499. */
  16500. void subtract (const RectangleList& otherList) throw();
  16501. /** Removes any areas of the region that lie outside a given rectangle.
  16502. Any rectangles in the list which overlap this will be clipped and subdivided
  16503. if necessary.
  16504. Returns true if the resulting region is not empty, false if it is empty.
  16505. @see getIntersectionWith
  16506. */
  16507. bool clipTo (const Rectangle& rect) throw();
  16508. /** Removes any areas of the region that lie outside a given rectangle list.
  16509. Any rectangles in this object which overlap the specified list will be clipped
  16510. and subdivided if necessary.
  16511. Returns true if the resulting region is not empty, false if it is empty.
  16512. @see getIntersectionWith
  16513. */
  16514. bool clipTo (const RectangleList& other) throw();
  16515. /** Creates a region which is the result of clipping this one to a given rectangle.
  16516. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  16517. resulting region into the list whose reference is passed-in.
  16518. Returns true if the resulting region is not empty, false if it is empty.
  16519. @see clipTo
  16520. */
  16521. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  16522. /** Swaps the contents of this and another list.
  16523. This swaps their internal pointers, so is hugely faster than using copy-by-value
  16524. to swap them.
  16525. */
  16526. void swapWith (RectangleList& otherList) throw();
  16527. /** Checks whether the region contains a given point.
  16528. @returns true if the point lies within one of the rectangles in the list
  16529. */
  16530. bool containsPoint (const int x, const int y) const throw();
  16531. /** Checks whether the region contains the whole of a given rectangle.
  16532. @returns true all parts of the rectangle passed in lie within the region
  16533. defined by this object
  16534. @see intersectsRectangle, containsPoint
  16535. */
  16536. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  16537. /** Checks whether the region contains any part of a given rectangle.
  16538. @returns true if any part of the rectangle passed in lies within the region
  16539. defined by this object
  16540. @see containsRectangle
  16541. */
  16542. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  16543. /** Checks whether this region intersects any part of another one.
  16544. @see intersectsRectangle
  16545. */
  16546. bool intersects (const RectangleList& other) const throw();
  16547. /** Returns the smallest rectangle that can enclose the whole of this region. */
  16548. const Rectangle getBounds() const throw();
  16549. /** Optimises the list into a minimum number of constituent rectangles.
  16550. This will try to combine any adjacent rectangles into larger ones where
  16551. possible, to simplify lists that might have been fragmented by repeated
  16552. add/subtract calls.
  16553. */
  16554. void consolidate() throw();
  16555. /** Adds an x and y value to all the co-ordinates. */
  16556. void offsetAll (const int dx, const int dy) throw();
  16557. /** Creates a Path object to represent this region. */
  16558. const Path toPath() const throw();
  16559. /** An iterator for accessing all the rectangles in a RectangleList. */
  16560. class Iterator
  16561. {
  16562. public:
  16563. Iterator (const RectangleList& list) throw();
  16564. ~Iterator() throw();
  16565. /** Advances to the next rectangle, and returns true if it's not finished.
  16566. Call this before using getRectangle() to find the rectangle that was returned.
  16567. */
  16568. bool next() throw();
  16569. /** Returns the current rectangle. */
  16570. const Rectangle* getRectangle() const throw() { return current; }
  16571. juce_UseDebuggingNewOperator
  16572. private:
  16573. const Rectangle* current;
  16574. const RectangleList& owner;
  16575. int index;
  16576. Iterator (const Iterator&);
  16577. const Iterator& operator= (const Iterator&);
  16578. };
  16579. juce_UseDebuggingNewOperator
  16580. private:
  16581. friend class Iterator;
  16582. Array <Rectangle> rects;
  16583. };
  16584. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  16585. /********* End of inlined file: juce_RectangleList.h *********/
  16586. /********* Start of inlined file: juce_BorderSize.h *********/
  16587. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  16588. #define __JUCE_BORDERSIZE_JUCEHEADER__
  16589. /**
  16590. Specifies a set of gaps to be left around the sides of a rectangle.
  16591. This is basically the size of the spaces at the top, bottom, left and right of
  16592. a rectangle. It's used by various component classes to specify borders.
  16593. @see Rectangle
  16594. */
  16595. class JUCE_API BorderSize
  16596. {
  16597. public:
  16598. /** Creates a null border.
  16599. All sizes are left as 0.
  16600. */
  16601. BorderSize() throw();
  16602. /** Creates a copy of another border. */
  16603. BorderSize (const BorderSize& other) throw();
  16604. /** Creates a border with the given gaps. */
  16605. BorderSize (const int topGap,
  16606. const int leftGap,
  16607. const int bottomGap,
  16608. const int rightGap) throw();
  16609. /** Creates a border with the given gap on all sides. */
  16610. BorderSize (const int allGaps) throw();
  16611. /** Destructor. */
  16612. ~BorderSize() throw();
  16613. /** Returns the gap that should be left at the top of the region. */
  16614. int getTop() const throw() { return top; }
  16615. /** Returns the gap that should be left at the top of the region. */
  16616. int getLeft() const throw() { return left; }
  16617. /** Returns the gap that should be left at the top of the region. */
  16618. int getBottom() const throw() { return bottom; }
  16619. /** Returns the gap that should be left at the top of the region. */
  16620. int getRight() const throw() { return right; }
  16621. /** Returns the sum of the top and bottom gaps. */
  16622. int getTopAndBottom() const throw() { return top + bottom; }
  16623. /** Returns the sum of the left and right gaps. */
  16624. int getLeftAndRight() const throw() { return left + right; }
  16625. /** Changes the top gap. */
  16626. void setTop (const int newTopGap) throw();
  16627. /** Changes the left gap. */
  16628. void setLeft (const int newLeftGap) throw();
  16629. /** Changes the bottom gap. */
  16630. void setBottom (const int newBottomGap) throw();
  16631. /** Changes the right gap. */
  16632. void setRight (const int newRightGap) throw();
  16633. /** Returns a rectangle with these borders removed from it. */
  16634. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  16635. /** Removes this border from a given rectangle. */
  16636. void subtractFrom (Rectangle& rectangle) const throw();
  16637. /** Returns a rectangle with these borders added around it. */
  16638. const Rectangle addedTo (const Rectangle& original) const throw();
  16639. /** Adds this border around a given rectangle. */
  16640. void addTo (Rectangle& original) const throw();
  16641. bool operator== (const BorderSize& other) const throw();
  16642. bool operator!= (const BorderSize& other) const throw();
  16643. juce_UseDebuggingNewOperator
  16644. private:
  16645. int top, left, bottom, right;
  16646. };
  16647. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  16648. /********* End of inlined file: juce_BorderSize.h *********/
  16649. /********* Start of inlined file: juce_ComponentPeer.h *********/
  16650. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  16651. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  16652. class Component;
  16653. class Graphics;
  16654. class ComponentBoundsConstrainer;
  16655. class ComponentDeletionWatcher;
  16656. /**
  16657. The base class for window objects that wrap a component as a real operating
  16658. system object.
  16659. This is an abstract base class - the platform specific code contains default
  16660. implementations of it that create and manage windows.
  16661. @see Component::createNewPeer
  16662. */
  16663. class JUCE_API ComponentPeer : public MessageListener
  16664. {
  16665. public:
  16666. /** A combination of these flags is passed to the ComponentPeer constructor. */
  16667. enum StyleFlags
  16668. {
  16669. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  16670. entry on the taskbar (ignored on MacOSX) */
  16671. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  16672. tooltip, etc. */
  16673. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  16674. through it (may not be possible on some platforms). */
  16675. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  16676. title bar and frame\. if not specified, the window will be
  16677. borderless. */
  16678. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  16679. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  16680. minimise button on it. */
  16681. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  16682. maximise button on it. */
  16683. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  16684. close button on it. */
  16685. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  16686. not be possible on all platforms). */
  16687. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  16688. do its own repainting, but only to repaint when the
  16689. performAnyPendingRepaintsNow() method is called. */
  16690. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  16691. be used for things like plugin windows, to stop them interfering
  16692. with the host's shortcut keys */
  16693. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  16694. };
  16695. /** Creates a peer.
  16696. The component is the one that we intend to represent, and the style flags are
  16697. a combination of the values in the StyleFlags enum
  16698. */
  16699. ComponentPeer (Component* const component,
  16700. const int styleFlags) throw();
  16701. /** Destructor. */
  16702. virtual ~ComponentPeer();
  16703. /** Returns the component being represented by this peer. */
  16704. Component* getComponent() const throw() { return component; }
  16705. /** Returns the set of style flags that were set when the window was created.
  16706. @see Component::addToDesktop
  16707. */
  16708. int getStyleFlags() const throw() { return styleFlags; }
  16709. /** Returns the raw handle to whatever kind of window is being used.
  16710. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  16711. but rememeber there's no guarantees what you'll get back.
  16712. */
  16713. virtual void* getNativeHandle() const = 0;
  16714. /** Shows or hides the window. */
  16715. virtual void setVisible (bool shouldBeVisible) = 0;
  16716. /** Changes the title of the window. */
  16717. virtual void setTitle (const String& title) = 0;
  16718. /** Moves the window without changing its size.
  16719. If the native window is contained in another window, then the co-ordinates are
  16720. relative to the parent window's origin, not the screen origin.
  16721. This should result in a callback to handleMovedOrResized().
  16722. */
  16723. virtual void setPosition (int x, int y) = 0;
  16724. /** Resizes the window without changing its position.
  16725. This should result in a callback to handleMovedOrResized().
  16726. */
  16727. virtual void setSize (int w, int h) = 0;
  16728. /** Moves and resizes the window.
  16729. If the native window is contained in another window, then the co-ordinates are
  16730. relative to the parent window's origin, not the screen origin.
  16731. This should result in a callback to handleMovedOrResized().
  16732. */
  16733. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  16734. /** Returns the current position and size of the window.
  16735. If the native window is contained in another window, then the co-ordinates are
  16736. relative to the parent window's origin, not the screen origin.
  16737. */
  16738. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  16739. /** Returns the x-position of this window, relative to the screen's origin. */
  16740. virtual int getScreenX() const = 0;
  16741. /** Returns the y-position of this window, relative to the screen's origin. */
  16742. virtual int getScreenY() const = 0;
  16743. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  16744. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  16745. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  16746. virtual void globalPositionToRelative (int& x, int& y) = 0;
  16747. /** Minimises the window. */
  16748. virtual void setMinimised (bool shouldBeMinimised) = 0;
  16749. /** True if the window is currently minimised. */
  16750. virtual bool isMinimised() const = 0;
  16751. /** Enable/disable fullscreen mode for the window. */
  16752. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  16753. /** True if the window is currently full-screen. */
  16754. virtual bool isFullScreen() const = 0;
  16755. /** Sets the size to restore to if fullscreen mode is turned off. */
  16756. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  16757. /** Returns the size to restore to if fullscreen mode is turned off. */
  16758. const Rectangle& getNonFullScreenBounds() const throw();
  16759. /** Attempts to change the icon associated with this window.
  16760. */
  16761. virtual void setIcon (const Image& newIcon) = 0;
  16762. /** Sets a constrainer to use if the peer can resize itself.
  16763. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  16764. */
  16765. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  16766. /** Returns the current constrainer, if one has been set. */
  16767. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  16768. /** Checks if a point is in the window.
  16769. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  16770. is false, then this returns false if the point is actually inside a child of this
  16771. window.
  16772. */
  16773. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  16774. /** Returns the size of the window frame that's around this window.
  16775. Whether or not the window has a normal window frame depends on the flags
  16776. that were set when the window was created by Component::addToDesktop()
  16777. */
  16778. virtual const BorderSize getFrameSize() const = 0;
  16779. /** This is called when the window's bounds change.
  16780. A peer implementation must call this when the window is moved and resized, so that
  16781. this method can pass the message on to the component.
  16782. */
  16783. void handleMovedOrResized();
  16784. /** This is called if the screen resolution changes.
  16785. A peer implementation must call this if the monitor arrangement changes or the available
  16786. screen size changes.
  16787. */
  16788. void handleScreenSizeChange();
  16789. /** This is called to repaint the component into the given context. */
  16790. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  16791. /** Sets this window to either be always-on-top or normal.
  16792. Some kinds of window might not be able to do this, so should return false.
  16793. */
  16794. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  16795. /** Brings the window to the top, optionally also giving it focus. */
  16796. virtual void toFront (bool makeActive) = 0;
  16797. /** Moves the window to be just behind another one. */
  16798. virtual void toBehind (ComponentPeer* other) = 0;
  16799. /** Called when the window is brought to the front, either by the OS or by a call
  16800. to toFront().
  16801. */
  16802. void handleBroughtToFront();
  16803. /** True if the window has the keyboard focus. */
  16804. virtual bool isFocused() const = 0;
  16805. /** Tries to give the window keyboard focus. */
  16806. virtual void grabFocus() = 0;
  16807. /** Tells the window that text input may be required at the given position.
  16808. This may cause things like a virtual on-screen keyboard to appear, depending
  16809. on the OS.
  16810. */
  16811. virtual void textInputRequired (int x, int y) = 0;
  16812. /** Called when the window gains keyboard focus. */
  16813. void handleFocusGain();
  16814. /** Called when the window loses keyboard focus. */
  16815. void handleFocusLoss();
  16816. Component* getLastFocusedSubcomponent() const throw();
  16817. /** Called when a key is pressed.
  16818. For keycode info, see the KeyPress class.
  16819. Returns true if the keystroke was used.
  16820. */
  16821. bool handleKeyPress (const int keyCode,
  16822. const juce_wchar textCharacter);
  16823. /** Called whenever a key is pressed or released.
  16824. Returns true if the keystroke was used.
  16825. */
  16826. bool handleKeyUpOrDown (const bool isKeyDown);
  16827. /** Called whenever a modifier key is pressed or released. */
  16828. void handleModifierKeysChange();
  16829. /** Invalidates a region of the window to be repainted asynchronously. */
  16830. virtual void repaint (int x, int y, int w, int h) = 0;
  16831. /** This can be called (from the message thread) to cause the immediate redrawing
  16832. of any areas of this window that need repainting.
  16833. You shouldn't ever really need to use this, it's mainly for special purposes
  16834. like supporting audio plugins where the host's event loop is out of our control.
  16835. */
  16836. virtual void performAnyPendingRepaintsNow() = 0;
  16837. void handleMouseEnter (int x, int y, const int64 time);
  16838. void handleMouseMove (int x, int y, const int64 time);
  16839. void handleMouseDown (int x, int y, const int64 time);
  16840. void handleMouseDrag (int x, int y, const int64 time);
  16841. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16842. void handleMouseExit (int x, int y, const int64 time);
  16843. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  16844. /** Causes a mouse-move callback to be made asynchronously. */
  16845. void sendFakeMouseMove() throw();
  16846. void handleUserClosingWindow();
  16847. void handleFileDragMove (const StringArray& files, int x, int y);
  16848. void handleFileDragExit (const StringArray& files);
  16849. void handleFileDragDrop (const StringArray& files, int x, int y);
  16850. /** Resets the masking region.
  16851. The subclass should call this every time it's about to call the handlePaint
  16852. method.
  16853. @see addMaskedRegion
  16854. */
  16855. void clearMaskedRegion() throw();
  16856. /** Adds a rectangle to the set of areas not to paint over.
  16857. A component can call this on its peer during its paint() method, to signal
  16858. that the painting code should ignore a given region. The reason
  16859. for this is to stop embedded windows (such as OpenGL) getting painted over.
  16860. The masked region is cleared each time before a paint happens, so a component
  16861. will have to make sure it calls this every time it's painted.
  16862. */
  16863. void addMaskedRegion (int x, int y, int w, int h) throw();
  16864. /** Returns the number of currently-active peers.
  16865. @see getPeer
  16866. */
  16867. static int getNumPeers() throw();
  16868. /** Returns one of the currently-active peers.
  16869. @see getNumPeers
  16870. */
  16871. static ComponentPeer* getPeer (const int index) throw();
  16872. /** Checks if this peer object is valid.
  16873. @see getNumPeers
  16874. */
  16875. static bool isValidPeer (const ComponentPeer* const peer) throw();
  16876. static void bringModalComponentToFront();
  16877. virtual const StringArray getAvailableRenderingEngines() throw();
  16878. virtual int getCurrentRenderingEngine() throw();
  16879. virtual void setCurrentRenderingEngine (int index) throw();
  16880. juce_UseDebuggingNewOperator
  16881. protected:
  16882. Component* const component;
  16883. const int styleFlags;
  16884. RectangleList maskedRegion;
  16885. Rectangle lastNonFullscreenBounds;
  16886. uint32 lastPaintTime;
  16887. ComponentBoundsConstrainer* constrainer;
  16888. static void updateCurrentModifiers() throw();
  16889. /** @internal */
  16890. void handleMessage (const Message& message);
  16891. private:
  16892. Component* lastFocusedComponent;
  16893. ComponentDeletionWatcher* dragAndDropTargetComponent;
  16894. Component* lastDragAndDropCompUnderMouse;
  16895. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  16896. friend class Component;
  16897. static ComponentPeer* getPeerFor (const Component* const component) throw();
  16898. void setLastDragDropTarget (Component* comp);
  16899. ComponentPeer (const ComponentPeer&);
  16900. const ComponentPeer& operator= (const ComponentPeer&);
  16901. };
  16902. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  16903. /********* End of inlined file: juce_ComponentPeer.h *********/
  16904. class LookAndFeel;
  16905. /**
  16906. The base class for all JUCE user-interface objects.
  16907. */
  16908. class JUCE_API Component : public MouseListener,
  16909. protected MessageListener
  16910. {
  16911. public:
  16912. /** Creates a component.
  16913. To get it to actually appear, you'll also need to:
  16914. - Either add it to a parent component or use the addToDesktop() method to
  16915. make it a desktop window
  16916. - Set its size and position to something sensible
  16917. - Use setVisible() to make it visible
  16918. And for it to serve any useful purpose, you'll need to write a
  16919. subclass of Component or use one of the other types of component from
  16920. the library.
  16921. */
  16922. Component() throw();
  16923. /** Destructor.
  16924. Note that when a component is deleted, any child components it might
  16925. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  16926. */
  16927. virtual ~Component();
  16928. /** Creates a component, setting its name at the same time.
  16929. @see getName, setName
  16930. */
  16931. Component (const String& componentName) throw();
  16932. /** Returns the name of this component.
  16933. @see setName
  16934. */
  16935. const String& getName() const throw() { return componentName_; }
  16936. /** Sets the name of this component.
  16937. When the name changes, all registered ComponentListeners will receive a
  16938. ComponentListener::componentNameChanged() callback.
  16939. @see getName
  16940. */
  16941. virtual void setName (const String& newName);
  16942. /** Checks whether this Component object has been deleted.
  16943. This will check whether this object is still a valid component, or whether
  16944. it's been deleted.
  16945. It's safe to call this on null or dangling pointers, but note that there is a
  16946. small risk if another new (but different) component has been created at the
  16947. same memory address which this one occupied, this methods can return a
  16948. false positive.
  16949. */
  16950. bool isValidComponent() const throw();
  16951. /** Makes the component visible or invisible.
  16952. This method will show or hide the component.
  16953. Note that components default to being non-visible when first created.
  16954. Also note that visible components won't be seen unless all their parent components
  16955. are also visible.
  16956. This method will call visibilityChanged() and also componentVisibilityChanged()
  16957. for any component listeners that are interested in this component.
  16958. @param shouldBeVisible whether to show or hide the component
  16959. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  16960. */
  16961. virtual void setVisible (bool shouldBeVisible);
  16962. /** Tests whether the component is visible or not.
  16963. this doesn't necessarily tell you whether this comp is actually on the screen
  16964. because this depends on whether all the parent components are also visible - use
  16965. isShowing() to find this out.
  16966. @see isShowing, setVisible
  16967. */
  16968. bool isVisible() const throw() { return flags.visibleFlag; }
  16969. /** Called when this component's visiblility changes.
  16970. @see setVisible, isVisible
  16971. */
  16972. virtual void visibilityChanged();
  16973. /** Tests whether this component and all its parents are visible.
  16974. @returns true only if this component and all its parents are visible.
  16975. @see isVisible
  16976. */
  16977. bool isShowing() const throw();
  16978. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  16979. To do this, this function will cunningly:
  16980. - take a snapshot of the component as it currently looks
  16981. - call setVisible(false) on the component
  16982. - replace it with a special component that will continue drawing the
  16983. snapshot, animating it and gradually making it more transparent
  16984. - when it's gone, the special component will also be deleted
  16985. As soon as this method returns, the component can be safely removed and deleted
  16986. leaving the proxy to do the fade-out, so it's even ok to call this in a
  16987. component's destructor.
  16988. Passing non-zero x and y values will cause the ghostly component image to
  16989. also whizz off by this distance while fading out. If the scale factor is
  16990. not 1.0, it will also zoom from the component's current size to this new size.
  16991. One thing to be careful about is that the parent component must be able to cope
  16992. with this unknown component type being added to it.
  16993. */
  16994. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  16995. const int deltaXToMove = 0,
  16996. const int deltaYToMove = 0,
  16997. const float scaleFactorAtEnd = 1.0f);
  16998. /** Makes this component appear as a window on the desktop.
  16999. Note that before calling this, you should make sure that the component's opacity is
  17000. set correctly using setOpaque(). If the component is non-opaque, the windowing
  17001. system will try to create a special transparent window for it, which will generally take
  17002. a lot more CPU to operate (and might not even be possible on some platforms).
  17003. If the component is inside a parent component at the time this method is called, it
  17004. will be first be removed from that parent. Likewise if a component on the desktop
  17005. is subsequently added to another component, it'll be removed from the desktop.
  17006. @param windowStyleFlags a combination of the flags specified in the
  17007. ComponentPeer::StyleFlags enum, which define the
  17008. window's characteristics.
  17009. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  17010. in which the juce component should place itself. On Windows,
  17011. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  17012. supported on all platforms, and best left as 0 unless you know
  17013. what you're doing
  17014. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  17015. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  17016. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  17017. */
  17018. virtual void addToDesktop (int windowStyleFlags,
  17019. void* nativeWindowToAttachTo = 0);
  17020. /** If the component is currently showing on the desktop, this will hide it.
  17021. You can also use setVisible() to hide a desktop window temporarily, but
  17022. removeFromDesktop() will free any system resources that are being used up.
  17023. @see addToDesktop, isOnDesktop
  17024. */
  17025. void removeFromDesktop();
  17026. /** Returns true if this component is currently showing on the desktop.
  17027. @see addToDesktop, removeFromDesktop
  17028. */
  17029. bool isOnDesktop() const throw();
  17030. /** Returns the heavyweight window that contains this component.
  17031. If this component is itself on the desktop, this will return the window
  17032. object that it is using. Otherwise, it will return the window of
  17033. its top-level parent component.
  17034. This may return 0 if there isn't a desktop component.
  17035. @see addToDesktop, isOnDesktop
  17036. */
  17037. ComponentPeer* getPeer() const throw();
  17038. /** For components on the desktop, this is called if the system wants to close the window.
  17039. This is a signal that either the user or the system wants the window to close. The
  17040. default implementation of this method will trigger an assertion to warn you that your
  17041. component should do something about it, but you can override this to ignore the event
  17042. if you want.
  17043. */
  17044. virtual void userTriedToCloseWindow();
  17045. /** Called for a desktop component which has just been minimised or un-minimised.
  17046. This will only be called for components on the desktop.
  17047. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  17048. */
  17049. virtual void minimisationStateChanged (bool isNowMinimised);
  17050. /** Brings the component to the front of its siblings.
  17051. If some of the component's siblings have had their 'always-on-top' flag set,
  17052. then they will still be kept in front of this one (unless of course this
  17053. one is also 'always-on-top').
  17054. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  17055. to the component (see grabKeyboardFocus() for more details)
  17056. @see toBack, toBehind, setAlwaysOnTop
  17057. */
  17058. void toFront (const bool shouldAlsoGainFocus);
  17059. /** Changes this component's z-order to be at the back of all its siblings.
  17060. If the component is set to be 'always-on-top', it will only be moved to the
  17061. back of the other other 'always-on-top' components.
  17062. @see toFront, toBehind, setAlwaysOnTop
  17063. */
  17064. void toBack();
  17065. /** Changes this component's z-order so that it's just behind another component.
  17066. @see toFront, toBack
  17067. */
  17068. void toBehind (Component* const other);
  17069. /** Sets whether the component should always be kept at the front of its siblings.
  17070. @see isAlwaysOnTop
  17071. */
  17072. void setAlwaysOnTop (const bool shouldStayOnTop);
  17073. /** Returns true if this component is set to always stay in front of its siblings.
  17074. @see setAlwaysOnTop
  17075. */
  17076. bool isAlwaysOnTop() const throw();
  17077. /** Returns the x co-ordinate of the component's left edge.
  17078. This is a distance in pixels from the left edge of the component's parent.
  17079. @see getScreenX
  17080. */
  17081. inline int getX() const throw() { return bounds_.getX(); }
  17082. /** Returns the y co-ordinate of the top of this component.
  17083. This is a distance in pixels from the top edge of the component's parent.
  17084. @see getScreenY
  17085. */
  17086. inline int getY() const throw() { return bounds_.getY(); }
  17087. /** Returns the component's width in pixels. */
  17088. inline int getWidth() const throw() { return bounds_.getWidth(); }
  17089. /** Returns the component's height in pixels. */
  17090. inline int getHeight() const throw() { return bounds_.getHeight(); }
  17091. /** Returns the x co-ordinate of the component's right-hand edge.
  17092. This is a distance in pixels from the left edge of the component's parent.
  17093. */
  17094. int getRight() const throw() { return bounds_.getRight(); }
  17095. /** Returns the y co-ordinate of the bottom edge of this component.
  17096. This is a distance in pixels from the top edge of the component's parent.
  17097. */
  17098. int getBottom() const throw() { return bounds_.getBottom(); }
  17099. /** Returns this component's bounding box.
  17100. The rectangle returned is relative to the top-left of the component's parent.
  17101. */
  17102. const Rectangle& getBounds() const throw() { return bounds_; }
  17103. /** Returns the region of this component that's not obscured by other, opaque components.
  17104. The RectangleList that is returned represents the area of this component
  17105. which isn't covered by opaque child components.
  17106. If includeSiblings is true, it will also take into account any siblings
  17107. that may be overlapping the component.
  17108. */
  17109. void getVisibleArea (RectangleList& result,
  17110. const bool includeSiblings) const;
  17111. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  17112. @see getX, relativePositionToGlobal
  17113. */
  17114. int getScreenX() const throw();
  17115. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  17116. @see getY, relativePositionToGlobal
  17117. */
  17118. int getScreenY() const throw();
  17119. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  17120. @see globalPositionToRelative, relativePositionToOtherComponent
  17121. */
  17122. void relativePositionToGlobal (int& x, int& y) const throw();
  17123. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  17124. @see relativePositionToGlobal, relativePositionToOtherComponent
  17125. */
  17126. void globalPositionToRelative (int& x, int& y) const throw();
  17127. /** Converts a position relative to this component's top-left into a position
  17128. relative to another component's top-left.
  17129. @see relativePositionToGlobal, globalPositionToRelative
  17130. */
  17131. void relativePositionToOtherComponent (const Component* const targetComponent,
  17132. int& x, int& y) const throw();
  17133. /** Moves the component to a new position.
  17134. Changes the component's top-left position (without changing its size).
  17135. The position is relative to the top-left of the component's parent.
  17136. If the component actually moves, this method will make a synchronous call to moved().
  17137. @see setBounds, ComponentListener::componentMovedOrResized
  17138. */
  17139. void setTopLeftPosition (const int x, const int y);
  17140. /** Moves the component to a new position.
  17141. Changes the position of the component's top-right corner (keeping it the same size).
  17142. The position is relative to the top-left of the component's parent.
  17143. If the component actually moves, this method will make a synchronous call to moved().
  17144. */
  17145. void setTopRightPosition (const int x, const int y);
  17146. /** Changes the size of the component.
  17147. A synchronous call to resized() will be occur if the size actually changes.
  17148. */
  17149. void setSize (const int newWidth, const int newHeight);
  17150. /** Changes the component's position and size.
  17151. The co-ordinates are relative to the top-left of the component's parent, or relative
  17152. to the origin of the screen is the component is on the desktop.
  17153. If this method changes the component's top-left position, it will make a synchronous
  17154. call to moved(). If it changes the size, it will also make a call to resized().
  17155. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  17156. */
  17157. void setBounds (int x, int y, int width, int height);
  17158. /** Changes the component's position and size.
  17159. @see setBounds
  17160. */
  17161. void setBounds (const Rectangle& newBounds);
  17162. /** Changes the component's position and size in terms of fractions of its parent's size.
  17163. The values are factors of the parent's size, so for example
  17164. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  17165. width and height of the parent, with its top-left position 20% of
  17166. the way across and down the parent.
  17167. */
  17168. void setBoundsRelative (const float proportionalX, const float proportionalY,
  17169. const float proportionalWidth, const float proportionalHeight);
  17170. /** Changes the component's position and size based on the amount of space to leave around it.
  17171. This will position the component within its parent, leaving the specified number of
  17172. pixels around each edge.
  17173. */
  17174. void setBoundsInset (const BorderSize& borders);
  17175. /** Positions the component within a given rectangle, keeping its proportions
  17176. unchanged.
  17177. If onlyReduceInSize is false, the component will be resized to fill as much of the
  17178. rectangle as possible without changing its aspect ratio (the component's
  17179. current size is used to determine its aspect ratio, so a zero-size component
  17180. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  17181. too big to fit inside the rectangle.
  17182. It will then be positioned within the rectangle according to the justification flags
  17183. specified.
  17184. */
  17185. void setBoundsToFit (int x, int y, int width, int height,
  17186. const Justification& justification,
  17187. const bool onlyReduceInSize);
  17188. /** Changes the position of the component's centre.
  17189. Leaves the component's size unchanged, but sets the position of its centre
  17190. relative to its parent's top-left.
  17191. */
  17192. void setCentrePosition (const int x, const int y);
  17193. /** Changes the position of the component's centre.
  17194. Leaves the position unchanged, but positions its centre relative to its
  17195. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  17196. its parent.
  17197. */
  17198. void setCentreRelative (const float x, const float y);
  17199. /** Changes the component's size and centres it within its parent.
  17200. After changing the size, the component will be moved so that it's
  17201. centred within its parent.
  17202. */
  17203. void centreWithSize (const int width, const int height);
  17204. /** Returns a proportion of the component's width.
  17205. This is a handy equivalent of (getWidth() * proportion).
  17206. */
  17207. int proportionOfWidth (const float proportion) const throw();
  17208. /** Returns a proportion of the component's height.
  17209. This is a handy equivalent of (getHeight() * proportion).
  17210. */
  17211. int proportionOfHeight (const float proportion) const throw();
  17212. /** Returns the width of the component's parent.
  17213. If the component has no parent (i.e. if it's on the desktop), this will return
  17214. the width of the screen.
  17215. */
  17216. int getParentWidth() const throw();
  17217. /** Returns the height of the component's parent.
  17218. If the component has no parent (i.e. if it's on the desktop), this will return
  17219. the height of the screen.
  17220. */
  17221. int getParentHeight() const throw();
  17222. /** Returns the screen co-ordinates of the monitor that contains this component.
  17223. If there's only one monitor, this will return its size - if there are multiple
  17224. monitors, it will return the area of the monitor that contains the component's
  17225. centre.
  17226. */
  17227. const Rectangle getParentMonitorArea() const throw();
  17228. /** Returns the number of child components that this component contains.
  17229. @see getChildComponent, getIndexOfChildComponent
  17230. */
  17231. int getNumChildComponents() const throw();
  17232. /** Returns one of this component's child components, by it index.
  17233. The component with index 0 is at the back of the z-order, the one at the
  17234. front will have index (getNumChildComponents() - 1).
  17235. If the index is out-of-range, this will return a null pointer.
  17236. @see getNumChildComponents, getIndexOfChildComponent
  17237. */
  17238. Component* getChildComponent (const int index) const throw();
  17239. /** Returns the index of this component in the list of child components.
  17240. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  17241. values are further towards the front.
  17242. Returns -1 if the component passed-in is not a child of this component.
  17243. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  17244. */
  17245. int getIndexOfChildComponent (const Component* const child) const throw();
  17246. /** Adds a child component to this one.
  17247. @param child the new component to add. If the component passed-in is already
  17248. the child of another component, it'll first be removed from that.
  17249. @param zOrder The index in the child-list at which this component should be inserted.
  17250. A value of -1 will insert it in front of the others, 0 is the back.
  17251. @see removeChildComponent, addAndMakeVisible, getChild,
  17252. ComponentListener::componentChildrenChanged
  17253. */
  17254. void addChildComponent (Component* const child,
  17255. int zOrder = -1);
  17256. /** Adds a child component to this one, and also makes the child visible if it isn't.
  17257. Quite a useful function, this is just the same as calling addChildComponent()
  17258. followed by setVisible (true) on the child.
  17259. */
  17260. void addAndMakeVisible (Component* const child,
  17261. int zOrder = -1);
  17262. /** Removes one of this component's child-components.
  17263. If the child passed-in isn't actually a child of this component (either because
  17264. it's invalid or is the child of a different parent), then nothing is done.
  17265. Note that removing a child will not delete it!
  17266. @see addChildComponent, ComponentListener::componentChildrenChanged
  17267. */
  17268. void removeChildComponent (Component* const childToRemove);
  17269. /** Removes one of this component's child-components by index.
  17270. This will return a pointer to the component that was removed, or null if
  17271. the index was out-of-range.
  17272. Note that removing a child will not delete it!
  17273. @see addChildComponent, ComponentListener::componentChildrenChanged
  17274. */
  17275. Component* removeChildComponent (const int childIndexToRemove);
  17276. /** Removes all this component's children.
  17277. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  17278. */
  17279. void removeAllChildren();
  17280. /** Removes all this component's children, and deletes them.
  17281. @see removeAllChildren
  17282. */
  17283. void deleteAllChildren();
  17284. /** Returns the component which this component is inside.
  17285. If this is the highest-level component or hasn't yet been added to
  17286. a parent, this will return null.
  17287. */
  17288. Component* getParentComponent() const throw() { return parentComponent_; }
  17289. /** Searches the parent components for a component of a specified class.
  17290. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  17291. component that can be dynamically cast to a MyComp, or will return 0 if none
  17292. of the parents are suitable.
  17293. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  17294. */
  17295. template <class TargetClass>
  17296. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  17297. {
  17298. (void) dummyParameter;
  17299. Component* p = parentComponent_;
  17300. while (p != 0)
  17301. {
  17302. TargetClass* target = dynamic_cast <TargetClass*> (p);
  17303. if (target != 0)
  17304. return target;
  17305. p = p->parentComponent_;
  17306. }
  17307. return 0;
  17308. }
  17309. /** Returns the highest-level component which contains this one or its parents.
  17310. This will search upwards in the parent-hierarchy from this component, until it
  17311. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  17312. not yet added to a parent), and will return that.
  17313. */
  17314. Component* getTopLevelComponent() const throw();
  17315. /** Checks whether a component is anywhere inside this component or its children.
  17316. This will recursively check through this components children to see if the
  17317. given component is anywhere inside.
  17318. */
  17319. bool isParentOf (const Component* possibleChild) const throw();
  17320. /** Called to indicate that the component's parents have changed.
  17321. When a component is added or removed from its parent, this method will
  17322. be called on all of its children (recursively - so all children of its
  17323. children will also be called as well).
  17324. Subclasses can override this if they need to react to this in some way.
  17325. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  17326. */
  17327. virtual void parentHierarchyChanged();
  17328. /** Subclasses can use this callback to be told when children are added or removed.
  17329. @see parentHierarchyChanged
  17330. */
  17331. virtual void childrenChanged();
  17332. /** Tests whether a given point inside the component.
  17333. Overriding this method allows you to create components which only intercept
  17334. mouse-clicks within a user-defined area.
  17335. This is called to find out whether a particular x, y co-ordinate is
  17336. considered to be inside the component or not, and is used by methods such
  17337. as contains() and getComponentAt() to work out which component
  17338. the mouse is clicked on.
  17339. Components with custom shapes will probably want to override it to perform
  17340. some more complex hit-testing.
  17341. The default implementation of this method returns either true or false,
  17342. depending on the value that was set by calling setInterceptsMouseClicks() (true
  17343. is the default return value).
  17344. Note that the hit-test region is not related to the opacity with which
  17345. areas of a component are painted.
  17346. Applications should never call hitTest() directly - instead use the
  17347. contains() method, because this will also test for occlusion by the
  17348. component's parent.
  17349. Note that for components on the desktop, this method will be ignored, because it's
  17350. not always possible to implement this behaviour on all platforms.
  17351. @param x the x co-ordinate to test, relative to the left hand edge of this
  17352. component. This value is guaranteed to be greater than or equal to
  17353. zero, and less than the component's width
  17354. @param y the y co-ordinate to test, relative to the top edge of this
  17355. component. This value is guaranteed to be greater than or equal to
  17356. zero, and less than the component's height
  17357. @returns true if the click is considered to be inside the component
  17358. @see setInterceptsMouseClicks, contains
  17359. */
  17360. virtual bool hitTest (int x, int y);
  17361. /** Changes the default return value for the hitTest() method.
  17362. Setting this to false is an easy way to make a component pass its mouse-clicks
  17363. through to the components behind it.
  17364. When a component is created, the default setting for this is true.
  17365. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  17366. return false (or true for child components if allowClicksOnChildComponents
  17367. is true)
  17368. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  17369. components can be clicked on as normal but clicks on this component pass
  17370. straight through; if this is false and allowClicksOnThisComponent
  17371. is false, then neither this component nor any child components can
  17372. be clicked on
  17373. @see hitTest, getInterceptsMouseClicks
  17374. */
  17375. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  17376. const bool allowClicksOnChildComponents) throw();
  17377. /** Retrieves the current state of the mouse-click interception flags.
  17378. On return, the two parameters are set to the state used in the last call to
  17379. setInterceptsMouseClicks().
  17380. @see setInterceptsMouseClicks
  17381. */
  17382. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  17383. bool& allowsClicksOnChildComponents) const throw();
  17384. /** Returns true if a given point lies within this component or one of its children.
  17385. Never override this method! Use hitTest to create custom hit regions.
  17386. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17387. @param y the y co-ordinate to test, relative to this component's top edge.
  17388. @returns true if the point is within the component's hit-test area, but only if
  17389. that part of the component isn't clipped by its parent component. Note
  17390. that this won't take into account any overlapping sibling components
  17391. which might be in the way - for that, see reallyContains()
  17392. @see hitTest, reallyContains, getComponentAt
  17393. */
  17394. virtual bool contains (int x, int y);
  17395. /** Returns true if a given point lies in this component, taking any overlapping
  17396. siblings into account.
  17397. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17398. @param y the y co-ordinate to test, relative to this component's top edge.
  17399. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  17400. component, this determines the value that will
  17401. be returned.
  17402. @see contains, getComponentAt
  17403. */
  17404. bool reallyContains (int x, int y,
  17405. const bool returnTrueIfWithinAChild);
  17406. /** Returns the component at a certain point within this one.
  17407. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17408. @param y the y co-ordinate to test, relative to this component's top edge.
  17409. @returns the component that is at this position - which may be 0, this component,
  17410. or one of its children. Note that overlapping siblings that might actually
  17411. be in the way are not taken into account by this method - to account for these,
  17412. instead call getComponentAt on the top-level parent of this component.
  17413. @see hitTest, contains, reallyContains
  17414. */
  17415. Component* getComponentAt (const int x, const int y);
  17416. /** Marks the whole component as needing to be redrawn.
  17417. Calling this will not do any repainting immediately, but will mark the component
  17418. as 'dirty'. At some point in the near future the operating system will send a paint
  17419. message, which will redraw all the dirty regions of all components.
  17420. There's no guarantee about how soon after calling repaint() the redraw will actually
  17421. happen, and other queued events may be delivered before a redraw is done.
  17422. If the setBufferedToImage() method has been used to cause this component
  17423. to use a buffer, the repaint() call will invalidate the component's buffer.
  17424. To redraw just a subsection of the component rather than the whole thing,
  17425. use the repaint (int, int, int, int) method.
  17426. @see paint
  17427. */
  17428. void repaint() throw();
  17429. /** Marks a subsection of this component as needing to be redrawn.
  17430. Calling this will not do any repainting immediately, but will mark the given region
  17431. of the component as 'dirty'. At some point in the near future the operating system
  17432. will send a paint message, which will redraw all the dirty regions of all components.
  17433. There's no guarantee about how soon after calling repaint() the redraw will actually
  17434. happen, and other queued events may be delivered before a redraw is done.
  17435. The region that is passed in will be clipped to keep it within the bounds of this
  17436. component.
  17437. @see repaint()
  17438. */
  17439. void repaint (const int x, const int y,
  17440. const int width, const int height) throw();
  17441. /** Makes the component use an internal buffer to optimise its redrawing.
  17442. Setting this flag to true will cause the component to allocate an
  17443. internal buffer into which it paints itself, so that when asked to
  17444. redraw itself, it can use this buffer rather than actually calling the
  17445. paint() method.
  17446. The buffer is kept until the repaint() method is called directly on
  17447. this component (or until it is resized), when the image is invalidated
  17448. and then redrawn the next time the component is painted.
  17449. Note that only the drawing that happens within the component's paint()
  17450. method is drawn into the buffer, it's child components are not buffered, and
  17451. nor is the paintOverChildren() method.
  17452. @see repaint, paint, createComponentSnapshot
  17453. */
  17454. void setBufferedToImage (const bool shouldBeBuffered) throw();
  17455. /** Generates a snapshot of part of this component.
  17456. This will return a new Image, the size of the rectangle specified,
  17457. containing a snapshot of the specified area of the component and all
  17458. its children.
  17459. The image may or may not have an alpha-channel, depending on whether the
  17460. image is opaque or not.
  17461. If the clipImageToComponentBounds parameter is true and the area is greater than
  17462. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  17463. then parts of the component beyond its bounds can be drawn.
  17464. The caller is responsible for deleting the image that is returned.
  17465. @see paintEntireComponent
  17466. */
  17467. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  17468. const bool clipImageToComponentBounds = true);
  17469. /** Draws this component and all its subcomponents onto the specified graphics
  17470. context.
  17471. You should very rarely have to use this method, it's simply there in case you need
  17472. to draw a component with a custom graphics context for some reason, e.g. for
  17473. creating a snapshot of the component.
  17474. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  17475. on its children in order to render the entire tree.
  17476. The graphics context may be left in an undefined state after this method returns,
  17477. so you may need to reset it if you're going to use it again.
  17478. */
  17479. void paintEntireComponent (Graphics& context);
  17480. /** Adds an effect filter to alter the component's appearance.
  17481. When a component has an effect filter set, then this is applied to the
  17482. results of its paint() method. There are a few preset effects, such as
  17483. a drop-shadow or glow, but they can be user-defined as well.
  17484. The effect that is passed in will not be deleted by the component - the
  17485. caller must take care of deleting it.
  17486. To remove an effect from a component, pass a null pointer in as the parameter.
  17487. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  17488. */
  17489. void setComponentEffect (ImageEffectFilter* const newEffect);
  17490. /** Returns the current component effect.
  17491. @see setComponentEffect
  17492. */
  17493. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  17494. /** Finds the appropriate look-and-feel to use for this component.
  17495. If the component hasn't had a look-and-feel explicitly set, this will
  17496. return the parent's look-and-feel, or just the default one if there's no
  17497. parent.
  17498. @see setLookAndFeel, lookAndFeelChanged
  17499. */
  17500. LookAndFeel& getLookAndFeel() const throw();
  17501. /** Sets the look and feel to use for this component.
  17502. This will also change the look and feel for any child components that haven't
  17503. had their look set explicitly.
  17504. The object passed in will not be deleted by the component, so it's the caller's
  17505. responsibility to manage it. It may be used at any time until this component
  17506. has been deleted.
  17507. Calling this method will also invoke the sendLookAndFeelChange() method.
  17508. @see getLookAndFeel, lookAndFeelChanged
  17509. */
  17510. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  17511. /** Called to let the component react to a change in the look-and-feel setting.
  17512. When the look-and-feel is changed for a component, this will be called in
  17513. all its child components, recursively.
  17514. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  17515. an application uses a LookAndFeel class that might have changed internally.
  17516. @see sendLookAndFeelChange, getLookAndFeel
  17517. */
  17518. virtual void lookAndFeelChanged();
  17519. /** Calls the lookAndFeelChanged() method in this component and all its children.
  17520. This will recurse through the children and their children, calling lookAndFeelChanged()
  17521. on them all.
  17522. @see lookAndFeelChanged
  17523. */
  17524. void sendLookAndFeelChange();
  17525. /** Indicates whether any parts of the component might be transparent.
  17526. Components that always paint all of their contents with solid colour and
  17527. thus completely cover any components behind them should use this method
  17528. to tell the repaint system that they are opaque.
  17529. This information is used to optimise drawing, because it means that
  17530. objects underneath opaque windows don't need to be painted.
  17531. By default, components are considered transparent, unless this is used to
  17532. make it otherwise.
  17533. @see isOpaque, getVisibleArea
  17534. */
  17535. void setOpaque (const bool shouldBeOpaque) throw();
  17536. /** Returns true if no parts of this component are transparent.
  17537. @returns the value that was set by setOpaque, (the default being false)
  17538. @see setOpaque
  17539. */
  17540. bool isOpaque() const throw();
  17541. /** Indicates whether the component should be brought to the front when clicked.
  17542. Setting this flag to true will cause the component to be brought to the front
  17543. when the mouse is clicked somewhere inside it or its child components.
  17544. Note that a top-level desktop window might still be brought to the front by the
  17545. operating system when it's clicked, depending on how the OS works.
  17546. By default this is set to false.
  17547. @see setMouseClickGrabsKeyboardFocus
  17548. */
  17549. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  17550. /** Indicates whether the component should be brought to the front when clicked-on.
  17551. @see setBroughtToFrontOnMouseClick
  17552. */
  17553. bool isBroughtToFrontOnMouseClick() const throw();
  17554. // Keyboard focus methods
  17555. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  17556. By default components aren't actually interested in gaining the
  17557. focus, but this method can be used to turn this on.
  17558. See the grabKeyboardFocus() method for details about the way a component
  17559. is chosen to receive the focus.
  17560. @see grabKeyboardFocus, getWantsKeyboardFocus
  17561. */
  17562. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  17563. /** Returns true if the component is interested in getting keyboard focus.
  17564. This returns the flag set by setWantsKeyboardFocus(). The default
  17565. setting is false.
  17566. @see setWantsKeyboardFocus
  17567. */
  17568. bool getWantsKeyboardFocus() const throw();
  17569. /** Chooses whether a click on this component automatically grabs the focus.
  17570. By default this is set to true, but you might want a component which can
  17571. be focused, but where you don't want the user to be able to affect it directly
  17572. by clicking.
  17573. */
  17574. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  17575. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  17576. See setMouseClickGrabsKeyboardFocus() for more info.
  17577. */
  17578. bool getMouseClickGrabsKeyboardFocus() const throw();
  17579. /** Tries to give keyboard focus to this component.
  17580. When the user clicks on a component or its grabKeyboardFocus()
  17581. method is called, the following procedure is used to work out which
  17582. component should get it:
  17583. - if the component that was clicked on actually wants focus (as indicated
  17584. by calling getWantsKeyboardFocus), it gets it.
  17585. - if the component itself doesn't want focus, it will try to pass it
  17586. on to whichever of its children is the default component, as determined by
  17587. KeyboardFocusTraverser::getDefaultComponent()
  17588. - if none of its children want focus at all, it will pass it up to its
  17589. parent instead, unless it's a top-level component without a parent,
  17590. in which case it just takes the focus itself.
  17591. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  17592. getCurrentlyFocusedComponent, focusGained, focusLost,
  17593. keyPressed, keyStateChanged
  17594. */
  17595. void grabKeyboardFocus();
  17596. /** Returns true if this component currently has the keyboard focus.
  17597. @param trueIfChildIsFocused if this is true, then the method returns true if
  17598. either this component or any of its children (recursively)
  17599. have the focus. If false, the method only returns true if
  17600. this component has the focus.
  17601. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  17602. focusGained, focusLost
  17603. */
  17604. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  17605. /** Returns the component that currently has the keyboard focus.
  17606. @returns the focused component, or null if nothing is focused.
  17607. */
  17608. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  17609. /** Tries to move the keyboard focus to one of this component's siblings.
  17610. This will try to move focus to either the next or previous component. (This
  17611. is the method that is used when shifting focus by pressing the tab key).
  17612. Components for which getWantsKeyboardFocus() returns false are not looked at.
  17613. @param moveToNext if true, the focus will move forwards; if false, it will
  17614. move backwards
  17615. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  17616. */
  17617. void moveKeyboardFocusToSibling (const bool moveToNext);
  17618. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  17619. which focus should be passed from this component.
  17620. The default implementation of this method will return a default
  17621. KeyboardFocusTraverser if this component is a focus container (as determined
  17622. by the setFocusContainer() method). If the component isn't a focus
  17623. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  17624. If you overrride this to return a custom KeyboardFocusTraverser, then
  17625. this component and all its sub-components will use the new object to
  17626. make their focusing decisions.
  17627. The method should return a new object, which the caller is required to
  17628. delete when no longer needed.
  17629. */
  17630. virtual KeyboardFocusTraverser* createFocusTraverser();
  17631. /** Returns the focus order of this component, if one has been specified.
  17632. By default components don't have a focus order - in that case, this
  17633. will return 0. Lower numbers indicate that the component will be
  17634. earlier in the focus traversal order.
  17635. To change the order, call setExplicitFocusOrder().
  17636. The focus order may be used by the KeyboardFocusTraverser class as part of
  17637. its algorithm for deciding the order in which components should be traversed.
  17638. See the KeyboardFocusTraverser class for more details on this.
  17639. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  17640. */
  17641. int getExplicitFocusOrder() const throw();
  17642. /** Sets the index used in determining the order in which focusable components
  17643. should be traversed.
  17644. A value of 0 or less is taken to mean that no explicit order is wanted, and
  17645. that traversal should use other factors, like the component's position.
  17646. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  17647. */
  17648. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  17649. /** Indicates whether this component is a parent for components that can have
  17650. their focus traversed.
  17651. This flag is used by the default implementation of the createFocusTraverser()
  17652. method, which uses the flag to find the first parent component (of the currently
  17653. focused one) which wants to be a focus container.
  17654. So using this method to set the flag to 'true' causes this component to
  17655. act as the top level within which focus is passed around.
  17656. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  17657. */
  17658. void setFocusContainer (const bool shouldBeFocusContainer) throw();
  17659. /** Returns true if this component has been marked as a focus container.
  17660. See setFocusContainer() for more details.
  17661. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  17662. */
  17663. bool isFocusContainer() const throw();
  17664. /** Returns true if the component (and all its parents) are enabled.
  17665. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  17666. what difference this makes to the component depends on the type. E.g. buttons
  17667. and sliders will choose to draw themselves differently, etc.
  17668. Note that if one of this component's parents is disabled, this will always
  17669. return false, even if this component itself is enabled.
  17670. @see setEnabled, enablementChanged
  17671. */
  17672. bool isEnabled() const throw();
  17673. /** Enables or disables this component.
  17674. Disabling a component will also cause all of its child components to become
  17675. disabled.
  17676. Similarly, enabling a component which is inside a disabled parent
  17677. component won't make any difference until the parent is re-enabled.
  17678. @see isEnabled, enablementChanged
  17679. */
  17680. void setEnabled (const bool shouldBeEnabled);
  17681. /** Callback to indicate that this component has been enabled or disabled.
  17682. This can be triggered by one of the component's parent components
  17683. being enabled or disabled, as well as changes to the component itself.
  17684. The default implementation of this method does nothing; your class may
  17685. wish to repaint itself or something when this happens.
  17686. @see setEnabled, isEnabled
  17687. */
  17688. virtual void enablementChanged();
  17689. /** Changes the mouse cursor shape to use when the mouse is over this component.
  17690. Note that the cursor set by this method can be overridden by the getMouseCursor
  17691. method.
  17692. @see MouseCursor
  17693. */
  17694. void setMouseCursor (const MouseCursor& cursorType) throw();
  17695. /** Returns the mouse cursor shape to use when the mouse is over this component.
  17696. The default implementation will return the cursor that was set by setCursor()
  17697. but can be overridden for more specialised purposes, e.g. returning different
  17698. cursors depending on the mouse position.
  17699. @see MouseCursor
  17700. */
  17701. virtual const MouseCursor getMouseCursor();
  17702. /** Forces the current mouse cursor to be updated.
  17703. If you're overriding the getMouseCursor() method to control which cursor is
  17704. displayed, then this will only be checked each time the user moves the mouse. So
  17705. if you want to force the system to check that the cursor being displayed is
  17706. up-to-date (even if the mouse is just sitting there), call this method.
  17707. This isn't needed if you're only using setMouseCursor().
  17708. */
  17709. void updateMouseCursor() const throw();
  17710. /** Components can override this method to draw their content.
  17711. The paint() method gets called when a region of a component needs redrawing,
  17712. either because the component's repaint() method has been called, or because
  17713. something has happened on the screen that means a section of a window needs
  17714. to be redrawn.
  17715. Any child components will draw themselves over whatever this method draws. If
  17716. you need to paint over the top of your child components, you can also implement
  17717. the paintOverChildren() method to do this.
  17718. If you want to cause a component to redraw itself, this is done asynchronously -
  17719. calling the repaint() method marks a region of the component as "dirty", and the
  17720. paint() method will automatically be called sometime later, by the message thread,
  17721. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  17722. you never redraw something synchronously.
  17723. You should never need to call this method directly - to take a snapshot of the
  17724. component you could use createComponentSnapshot() or paintEntireComponent().
  17725. @param g the graphics context that must be used to do the drawing operations.
  17726. @see repaint, paintOverChildren, Graphics
  17727. */
  17728. virtual void paint (Graphics& g);
  17729. /** Components can override this method to draw over the top of their children.
  17730. For most drawing operations, it's better to use the normal paint() method,
  17731. but if you need to overlay something on top of the children, this can be
  17732. used.
  17733. @see paint, Graphics
  17734. */
  17735. virtual void paintOverChildren (Graphics& g);
  17736. /** Called when the mouse moves inside this component.
  17737. If the mouse button isn't pressed and the mouse moves over a component,
  17738. this will be called to let the component react to this.
  17739. A component will always get a mouseEnter callback before a mouseMove.
  17740. @param e details about the position and status of the mouse event
  17741. @see mouseEnter, mouseExit, mouseDrag, contains
  17742. */
  17743. virtual void mouseMove (const MouseEvent& e);
  17744. /** Called when the mouse first enters this component.
  17745. If the mouse button isn't pressed and the mouse moves into a component,
  17746. this will be called to let the component react to this.
  17747. When the mouse button is pressed and held down while being moved in
  17748. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17749. mouseDrag messages are sent to the component that the mouse was originally
  17750. clicked on, until the button is released.
  17751. If you're writing a component that needs to repaint itself when the mouse
  17752. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  17753. method.
  17754. @param e details about the position and status of the mouse event
  17755. @see mouseExit, mouseDrag, mouseMove, contains
  17756. */
  17757. virtual void mouseEnter (const MouseEvent& e);
  17758. /** Called when the mouse moves out of this component.
  17759. This will be called when the mouse moves off the edge of this
  17760. component.
  17761. If the mouse button was pressed, and it was then dragged off the
  17762. edge of the component and released, then this callback will happen
  17763. when the button is released, after the mouseUp callback.
  17764. If you're writing a component that needs to repaint itself when the mouse
  17765. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  17766. method.
  17767. @param e details about the position and status of the mouse event
  17768. @see mouseEnter, mouseDrag, mouseMove, contains
  17769. */
  17770. virtual void mouseExit (const MouseEvent& e);
  17771. /** Called when a mouse button is pressed while it's over this component.
  17772. The MouseEvent object passed in contains lots of methods for finding out
  17773. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17774. were held down at the time.
  17775. Once a button is held down, the mouseDrag method will be called when the
  17776. mouse moves, until the button is released.
  17777. @param e details about the position and status of the mouse event
  17778. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  17779. */
  17780. virtual void mouseDown (const MouseEvent& e);
  17781. /** Called when the mouse is moved while a button is held down.
  17782. When a mouse button is pressed inside a component, that component
  17783. receives mouseDrag callbacks each time the mouse moves, even if the
  17784. mouse strays outside the component's bounds.
  17785. If you want to be able to drag things off the edge of a component
  17786. and have the component scroll when you get to the edges, the
  17787. beginDragAutoRepeat() method might be useful.
  17788. @param e details about the position and status of the mouse event
  17789. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  17790. */
  17791. virtual void mouseDrag (const MouseEvent& e);
  17792. /** Called when a mouse button is released.
  17793. A mouseUp callback is sent to the component in which a button was pressed
  17794. even if the mouse is actually over a different component when the
  17795. button is released.
  17796. The MouseEvent object passed in contains lots of methods for finding out
  17797. which buttons were down just before they were released.
  17798. @param e details about the position and status of the mouse event
  17799. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  17800. */
  17801. virtual void mouseUp (const MouseEvent& e);
  17802. /** Called when a mouse button has been double-clicked in this component.
  17803. The MouseEvent object passed in contains lots of methods for finding out
  17804. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17805. were held down at the time.
  17806. For altering the time limit used to detect double-clicks,
  17807. see MouseEvent::setDoubleClickTimeout.
  17808. @param e details about the position and status of the mouse event
  17809. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  17810. MouseEvent::getDoubleClickTimeout
  17811. */
  17812. virtual void mouseDoubleClick (const MouseEvent& e);
  17813. /** Called when the mouse-wheel is moved.
  17814. This callback is sent to the component that the mouse is over when the
  17815. wheel is moved.
  17816. If not overridden, the component will forward this message to its parent, so
  17817. that parent components can collect mouse-wheel messages that happen to
  17818. child components which aren't interested in them.
  17819. @param e details about the position and status of the mouse event
  17820. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  17821. value means the wheel has been pushed to the right, negative means it
  17822. was pushed to the left
  17823. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  17824. value means the wheel has been pushed upwards, negative means it
  17825. was pushed downwards
  17826. */
  17827. virtual void mouseWheelMove (const MouseEvent& e,
  17828. float wheelIncrementX,
  17829. float wheelIncrementY);
  17830. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  17831. next mouse-drag operation.
  17832. This allows you to make sure that mouseDrag() events sent continuously, even
  17833. when the mouse isn't moving. This can be useful for things like auto-scrolling
  17834. components when the mouse is near an edge.
  17835. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  17836. minimum interval between consecutive mouse drag callbacks. The callbacks
  17837. will continue until the mouse is released, and then the interval will be reset,
  17838. so you need to make sure it's called every time you begin a drag event. If it
  17839. is called when the mouse isn't actually being pressed, it will apply to the next
  17840. mouse-drag operation that happens.
  17841. Passing an interval of 0 or less will cancel the auto-repeat.
  17842. @see mouseDrag
  17843. */
  17844. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  17845. /** Causes automatic repaints when the mouse enters or exits this component.
  17846. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  17847. on the component, it will trigger a repaint.
  17848. This is handy for things like buttons that need to draw themselves differently when
  17849. the mouse moves over them, and it avoids having to override all the different mouse
  17850. callbacks and call repaint().
  17851. @see mouseEnter, mouseExit, mouseDown, mouseUp
  17852. */
  17853. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  17854. /** Registers a listener to be told when mouse events occur in this component.
  17855. If you need to get informed about mouse events in a component but can't or
  17856. don't want to override its methods, you can attach any number of listeners
  17857. to the component, and these will get told about the events in addition to
  17858. the component's own callbacks being called.
  17859. Note that a MouseListener can also be attached to more than one component.
  17860. @param newListener the listener to register
  17861. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  17862. for events that happen to any child component
  17863. within this component, including deeply-nested
  17864. child components. If false, it will only be
  17865. told about events that this component handles.
  17866. @see MouseListener, removeMouseListener
  17867. */
  17868. void addMouseListener (MouseListener* const newListener,
  17869. const bool wantsEventsForAllNestedChildComponents) throw();
  17870. /** Deregisters a mouse listener.
  17871. @see addMouseListener, MouseListener
  17872. */
  17873. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  17874. /** Adds a listener that wants to hear about keypresses that this component receives.
  17875. The listeners that are registered with a component are called by its keyPressed() or
  17876. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  17877. If you add an object as a key listener, be careful to remove it when the object
  17878. is deleted, or the component will be left with a dangling pointer.
  17879. @see keyPressed, keyStateChanged, removeKeyListener
  17880. */
  17881. void addKeyListener (KeyListener* const newListener) throw();
  17882. /** Removes a previously-registered key listener.
  17883. @see addKeyListener
  17884. */
  17885. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  17886. /** Called when a key is pressed.
  17887. When a key is pressed, the component that has the keyboard focus will have this
  17888. method called. Remember that a component will only be given the focus if its
  17889. setWantsKeyboardFocus() method has been used to enable this.
  17890. If your implementation returns true, the event will be consumed and not passed
  17891. on to any other listeners. If it returns false, the key will be passed to any
  17892. KeyListeners that have been registered with this component. As soon as one of these
  17893. returns true, the process will stop, but if they all return false, the event will
  17894. be passed upwards to this component's parent, and so on.
  17895. The default implementation of this method does nothing and returns false.
  17896. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  17897. */
  17898. virtual bool keyPressed (const KeyPress& key);
  17899. /** Called when a key is pressed or released.
  17900. Whenever a key on the keyboard is pressed or released (including modifier keys
  17901. like shift and ctrl), this method will be called on the component that currently
  17902. has the keyboard focus. Remember that a component will only be given the focus if
  17903. its setWantsKeyboardFocus() method has been used to enable this.
  17904. If your implementation returns true, the event will be consumed and not passed
  17905. on to any other listeners. If it returns false, then any KeyListeners that have
  17906. been registered with this component will have their keyStateChanged methods called.
  17907. As soon as one of these returns true, the process will stop, but if they all return
  17908. false, the event will be passed upwards to this component's parent, and so on.
  17909. The default implementation of this method does nothing and returns false.
  17910. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  17911. method.
  17912. @param isKeyDown true if a key has been pressed; false if it has been released
  17913. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  17914. */
  17915. virtual bool keyStateChanged (const bool isKeyDown);
  17916. /** Called when a modifier key is pressed or released.
  17917. Whenever the shift, control, alt or command keys are pressed or released,
  17918. this method will be called on the component that currently has the keyboard focus.
  17919. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  17920. method has been used to enable this.
  17921. The default implementation of this method actually calls its parent's modifierKeysChanged
  17922. method, so that focused components which aren't interested in this will give their
  17923. parents a chance to act on the event instead.
  17924. @see keyStateChanged, ModifierKeys
  17925. */
  17926. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  17927. /** Enumeration used by the focusChanged() and focusLost() methods. */
  17928. enum FocusChangeType
  17929. {
  17930. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  17931. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  17932. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  17933. };
  17934. /** Called to indicate that this component has just acquired the keyboard focus.
  17935. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  17936. */
  17937. virtual void focusGained (FocusChangeType cause);
  17938. /** Called to indicate that this component has just lost the keyboard focus.
  17939. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  17940. */
  17941. virtual void focusLost (FocusChangeType cause);
  17942. /** Called to indicate that one of this component's children has been focused or unfocused.
  17943. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  17944. changed. It happens when focus moves from one of this component's children (at any depth)
  17945. to a component that isn't contained in this one, (or vice-versa).
  17946. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  17947. */
  17948. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  17949. /** Returns true if the mouse is currently over this component.
  17950. If the mouse isn't over the component, this will return false, even if the
  17951. mouse is currently being dragged - so you can use this in your mouseDrag
  17952. method to find out whether it's really over the component or not.
  17953. Note that when the mouse button is being held down, then the only component
  17954. for which this method will return true is the one that was originally
  17955. clicked on.
  17956. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  17957. */
  17958. bool isMouseOver() const throw();
  17959. /** Returns true if the mouse button is currently held down in this component.
  17960. Note that this is a test to see whether the mouse is being pressed in this
  17961. component, so it'll return false if called on component A when the mouse
  17962. is actually being dragged in component B.
  17963. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  17964. */
  17965. bool isMouseButtonDown() const throw();
  17966. /** True if the mouse is over this component, or if it's being dragged in this component.
  17967. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  17968. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  17969. */
  17970. bool isMouseOverOrDragging() const throw();
  17971. /** Returns true if a mouse button is currently down.
  17972. Unlike isMouseButtonDown, this will test the current state of the
  17973. buttons without regard to which component (if any) it has been
  17974. pressed in.
  17975. @see isMouseButtonDown, ModifierKeys
  17976. */
  17977. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  17978. /** Returns the mouse's current position, relative to this component.
  17979. The co-ordinates are relative to the component's top-left corner.
  17980. */
  17981. void getMouseXYRelative (int& x, int& y) const throw();
  17982. /** Returns the component that's currently underneath the mouse.
  17983. @returns the component or 0 if there isn't one.
  17984. @see contains, getComponentAt
  17985. */
  17986. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  17987. /** Allows the mouse to move beyond the edges of the screen.
  17988. Calling this method when the mouse button is currently pressed inside this component
  17989. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  17990. the edges of the screen.
  17991. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  17992. can be used for things like custom slider controls or dragging objects around, where
  17993. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  17994. The unbounded mode is automatically turned off when the mouse button is released, or
  17995. it can be turned off explicitly by calling this method again.
  17996. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  17997. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  17998. hidden; if true, it will only be hidden when it
  17999. is moved beyond the edge of the screen
  18000. */
  18001. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  18002. bool keepCursorVisibleUntilOffscreen = false) throw();
  18003. /** Called when this component's size has been changed.
  18004. A component can implement this method to do things such as laying out its
  18005. child components when its width or height changes.
  18006. The method is called synchronously as a result of the setBounds or setSize
  18007. methods, so repeatedly changing a components size will repeatedly call its
  18008. resized method (unlike things like repainting, where multiple calls to repaint
  18009. are coalesced together).
  18010. If the component is a top-level window on the desktop, its size could also
  18011. be changed by operating-system factors beyond the application's control.
  18012. @see moved, setSize
  18013. */
  18014. virtual void resized();
  18015. /** Called when this component's position has been changed.
  18016. This is called when the position relative to its parent changes, not when
  18017. its absolute position on the screen changes (so it won't be called for
  18018. all child components when a parent component is moved).
  18019. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  18020. or any of the other repositioning methods, and like resized(), it will be
  18021. called each time those methods are called.
  18022. If the component is a top-level window on the desktop, its position could also
  18023. be changed by operating-system factors beyond the application's control.
  18024. @see resized, setBounds
  18025. */
  18026. virtual void moved();
  18027. /** Called when one of this component's children is moved or resized.
  18028. If the parent wants to know about changes to its immediate children (not
  18029. to children of its children), this is the method to override.
  18030. @see moved, resized, parentSizeChanged
  18031. */
  18032. virtual void childBoundsChanged (Component* child);
  18033. /** Called when this component's immediate parent has been resized.
  18034. If the component is a top-level window, this indicates that the screen size
  18035. has changed.
  18036. @see childBoundsChanged, moved, resized
  18037. */
  18038. virtual void parentSizeChanged();
  18039. /** Called when this component has been moved to the front of its siblings.
  18040. The component may have been brought to the front by the toFront() method, or
  18041. by the operating system if it's a top-level window.
  18042. @see toFront
  18043. */
  18044. virtual void broughtToFront();
  18045. /** Adds a listener to be told about changes to the component hierarchy or position.
  18046. Component listeners get called when this component's size, position or children
  18047. change - see the ComponentListener class for more details.
  18048. @param newListener the listener to register - if this is already registered, it
  18049. will be ignored.
  18050. @see ComponentListener, removeComponentListener
  18051. */
  18052. void addComponentListener (ComponentListener* const newListener) throw();
  18053. /** Removes a component listener.
  18054. @see addComponentListener
  18055. */
  18056. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  18057. /** Dispatches a numbered message to this component.
  18058. This is a quick and cheap way of allowing simple asynchronous messages to
  18059. be sent to components. It's also safe, because if the component that you
  18060. send the message to is a null or dangling pointer, this won't cause an error.
  18061. The command ID is later delivered to the component's handleCommandMessage() method by
  18062. the application's message queue.
  18063. @see handleCommandMessage
  18064. */
  18065. void postCommandMessage (const int commandId) throw();
  18066. /** Called to handle a command that was sent by postCommandMessage().
  18067. This is called by the message thread when a command message arrives, and
  18068. the component can override this method to process it in any way it needs to.
  18069. @see postCommandMessage
  18070. */
  18071. virtual void handleCommandMessage (int commandId);
  18072. /** Runs a component modally, waiting until the loop terminates.
  18073. This method first makes the component visible, brings it to the front and
  18074. gives it the keyboard focus.
  18075. It then runs a loop, dispatching messages from the system message queue, but
  18076. blocking all mouse or keyboard messages from reaching any components other
  18077. than this one and its children.
  18078. This loop continues until the component's exitModalState() method is called (or
  18079. the component is deleted), and then this method returns, returning the value
  18080. passed into exitModalState().
  18081. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  18082. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  18083. */
  18084. int runModalLoop();
  18085. /** Puts the component into a modal state.
  18086. This makes the component modal, so that messages are blocked from reaching
  18087. any components other than this one and its children, but unlike runModalLoop(),
  18088. this method returns immediately.
  18089. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  18090. get the focus, which is usually what you'll want it to do. If not, it will leave
  18091. the focus unchanged.
  18092. @see exitModalState, runModalLoop
  18093. */
  18094. void enterModalState (const bool takeKeyboardFocus = true);
  18095. /** Ends a component's modal state.
  18096. If this component is currently modal, this will turn of its modalness, and return
  18097. a value to the runModalLoop() method that might have be running its modal loop.
  18098. @see runModalLoop, enterModalState, isCurrentlyModal
  18099. */
  18100. void exitModalState (const int returnValue);
  18101. /** Returns true if this component is the modal one.
  18102. It's possible to have nested modal components, e.g. a pop-up dialog box
  18103. that launches another pop-up, but this will only return true for
  18104. the one at the top of the stack.
  18105. @see getCurrentlyModalComponent
  18106. */
  18107. bool isCurrentlyModal() const throw();
  18108. /** Returns the number of components that are currently in a modal state.
  18109. @see getCurrentlyModalComponent
  18110. */
  18111. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  18112. /** Returns one of the components that are currently modal.
  18113. The index specifies which of the possible modal components to return. The order
  18114. of the components in this list is the reverse of the order in which they became
  18115. modal - so the component at index 0 is always the active component, and the others
  18116. are progressively earlier ones that are themselves now blocked by later ones.
  18117. @returns the modal component, or null if no components are modal (or if the
  18118. index is out of range)
  18119. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  18120. */
  18121. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  18122. /** Checks whether there's a modal component somewhere that's stopping this one
  18123. from receiving messages.
  18124. If there is a modal component, its canModalEventBeSentToComponent() method
  18125. will be called to see if it will still allow this component to receive events.
  18126. @see runModalLoop, getCurrentlyModalComponent
  18127. */
  18128. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  18129. /** When a component is modal, this callback allows it to choose which other
  18130. components can still receive events.
  18131. When a modal component is active and the user clicks on a non-modal component,
  18132. this method is called on the modal component, and if it returns true, the
  18133. event is allowed to reach its target. If it returns false, the event is blocked
  18134. and the inputAttemptWhenModal() callback is made.
  18135. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  18136. implementation just returns false in all cases.
  18137. */
  18138. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  18139. /** Called when the user tries to click on a component that is blocked by another
  18140. modal component.
  18141. When a component is modal and the user clicks on one of the other components,
  18142. the modal component will receive this callback.
  18143. The default implementation of this method will play a beep, and bring the currently
  18144. modal component to the front, but it can be overridden to do other tasks.
  18145. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  18146. */
  18147. virtual void inputAttemptWhenModal();
  18148. /** Returns one of the component's properties as a string.
  18149. @param keyName the name of the property to retrieve
  18150. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18151. properties, then it will check whether the parent component has
  18152. the key.
  18153. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18154. */
  18155. const String getComponentProperty (const String& keyName,
  18156. const bool useParentComponentIfNotFound,
  18157. const String& defaultReturnValue = String::empty) const throw();
  18158. /** Returns one of the properties as an integer.
  18159. @param keyName the name of the property to retrieve
  18160. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18161. properties, then it will check whether the parent component has
  18162. the key.
  18163. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18164. */
  18165. int getComponentPropertyInt (const String& keyName,
  18166. const bool useParentComponentIfNotFound,
  18167. const int defaultReturnValue = 0) const throw();
  18168. /** Returns one of the properties as an double.
  18169. @param keyName the name of the property to retrieve
  18170. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18171. properties, then it will check whether the parent component has
  18172. the key.
  18173. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18174. */
  18175. double getComponentPropertyDouble (const String& keyName,
  18176. const bool useParentComponentIfNotFound,
  18177. const double defaultReturnValue = 0.0) const throw();
  18178. /** Returns one of the properties as an boolean.
  18179. The result will be true if the string found for this key name can be parsed as a non-zero
  18180. integer.
  18181. @param keyName the name of the property to retrieve
  18182. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18183. properties, then it will check whether the parent component has
  18184. the key.
  18185. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18186. */
  18187. bool getComponentPropertyBool (const String& keyName,
  18188. const bool useParentComponentIfNotFound,
  18189. const bool defaultReturnValue = false) const throw();
  18190. /** Returns one of the properties as an colour.
  18191. @param keyName the name of the property to retrieve
  18192. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18193. properties, then it will check whether the parent component has
  18194. the key.
  18195. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  18196. */
  18197. const Colour getComponentPropertyColour (const String& keyName,
  18198. const bool useParentComponentIfNotFound,
  18199. const Colour& defaultReturnValue = Colours::black) const throw();
  18200. /** Sets a named property as a string.
  18201. @param keyName the name of the property to set. (This mustn't be an empty string)
  18202. @param value the new value to set it to
  18203. @see removeComponentProperty
  18204. */
  18205. void setComponentProperty (const String& keyName, const String& value) throw();
  18206. /** Sets a named property to an integer.
  18207. @param keyName the name of the property to set. (This mustn't be an empty string)
  18208. @param value the new value to set it to
  18209. @see removeComponentProperty
  18210. */
  18211. void setComponentProperty (const String& keyName, const int value) throw();
  18212. /** Sets a named property to a double.
  18213. @param keyName the name of the property to set. (This mustn't be an empty string)
  18214. @param value the new value to set it to
  18215. @see removeComponentProperty
  18216. */
  18217. void setComponentProperty (const String& keyName, const double value) throw();
  18218. /** Sets a named property to a boolean.
  18219. @param keyName the name of the property to set. (This mustn't be an empty string)
  18220. @param value the new value to set it to
  18221. @see removeComponentProperty
  18222. */
  18223. void setComponentProperty (const String& keyName, const bool value) throw();
  18224. /** Sets a named property to a colour.
  18225. @param keyName the name of the property to set. (This mustn't be an empty string)
  18226. @param newColour the new colour to set it to
  18227. @see removeComponentProperty
  18228. */
  18229. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  18230. /** Deletes a named component property.
  18231. @param keyName the name of the property to delete. (This mustn't be an empty string)
  18232. @see setComponentProperty, getComponentProperty
  18233. */
  18234. void removeComponentProperty (const String& keyName) throw();
  18235. /** Returns the complete set of properties that have been set for this component.
  18236. If no properties have been set, this will return a null pointer.
  18237. @see getComponentProperty, setComponentProperty
  18238. */
  18239. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  18240. /** Looks for a colour that has been registered with the given colour ID number.
  18241. If a colour has been set for this ID number using setColour(), then it is
  18242. returned. If none has been set, the method will try calling the component's
  18243. LookAndFeel class's findColour() method. If none has been registered with the
  18244. look-and-feel either, it will just return black.
  18245. The colour IDs for various purposes are stored as enums in the components that
  18246. they are relevent to - for an example, see Slider::ColourIds,
  18247. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  18248. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  18249. */
  18250. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  18251. /** Registers a colour to be used for a particular purpose.
  18252. Changing a colour will cause a synchronous callback to the colourChanged()
  18253. method, which your component can override if it needs to do something when
  18254. colours are altered.
  18255. For more details about colour IDs, see the comments for findColour().
  18256. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  18257. */
  18258. void setColour (const int colourId, const Colour& colour);
  18259. /** If a colour has been set with setColour(), this will remove it.
  18260. This allows you to make a colour revert to its default state.
  18261. */
  18262. void removeColour (const int colourId);
  18263. /** Returns true if the specified colour ID has been explicitly set for this
  18264. component using the setColour() method.
  18265. */
  18266. bool isColourSpecified (const int colourId) const throw();
  18267. /** This looks for any colours that have been specified for this component,
  18268. and copies them to the specified target component.
  18269. */
  18270. void copyAllExplicitColoursTo (Component& target) const throw();
  18271. /** This method is called when a colour is changed by the setColour() method.
  18272. @see setColour, findColour
  18273. */
  18274. virtual void colourChanged();
  18275. /** Returns the underlying native window handle for this component.
  18276. This is platform-dependent and strictly for power-users only!
  18277. */
  18278. void* getWindowHandle() const throw();
  18279. /** When created, each component is given a number to uniquely identify it.
  18280. The number is incremented each time a new component is created, so it's a more
  18281. unique way of identifying a component than using its memory location (which
  18282. may be reused after the component is deleted, of course).
  18283. */
  18284. uint32 getComponentUID() const throw() { return componentUID; }
  18285. juce_UseDebuggingNewOperator
  18286. private:
  18287. friend class ComponentPeer;
  18288. friend class InternalDragRepeater;
  18289. static Component* currentlyFocusedComponent;
  18290. static Component* componentUnderMouse;
  18291. String componentName_;
  18292. Component* parentComponent_;
  18293. uint32 componentUID;
  18294. Rectangle bounds_;
  18295. unsigned short numDeepMouseListeners;
  18296. Array <Component*> childComponentList_;
  18297. LookAndFeel* lookAndFeel_;
  18298. MouseCursor cursor_;
  18299. ImageEffectFilter* effect_;
  18300. Image* bufferedImage_;
  18301. VoidArray* mouseListeners_;
  18302. VoidArray* keyListeners_;
  18303. VoidArray* componentListeners_;
  18304. PropertySet* propertySet_;
  18305. struct ComponentFlags
  18306. {
  18307. bool hasHeavyweightPeerFlag : 1;
  18308. bool visibleFlag : 1;
  18309. bool opaqueFlag : 1;
  18310. bool ignoresMouseClicksFlag : 1;
  18311. bool allowChildMouseClicksFlag : 1;
  18312. bool wantsFocusFlag : 1;
  18313. bool isFocusContainerFlag : 1;
  18314. bool dontFocusOnMouseClickFlag : 1;
  18315. bool alwaysOnTopFlag : 1;
  18316. bool bufferToImageFlag : 1;
  18317. bool bringToFrontOnClickFlag : 1;
  18318. bool repaintOnMouseActivityFlag : 1;
  18319. bool draggingFlag : 1;
  18320. bool mouseOverFlag : 1;
  18321. bool mouseInsideFlag : 1;
  18322. bool currentlyModalFlag : 1;
  18323. bool isDisabledFlag : 1;
  18324. bool childCompFocusedFlag : 1;
  18325. #ifdef JUCE_DEBUG
  18326. bool isInsidePaintCall : 1;
  18327. #endif
  18328. };
  18329. union
  18330. {
  18331. uint32 componentFlags_;
  18332. ComponentFlags flags;
  18333. };
  18334. void internalMouseEnter (int x, int y, const int64 time);
  18335. void internalMouseExit (int x, int y, const int64 time);
  18336. void internalMouseDown (int x, int y);
  18337. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  18338. void internalMouseDrag (int x, int y, const int64 time);
  18339. void internalMouseMove (int x, int y, const int64 time);
  18340. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  18341. void internalBroughtToFront();
  18342. void internalFocusGain (const FocusChangeType cause);
  18343. void internalFocusLoss (const FocusChangeType cause);
  18344. void internalChildFocusChange (FocusChangeType cause);
  18345. void internalModalInputAttempt();
  18346. void internalModifierKeysChanged();
  18347. void internalChildrenChanged();
  18348. void internalHierarchyChanged();
  18349. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  18350. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  18351. void repaintParent() throw();
  18352. void sendFakeMouseMove() const;
  18353. void takeKeyboardFocus (const FocusChangeType cause);
  18354. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  18355. static void giveAwayFocus();
  18356. void sendEnablementChangeMessage();
  18357. static void* runModalLoopCallback (void*);
  18358. static void bringModalComponentToFront();
  18359. void subtractObscuredRegions (RectangleList& result,
  18360. const int deltaX, const int deltaY,
  18361. const Rectangle& clipRect,
  18362. const Component* const compToAvoid) const throw();
  18363. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  18364. const int deltaX, const int deltaY) const throw();
  18365. // how much of the component is not off the edges of its parents
  18366. const Rectangle getUnclippedArea() const;
  18367. void sendVisibilityChangeMessage();
  18368. // This is included here just to cause a compile error if your code is still handling
  18369. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  18370. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  18371. // implement its methods instead of this Component method).
  18372. virtual void filesDropped (const StringArray&, int, int) {}
  18373. // components aren't allowed to have copy constructors, as this would mess up parent
  18374. // hierarchies. You might need to give your subclasses a private dummy constructor like
  18375. // this one to avoid compiler warnings.
  18376. Component (const Component&);
  18377. const Component& operator= (const Component&);
  18378. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  18379. // subclass to use the new parameters to keyStateChanged)
  18380. virtual void keyStateChanged() {};
  18381. protected:
  18382. /** @internal */
  18383. virtual void internalRepaint (int x, int y, int w, int h);
  18384. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  18385. /** Overridden from the MessageListener parent class.
  18386. You can override this if you really need to, but be sure to pass your unwanted messages up
  18387. to this base class implementation, as the Component class needs to send itself messages
  18388. to work properly.
  18389. */
  18390. void handleMessage (const Message&);
  18391. };
  18392. #endif // __JUCE_COMPONENT_JUCEHEADER__
  18393. /********* End of inlined file: juce_Component.h *********/
  18394. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  18395. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18396. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18397. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  18398. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18399. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18400. /** A type used to hold the unique ID for an application command.
  18401. This is a numeric type, so it can be stored as an integer.
  18402. @see ApplicationCommandInfo, ApplicationCommandManager,
  18403. ApplicationCommandTarget, KeyPressMappingSet
  18404. */
  18405. typedef int CommandID;
  18406. /** A set of general-purpose application command IDs.
  18407. Because these commands are likely to be used in most apps, they're defined
  18408. here to help different apps to use the same numeric values for them.
  18409. Of course you don't have to use these, but some of them are used internally by
  18410. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  18411. @see ApplicationCommandInfo, ApplicationCommandManager,
  18412. ApplicationCommandTarget, KeyPressMappingSet
  18413. */
  18414. namespace StandardApplicationCommandIDs
  18415. {
  18416. /** This command ID should be used to send a "Quit the App" command.
  18417. This command is recognised by the JUCEApplication class, so if it is invoked
  18418. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  18419. object will catch it and call JUCEApplication::systemRequestedQuit().
  18420. */
  18421. static const CommandID quit = 0x1001;
  18422. /** The command ID that should be used to send a "Delete" command. */
  18423. static const CommandID del = 0x1002;
  18424. /** The command ID that should be used to send a "Cut" command. */
  18425. static const CommandID cut = 0x1003;
  18426. /** The command ID that should be used to send a "Copy to clipboard" command. */
  18427. static const CommandID copy = 0x1004;
  18428. /** The command ID that should be used to send a "Paste from clipboard" command. */
  18429. static const CommandID paste = 0x1005;
  18430. /** The command ID that should be used to send a "Select all" command. */
  18431. static const CommandID selectAll = 0x1006;
  18432. /** The command ID that should be used to send a "Deselect all" command. */
  18433. static const CommandID deselectAll = 0x1007;
  18434. }
  18435. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18436. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  18437. /**
  18438. Holds information describing an application command.
  18439. This object is used to pass information about a particular command, such as its
  18440. name, description and other usage flags.
  18441. When an ApplicationCommandTarget is asked to provide information about the commands
  18442. it can perform, this is the structure gets filled-in to describe each one.
  18443. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  18444. ApplicationCommandManager
  18445. */
  18446. struct JUCE_API ApplicationCommandInfo
  18447. {
  18448. ApplicationCommandInfo (const CommandID commandID) throw();
  18449. /** Sets a number of the structures values at once.
  18450. The meanings of each of the parameters is described below, in the appropriate
  18451. member variable's description.
  18452. */
  18453. void setInfo (const String& shortName,
  18454. const String& description,
  18455. const String& categoryName,
  18456. const int flags) throw();
  18457. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  18458. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  18459. is false, the bit is set.
  18460. */
  18461. void setActive (const bool isActive) throw();
  18462. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  18463. */
  18464. void setTicked (const bool isTicked) throw();
  18465. /** Handy method for adding a keypress to the defaultKeypresses array.
  18466. This is just so you can write things like:
  18467. @code
  18468. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  18469. @endcode
  18470. instead of
  18471. @code
  18472. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  18473. @endcode
  18474. */
  18475. void addDefaultKeypress (const int keyCode,
  18476. const ModifierKeys& modifiers) throw();
  18477. /** The command's unique ID number.
  18478. */
  18479. CommandID commandID;
  18480. /** A short name to describe the command.
  18481. This should be suitable for use in menus, on buttons that trigger the command, etc.
  18482. You can use the setInfo() method to quickly set this and some of the command's
  18483. other properties.
  18484. */
  18485. String shortName;
  18486. /** A longer description of the command.
  18487. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  18488. pop-up tooltip describing what the command does.
  18489. You can use the setInfo() method to quickly set this and some of the command's
  18490. other properties.
  18491. */
  18492. String description;
  18493. /** A named category that the command fits into.
  18494. You can give your commands any category you like, and these will be displayed in
  18495. contexts such as the KeyMappingEditorComponent, where the category is used to group
  18496. commands together.
  18497. You can use the setInfo() method to quickly set this and some of the command's
  18498. other properties.
  18499. */
  18500. String categoryName;
  18501. /** A list of zero or more keypresses that should be used as the default keys for
  18502. this command.
  18503. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  18504. this list to initialise the default set of key-to-command mappings.
  18505. @see addDefaultKeypress
  18506. */
  18507. Array <KeyPress> defaultKeypresses;
  18508. /** Flags describing the ways in which this command should be used.
  18509. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  18510. variable.
  18511. */
  18512. enum CommandFlags
  18513. {
  18514. /** Indicates that the command can't currently be performed.
  18515. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  18516. not currently permissable to perform the command. If the flag is set, then
  18517. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  18518. command or show themselves as not being enabled.
  18519. @see ApplicationCommandInfo::setActive
  18520. */
  18521. isDisabled = 1 << 0,
  18522. /** Indicates that the command should have a tick next to it on a menu.
  18523. If your command is shown on a menu and this is set, it'll show a tick next to
  18524. it. Other components such as buttons may also use this flag to indicate that it
  18525. is a value that can be toggled, and is currently in the 'on' state.
  18526. @see ApplicationCommandInfo::setTicked
  18527. */
  18528. isTicked = 1 << 1,
  18529. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  18530. it will call the command twice, once on key-down and again on key-up.
  18531. @see ApplicationCommandTarget::InvocationInfo
  18532. */
  18533. wantsKeyUpDownCallbacks = 1 << 2,
  18534. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  18535. command in its list.
  18536. */
  18537. hiddenFromKeyEditor = 1 << 3,
  18538. /** If this flag is present, then a KeyMappingEditorComponent will display the
  18539. command in its list, but won't allow the assigned keypress to be changed.
  18540. */
  18541. readOnlyInKeyEditor = 1 << 4,
  18542. /** If this flag is present and the command is invoked from a keypress, then any
  18543. buttons or menus that are also connected to the command will not flash to
  18544. indicate that they've been triggered.
  18545. */
  18546. dontTriggerVisualFeedback = 1 << 5
  18547. };
  18548. /** A bitwise-OR of the values specified in the CommandFlags enum.
  18549. You can use the setInfo() method to quickly set this and some of the command's
  18550. other properties.
  18551. */
  18552. int flags;
  18553. };
  18554. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18555. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  18556. /**
  18557. A command target publishes a list of command IDs that it can perform.
  18558. An ApplicationCommandManager despatches commands to targets, which must be
  18559. able to provide information about what commands they can handle.
  18560. To create a target, you'll need to inherit from this class, implementing all of
  18561. its pure virtual methods.
  18562. For info about how a target is chosen to receive a command, see
  18563. ApplicationCommandManager::getFirstCommandTarget().
  18564. @see ApplicationCommandManager, ApplicationCommandInfo
  18565. */
  18566. class JUCE_API ApplicationCommandTarget
  18567. {
  18568. public:
  18569. /** Creates a command target. */
  18570. ApplicationCommandTarget();
  18571. /** Destructor. */
  18572. virtual ~ApplicationCommandTarget();
  18573. /**
  18574. */
  18575. struct JUCE_API InvocationInfo
  18576. {
  18577. InvocationInfo (const CommandID commandID) throw();
  18578. /** The UID of the command that should be performed. */
  18579. CommandID commandID;
  18580. /** The command's flags.
  18581. See ApplicationCommandInfo for a description of these flag values.
  18582. */
  18583. int commandFlags;
  18584. /** The types of context in which the command might be called. */
  18585. enum InvocationMethod
  18586. {
  18587. direct = 0, /**< The command is being invoked directly by a piece of code. */
  18588. fromKeyPress, /**< The command is being invoked by a key-press. */
  18589. fromMenu, /**< The command is being invoked by a menu selection. */
  18590. fromButton /**< The command is being invoked by a button click. */
  18591. };
  18592. /** The type of event that triggered this command. */
  18593. InvocationMethod invocationMethod;
  18594. /** If triggered by a keypress or menu, this will be the component that had the
  18595. keyboard focus at the time.
  18596. If triggered by a button, it may be set to that component, or it may be null.
  18597. */
  18598. Component* originatingComponent;
  18599. /** The keypress that was used to invoke it.
  18600. Note that this will be an invalid keypress if the command was invoked
  18601. by some other means than a keyboard shortcut.
  18602. */
  18603. KeyPress keyPress;
  18604. /** True if the callback is being invoked when the key is pressed,
  18605. false if the key is being released.
  18606. @see KeyPressMappingSet::addCommand()
  18607. */
  18608. bool isKeyDown;
  18609. /** If the key is being released, this indicates how long it had been held
  18610. down for.
  18611. (Only relevant if isKeyDown is false.)
  18612. */
  18613. int millisecsSinceKeyPressed;
  18614. };
  18615. /** This must return the next target to try after this one.
  18616. When a command is being sent, and the first target can't handle
  18617. that command, this method is used to determine the next target that should
  18618. be tried.
  18619. It may return 0 if it doesn't know of another target.
  18620. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  18621. method to return a parent component that might want to handle it.
  18622. @see invoke
  18623. */
  18624. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  18625. /** This must return a complete list of commands that this target can handle.
  18626. Your target should add all the command IDs that it handles to the array that is
  18627. passed-in.
  18628. */
  18629. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  18630. /** This must provide details about one of the commands that this target can perform.
  18631. This will be called with one of the command IDs that the target provided in its
  18632. getAllCommands() methods.
  18633. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  18634. suitable information about the command. (The commandID field will already have been filled-in
  18635. by the caller).
  18636. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  18637. set all the fields at once.
  18638. If the command is currently inactive for some reason, this method must use
  18639. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  18640. bit of the ApplicationCommandInfo::flags field).
  18641. Any default key-presses for the command should be appended to the
  18642. ApplicationCommandInfo::defaultKeypresses field.
  18643. Note that if you change something that affects the status of the commands
  18644. that would be returned by this method (e.g. something that makes some commands
  18645. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  18646. to cause the manager to refresh its status.
  18647. */
  18648. virtual void getCommandInfo (const CommandID commandID,
  18649. ApplicationCommandInfo& result) = 0;
  18650. /** This must actually perform the specified command.
  18651. If this target is able to perform the command specified by the commandID field of the
  18652. InvocationInfo structure, then it should do so, and must return true.
  18653. If it can't handle this command, it should return false, which tells the caller to pass
  18654. the command on to the next target in line.
  18655. @see invoke, ApplicationCommandManager::invoke
  18656. */
  18657. virtual bool perform (const InvocationInfo& info) = 0;
  18658. /** Makes this target invoke a command.
  18659. Your code can call this method to invoke a command on this target, but normally
  18660. you'd call it indirectly via ApplicationCommandManager::invoke() or
  18661. ApplicationCommandManager::invokeDirectly().
  18662. If this target can perform the given command, it will call its perform() method to
  18663. do so. If not, then getNextCommandTarget() will be used to determine the next target
  18664. to try, and the command will be passed along to it.
  18665. @param invocationInfo this must be correctly filled-in, describing the context for
  18666. the invocation.
  18667. @param asynchronously if false, the command will be performed before this method returns.
  18668. If true, a message will be posted so that the command will be performed
  18669. later on the message thread, and this method will return immediately.
  18670. @see perform, ApplicationCommandManager::invoke
  18671. */
  18672. bool invoke (const InvocationInfo& invocationInfo,
  18673. const bool asynchronously);
  18674. /** Invokes a given command directly on this target.
  18675. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18676. structure.
  18677. */
  18678. bool invokeDirectly (const CommandID commandID,
  18679. const bool asynchronously);
  18680. /** Searches this target and all subsequent ones for the first one that can handle
  18681. the specified command.
  18682. This will use getNextCommandTarget() to determine the chain of targets to try
  18683. after this one.
  18684. */
  18685. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  18686. /** Checks whether this command can currently be performed by this target.
  18687. This will return true only if a call to getCommandInfo() doesn't set the
  18688. isDisabled flag to indicate that the command is inactive.
  18689. */
  18690. bool isCommandActive (const CommandID commandID);
  18691. /** If this object is a Component, this method will seach upwards in its current
  18692. UI hierarchy for the next parent component that implements the
  18693. ApplicationCommandTarget class.
  18694. If your target is a Component, this is a very handy method to use in your
  18695. getNextCommandTarget() implementation.
  18696. */
  18697. ApplicationCommandTarget* findFirstTargetParentComponent();
  18698. juce_UseDebuggingNewOperator
  18699. private:
  18700. // (for async invocation of commands)
  18701. class CommandTargetMessageInvoker : public MessageListener
  18702. {
  18703. public:
  18704. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  18705. ~CommandTargetMessageInvoker();
  18706. void handleMessage (const Message& message);
  18707. private:
  18708. ApplicationCommandTarget* const owner;
  18709. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  18710. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  18711. };
  18712. CommandTargetMessageInvoker* messageInvoker;
  18713. friend class CommandTargetMessageInvoker;
  18714. bool tryToInvoke (const InvocationInfo& info, const bool async);
  18715. ApplicationCommandTarget (const ApplicationCommandTarget&);
  18716. const ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  18717. };
  18718. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18719. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  18720. /********* Start of inlined file: juce_ActionListener.h *********/
  18721. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  18722. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  18723. /**
  18724. Receives callbacks to indicate that some kind of event has occurred.
  18725. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  18726. about something that's happened.
  18727. @see ActionListenerList, ActionBroadcaster, ChangeListener
  18728. */
  18729. class JUCE_API ActionListener
  18730. {
  18731. public:
  18732. /** Destructor. */
  18733. virtual ~ActionListener() {}
  18734. /** Overridden by your subclass to receive the callback.
  18735. @param message the string that was specified when the event was triggered
  18736. by a call to ActionListenerList::sendActionMessage()
  18737. */
  18738. virtual void actionListenerCallback (const String& message) = 0;
  18739. };
  18740. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  18741. /********* End of inlined file: juce_ActionListener.h *********/
  18742. /**
  18743. An instance of this class is used to specify initialisation and shutdown
  18744. code for the application.
  18745. An application that wants to run in the JUCE framework needs to declare a
  18746. subclass of JUCEApplication and implement its various pure virtual methods.
  18747. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  18748. to declare an instance of this class and generate a suitable platform-specific
  18749. main() function.
  18750. e.g. @code
  18751. class MyJUCEApp : public JUCEApplication
  18752. {
  18753. // NEVER put objects inside a JUCEApplication class - only use pointers to
  18754. // objects, which you must create in the initialise() method.
  18755. MyApplicationWindow* myMainWindow;
  18756. public:
  18757. MyJUCEApp()
  18758. : myMainWindow (0)
  18759. {
  18760. // never create any Juce objects in the constructor - do all your initialisation
  18761. // in the initialise() method.
  18762. }
  18763. ~MyJUCEApp()
  18764. {
  18765. // all your shutdown code must have already been done in the shutdown() method -
  18766. // nothing should happen in this destructor.
  18767. }
  18768. void initialise (const String& commandLine)
  18769. {
  18770. myMainWindow = new MyApplicationWindow();
  18771. myMainWindow->setBounds (100, 100, 400, 500);
  18772. myMainWindow->setVisible (true);
  18773. }
  18774. void shutdown()
  18775. {
  18776. delete myMainWindow;
  18777. }
  18778. const String getApplicationName()
  18779. {
  18780. return T("Super JUCE-o-matic");
  18781. }
  18782. const String getApplicationVersion()
  18783. {
  18784. return T("1.0");
  18785. }
  18786. };
  18787. // this creates wrapper code to actually launch the app properly.
  18788. START_JUCE_APPLICATION (MyJUCEApp)
  18789. @endcode
  18790. Because this object will be created before Juce has properly initialised, you must
  18791. NEVER add any member variable objects that will be automatically constructed. Likewise
  18792. don't put ANY code in the constructor that could call Juce functions. Any objects that
  18793. you want to add to the class must be pointers, which you should instantiate during the
  18794. initialise() method, and delete in the shutdown() method.
  18795. @see MessageManager, DeletedAtShutdown
  18796. */
  18797. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  18798. private ActionListener
  18799. {
  18800. protected:
  18801. /** Constructs a JUCE app object.
  18802. If subclasses implement a constructor or destructor, they shouldn't call any
  18803. JUCE code in there - put your startup/shutdown code in initialise() and
  18804. shutdown() instead.
  18805. */
  18806. JUCEApplication();
  18807. public:
  18808. /** Destructor.
  18809. If subclasses implement a constructor or destructor, they shouldn't call any
  18810. JUCE code in there - put your startup/shutdown code in initialise() and
  18811. shutdown() instead.
  18812. */
  18813. virtual ~JUCEApplication();
  18814. /** Returns the global instance of the application object being run. */
  18815. static JUCEApplication* getInstance() throw();
  18816. /** Called when the application starts.
  18817. This will be called once to let the application do whatever initialisation
  18818. it needs, create its windows, etc.
  18819. After the method returns, the normal event-dispatch loop will be run,
  18820. until the quit() method is called, at which point the shutdown()
  18821. method will be called to let the application clear up anything it needs
  18822. to delete.
  18823. If during the initialise() method, the application decides not to start-up
  18824. after all, it can just call the quit() method and the event loop won't be run.
  18825. @param commandLineParameters the line passed in does not include the
  18826. name of the executable, just the parameter list.
  18827. @see shutdown, quit
  18828. */
  18829. virtual void initialise (const String& commandLineParameters) = 0;
  18830. /** Returns true if the application hasn't yet completed its initialise() method
  18831. and entered the main event loop.
  18832. This is handy for things like splash screens to know when the app's up-and-running
  18833. properly.
  18834. */
  18835. bool isInitialising() const throw();
  18836. /* Called to allow the application to clear up before exiting.
  18837. After JUCEApplication::quit() has been called, the event-dispatch loop will
  18838. terminate, and this method will get called to allow the app to sort itself
  18839. out.
  18840. Be careful that nothing happens in this method that might rely on messages
  18841. being sent, or any kind of window activity, because the message loop is no
  18842. longer running at this point.
  18843. @see DeletedAtShutdown
  18844. */
  18845. virtual void shutdown() = 0;
  18846. /** Returns the application's name.
  18847. An application must implement this to name itself.
  18848. */
  18849. virtual const String getApplicationName() = 0;
  18850. /** Returns the application's version number.
  18851. An application can implement this to give itself a version.
  18852. (The default implementation of this just returns an empty string).
  18853. */
  18854. virtual const String getApplicationVersion();
  18855. /** Checks whether multiple instances of the app are allowed.
  18856. If you application class returns true for this, more than one instance is
  18857. permitted to run (except on the Mac where this isn't possible).
  18858. If it's false, the second instance won't start, but it you will still get a
  18859. callback to anotherInstanceStarted() to tell you about this - which
  18860. gives you a chance to react to what the user was trying to do.
  18861. */
  18862. virtual bool moreThanOneInstanceAllowed();
  18863. /** Indicates that the user has tried to start up another instance of the app.
  18864. This will get called even if moreThanOneInstanceAllowed() is false.
  18865. */
  18866. virtual void anotherInstanceStarted (const String& commandLine);
  18867. /** Called when the operating system is trying to close the application.
  18868. The default implementation of this method is to call quit(), but it may
  18869. be overloaded to ignore the request or do some other special behaviour
  18870. instead. For example, you might want to offer the user the chance to save
  18871. their changes before quitting, and give them the chance to cancel.
  18872. If you want to send a quit signal to your app, this is the correct method
  18873. to call, because it means that requests that come from the system get handled
  18874. in the same way as those from your own application code. So e.g. you'd
  18875. call this method from a "quit" item on a menu bar.
  18876. */
  18877. virtual void systemRequestedQuit();
  18878. /** If any unhandled exceptions make it through to the message dispatch loop, this
  18879. callback will be triggered, in case you want to log them or do some other
  18880. type of error-handling.
  18881. If the type of exception is derived from the std::exception class, the pointer
  18882. passed-in will be valid. If the exception is of unknown type, this pointer
  18883. will be null.
  18884. */
  18885. virtual void unhandledException (const std::exception* e,
  18886. const String& sourceFilename,
  18887. const int lineNumber);
  18888. /** Signals that the main message loop should stop and the application should terminate.
  18889. This isn't synchronous, it just posts a quit message to the main queue, and
  18890. when this message arrives, the message loop will stop, the shutdown() method
  18891. will be called, and the app will exit.
  18892. Note that this will cause an unconditional quit to happen, so if you need an
  18893. extra level before this, e.g. to give the user the chance to save their work
  18894. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  18895. method - see that method's help for more info.
  18896. @see MessageManager, DeletedAtShutdown
  18897. */
  18898. static void quit();
  18899. /** Sets the value that should be returned as the application's exit code when the
  18900. app quits.
  18901. This is the value that's returned by the main() function. Normally you'd leave this
  18902. as 0 unless you want to indicate an error code.
  18903. @see getApplicationReturnValue
  18904. */
  18905. void setApplicationReturnValue (const int newReturnValue) throw();
  18906. /** Returns the value that has been set as the application's exit code.
  18907. @see setApplicationReturnValue
  18908. */
  18909. int getApplicationReturnValue() const throw() { return appReturnValue; }
  18910. /** Returns the application's command line params.
  18911. */
  18912. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  18913. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  18914. /** @internal */
  18915. static int main (String& commandLine, JUCEApplication* const newApp);
  18916. /** @internal */
  18917. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  18918. /** @internal */
  18919. static void sendUnhandledException (const std::exception* const e,
  18920. const char* const sourceFile,
  18921. const int lineNumber);
  18922. /** @internal */
  18923. ApplicationCommandTarget* getNextCommandTarget();
  18924. /** @internal */
  18925. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  18926. /** @internal */
  18927. void getAllCommands (Array <CommandID>& commands);
  18928. /** @internal */
  18929. bool perform (const InvocationInfo& info);
  18930. /** @internal */
  18931. void actionListenerCallback (const String& message);
  18932. private:
  18933. String commandLineParameters;
  18934. int appReturnValue;
  18935. bool stillInitialising;
  18936. InterProcessLock* appLock;
  18937. JUCEApplication (const JUCEApplication&);
  18938. const JUCEApplication& operator= (const JUCEApplication&);
  18939. public:
  18940. /** @internal */
  18941. bool initialiseApp (String& commandLine);
  18942. /** @internal */
  18943. static int shutdownAppAndClearUp();
  18944. };
  18945. #endif // __JUCE_APPLICATION_JUCEHEADER__
  18946. /********* End of inlined file: juce_Application.h *********/
  18947. #endif
  18948. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18949. #endif
  18950. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18951. #endif
  18952. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18953. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  18954. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18955. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18956. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  18957. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  18958. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  18959. /**
  18960. Has a callback method that is triggered asynchronously.
  18961. This object allows an asynchronous callback function to be triggered, for
  18962. tasks such as coalescing multiple updates into a single callback later on.
  18963. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  18964. message thread calling handleAsyncUpdate() as soon as it can.
  18965. */
  18966. class JUCE_API AsyncUpdater
  18967. {
  18968. public:
  18969. /** Creates an AsyncUpdater object. */
  18970. AsyncUpdater() throw();
  18971. /** Destructor.
  18972. If there are any pending callbacks when the object is deleted, these are lost.
  18973. */
  18974. virtual ~AsyncUpdater();
  18975. /** Causes the callback to be triggered at a later time.
  18976. This method returns immediately, having made sure that a callback
  18977. to the handleAsyncUpdate() method will occur as soon as possible.
  18978. If an update callback is already pending but hasn't happened yet, calls
  18979. to this method will be ignored.
  18980. It's thread-safe to call this method from any number of threads without
  18981. needing to worry about locking.
  18982. */
  18983. void triggerAsyncUpdate() throw();
  18984. /** This will stop any pending updates from happening.
  18985. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  18986. callback happens, this will cancel the handleAsyncUpdate() callback.
  18987. */
  18988. void cancelPendingUpdate() throw();
  18989. /** If an update has been triggered and is pending, this will invoke it
  18990. synchronously.
  18991. Use this as a kind of "flush" operation - if an update is pending, the
  18992. handleAsyncUpdate() method will be called immediately; if no update is
  18993. pending, then nothing will be done.
  18994. */
  18995. void handleUpdateNowIfNeeded();
  18996. /** Called back to do whatever your class needs to do.
  18997. This method is called by the message thread at the next convenient time
  18998. after the triggerAsyncUpdate() method has been called.
  18999. */
  19000. virtual void handleAsyncUpdate() = 0;
  19001. private:
  19002. class AsyncUpdaterInternal : public MessageListener
  19003. {
  19004. public:
  19005. AsyncUpdaterInternal() throw() {}
  19006. ~AsyncUpdaterInternal() {}
  19007. void handleMessage (const Message&);
  19008. AsyncUpdater* owner;
  19009. private:
  19010. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  19011. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  19012. };
  19013. AsyncUpdaterInternal internalAsyncHandler;
  19014. bool asyncMessagePending;
  19015. };
  19016. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  19017. /********* End of inlined file: juce_AsyncUpdater.h *********/
  19018. /********* Start of inlined file: juce_Desktop.h *********/
  19019. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  19020. #define __JUCE_DESKTOP_JUCEHEADER__
  19021. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  19022. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19023. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19024. /**
  19025. Classes derived from this will be automatically deleted when the application exits.
  19026. After JUCEApplication::shutdown() has been called, any objects derived from
  19027. DeletedAtShutdown which are still in existence will be deleted in the reverse
  19028. order to that in which they were created.
  19029. So if you've got a singleton and don't want to have to explicitly delete it, just
  19030. inherit from this and it'll be taken care of.
  19031. */
  19032. class JUCE_API DeletedAtShutdown
  19033. {
  19034. protected:
  19035. /** Creates a DeletedAtShutdown object. */
  19036. DeletedAtShutdown() throw();
  19037. /** Destructor.
  19038. It's ok to delete these objects explicitly - it's only the ones left
  19039. dangling at the end that will be deleted automatically.
  19040. */
  19041. virtual ~DeletedAtShutdown();
  19042. public:
  19043. /** Deletes all extant objects.
  19044. This shouldn't be used by applications, as it's called automatically
  19045. in the shutdown code of the JUCEApplication class.
  19046. */
  19047. static void deleteAll();
  19048. private:
  19049. DeletedAtShutdown (const DeletedAtShutdown&);
  19050. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  19051. };
  19052. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19053. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  19054. /********* Start of inlined file: juce_Timer.h *********/
  19055. #ifndef __JUCE_TIMER_JUCEHEADER__
  19056. #define __JUCE_TIMER_JUCEHEADER__
  19057. class InternalTimerThread;
  19058. /**
  19059. Repeatedly calls a user-defined method at a specified time interval.
  19060. A Timer's timerCallback() method will be repeatedly called at a given
  19061. interval. Initially when a Timer object is created, they will do nothing
  19062. until the startTimer() method is called, then the message thread will
  19063. start calling it back until stopTimer() is called.
  19064. The time interval isn't guaranteed to be precise to any more than maybe
  19065. 10-20ms, and the intervals may end up being much longer than requested if the
  19066. system is busy. Because it's the message thread that is doing the callbacks,
  19067. any messages that take a significant amount of time to process will block
  19068. all the timers for that period.
  19069. If you need to have a single callback that is shared by multiple timers with
  19070. different frequencies, then the MultiTimer class allows you to do that - its
  19071. structure is very similar to the Timer class, but contains multiple timers
  19072. internally, each one identified by an ID number.
  19073. @see MultiTimer
  19074. */
  19075. class JUCE_API Timer
  19076. {
  19077. protected:
  19078. /** Creates a Timer.
  19079. When created, the timer is stopped, so use startTimer() to get it going.
  19080. */
  19081. Timer() throw();
  19082. /** Creates a copy of another timer.
  19083. Note that this timer won't be started, even if the one you're copying
  19084. is running.
  19085. */
  19086. Timer (const Timer& other) throw();
  19087. public:
  19088. /** Destructor. */
  19089. virtual ~Timer();
  19090. /** The user-defined callback routine that actually gets called periodically.
  19091. It's perfectly ok to call startTimer() or stopTimer() from within this
  19092. callback to change the subsequent intervals.
  19093. */
  19094. virtual void timerCallback() = 0;
  19095. /** Starts the timer and sets the length of interval required.
  19096. If the timer is already started, this will reset it, so the
  19097. time between calling this method and the next timer callback
  19098. will not be less than the interval length passed in.
  19099. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  19100. rounded up to 1)
  19101. */
  19102. void startTimer (const int intervalInMilliseconds) throw();
  19103. /** Stops the timer.
  19104. No more callbacks will be made after this method returns.
  19105. If this is called from a different thread, any callbacks that may
  19106. be currently executing may be allowed to finish before the method
  19107. returns.
  19108. */
  19109. void stopTimer() throw();
  19110. /** Checks if the timer has been started.
  19111. @returns true if the timer is running.
  19112. */
  19113. bool isTimerRunning() const throw() { return periodMs > 0; }
  19114. /** Returns the timer's interval.
  19115. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  19116. */
  19117. int getTimerInterval() const throw() { return periodMs; }
  19118. private:
  19119. friend class InternalTimerThread;
  19120. int countdownMs, periodMs;
  19121. Timer* previous;
  19122. Timer* next;
  19123. const Timer& operator= (const Timer&);
  19124. };
  19125. #endif // __JUCE_TIMER_JUCEHEADER__
  19126. /********* End of inlined file: juce_Timer.h *********/
  19127. /**
  19128. Classes can implement this interface and register themselves with the Desktop class
  19129. to receive callbacks when the currently focused component changes.
  19130. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  19131. */
  19132. class JUCE_API FocusChangeListener
  19133. {
  19134. public:
  19135. /** Destructor. */
  19136. virtual ~FocusChangeListener() {}
  19137. /** Callback to indicate that the currently focused component has changed. */
  19138. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  19139. };
  19140. /**
  19141. Describes and controls aspects of the computer's desktop.
  19142. */
  19143. class JUCE_API Desktop : private DeletedAtShutdown,
  19144. private Timer,
  19145. private AsyncUpdater
  19146. {
  19147. public:
  19148. /** There's only one dektop object, and this method will return it.
  19149. */
  19150. static Desktop& JUCE_CALLTYPE getInstance() throw();
  19151. /** Returns a list of the positions of all the monitors available.
  19152. The first rectangle in the list will be the main monitor area.
  19153. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19154. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19155. */
  19156. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  19157. /** Returns the position and size of the main monitor.
  19158. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19159. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19160. */
  19161. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  19162. /** Returns the position and size of the monitor which contains this co-ordinate.
  19163. If none of the monitors contains the point, this will just return the
  19164. main monitor.
  19165. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19166. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19167. */
  19168. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  19169. /** Returns the mouse position.
  19170. The co-ordinates are relative to the top-left of the main monitor.
  19171. */
  19172. static void getMousePosition (int& x, int& y) throw();
  19173. /** Makes the mouse pointer jump to a given location.
  19174. The co-ordinates are relative to the top-left of the main monitor.
  19175. */
  19176. static void setMousePosition (int x, int y) throw();
  19177. /** Returns the last position at which a mouse button was pressed.
  19178. */
  19179. static void getLastMouseDownPosition (int& x, int& y) throw();
  19180. /** Returns the number of times the mouse button has been clicked since the
  19181. app started.
  19182. Each mouse-down event increments this number by 1.
  19183. */
  19184. static int getMouseButtonClickCounter() throw();
  19185. /** This lets you prevent the screensaver from becoming active.
  19186. Handy if you're running some sort of presentation app where having a screensaver
  19187. appear would be annoying.
  19188. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  19189. won't enable a screensaver unless the user has actually set one up).
  19190. The disablement will only happen while the Juce application is the foreground
  19191. process - if another task is running in front of it, then the screensaver will
  19192. be unaffected.
  19193. @see isScreenSaverEnabled
  19194. */
  19195. static void setScreenSaverEnabled (const bool isEnabled) throw();
  19196. /** Returns true if the screensaver has not been turned off.
  19197. This will return the last value passed into setScreenSaverEnabled(). Note that
  19198. it won't tell you whether the user is actually using a screen saver, just
  19199. whether this app is deliberately preventing one from running.
  19200. @see setScreenSaverEnabled
  19201. */
  19202. static bool isScreenSaverEnabled() throw();
  19203. /** Registers a MouseListener that will receive all mouse events that occur on
  19204. any component.
  19205. @see removeGlobalMouseListener
  19206. */
  19207. void addGlobalMouseListener (MouseListener* const listener) throw();
  19208. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  19209. method.
  19210. @see addGlobalMouseListener
  19211. */
  19212. void removeGlobalMouseListener (MouseListener* const listener) throw();
  19213. /** Registers a MouseListener that will receive a callback whenever the focused
  19214. component changes.
  19215. */
  19216. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  19217. /** Unregisters a listener that was added with addFocusChangeListener(). */
  19218. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  19219. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  19220. The component must already be on the desktop for this method to work. It will
  19221. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  19222. etc will be hidden.
  19223. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  19224. the component that's currently being used will be resized back to the size
  19225. and position it was in before being put into this mode.
  19226. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  19227. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  19228. to hide as much on-screen paraphenalia as possible.
  19229. */
  19230. void setKioskModeComponent (Component* componentToUse,
  19231. const bool allowMenusAndBars = true);
  19232. /** Returns the component that is currently being used in kiosk-mode.
  19233. This is the component that was last set by setKioskModeComponent(). If none
  19234. has been set, this returns 0.
  19235. */
  19236. Component* getKioskModeComponent() const { return kioskModeComponent; }
  19237. /** Returns the number of components that are currently active as top-level
  19238. desktop windows.
  19239. @see getComponent, Component::addToDesktop
  19240. */
  19241. int getNumComponents() const throw();
  19242. /** Returns one of the top-level desktop window components.
  19243. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  19244. index is out-of-range.
  19245. @see getNumComponents, Component::addToDesktop
  19246. */
  19247. Component* getComponent (const int index) const throw();
  19248. /** Finds the component at a given screen location.
  19249. This will drill down into top-level windows to find the child component at
  19250. the given position.
  19251. Returns 0 if the co-ordinates are inside a non-Juce window.
  19252. */
  19253. Component* findComponentAt (const int screenX,
  19254. const int screenY) const;
  19255. juce_UseDebuggingNewOperator
  19256. /** Tells this object to refresh its idea of what the screen resolution is.
  19257. (Called internally by the native code).
  19258. */
  19259. void refreshMonitorSizes() throw();
  19260. /** True if the OS supports semitransparent windows */
  19261. static bool canUseSemiTransparentWindows() throw();
  19262. private:
  19263. friend class Component;
  19264. friend class ComponentPeer;
  19265. SortedSet <void*> mouseListeners, focusListeners;
  19266. VoidArray desktopComponents;
  19267. friend class DeletedAtShutdown;
  19268. friend class TopLevelWindowManager;
  19269. Desktop() throw();
  19270. ~Desktop() throw();
  19271. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  19272. int lastMouseX, lastMouseY;
  19273. Component* kioskModeComponent;
  19274. Rectangle kioskComponentOriginalBounds;
  19275. void timerCallback();
  19276. void sendMouseMove();
  19277. void resetTimer() throw();
  19278. int getNumDisplayMonitors() const throw();
  19279. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  19280. void addDesktopComponent (Component* const c) throw();
  19281. void removeDesktopComponent (Component* const c) throw();
  19282. void componentBroughtToFront (Component* const c) throw();
  19283. void triggerFocusCallback() throw();
  19284. void handleAsyncUpdate();
  19285. Desktop (const Desktop&);
  19286. const Desktop& operator= (const Desktop&);
  19287. };
  19288. #endif // __JUCE_DESKTOP_JUCEHEADER__
  19289. /********* End of inlined file: juce_Desktop.h *********/
  19290. class KeyPressMappingSet;
  19291. class ApplicationCommandManagerListener;
  19292. /**
  19293. One of these objects holds a list of all the commands your app can perform,
  19294. and despatches these commands when needed.
  19295. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  19296. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  19297. to invoke automatically, which means you don't have to handle the result of a menu
  19298. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  19299. which can choose which events they want to handle.
  19300. This architecture also allows for nested ApplicationCommandTargets, so that for example
  19301. you could have two different objects, one inside the other, both of which can respond to
  19302. a "delete" command. Depending on which one has focus, the command will be sent to the
  19303. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  19304. method.
  19305. To set up your app to use commands, you'll need to do the following:
  19306. - Create a global ApplicationCommandManager to hold the list of all possible
  19307. commands. (This will also manage a set of key-mappings for them).
  19308. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  19309. This allows the object to provide a list of commands that it can perform, and
  19310. to handle them.
  19311. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  19312. or ApplicationCommandManager::registerCommand().
  19313. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  19314. method to access the key-mapper object, which you will need to register as a key-listener
  19315. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  19316. about setting this up.
  19317. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  19318. cause these commands to be invoked automatically.
  19319. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  19320. When a command is invoked, the ApplicationCommandManager will try to choose the best
  19321. ApplicationCommandTarget to receive the specified command. To do this it will use the
  19322. current keyboard focus to see which component might be interested, and will search the
  19323. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  19324. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  19325. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  19326. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  19327. point if the command still hasn't been performed, it will be passed to the current
  19328. JUCEApplication object (which is itself an ApplicationCommandTarget).
  19329. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  19330. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  19331. the object yourself.
  19332. @see ApplicationCommandTarget, ApplicationCommandInfo
  19333. */
  19334. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  19335. private FocusChangeListener
  19336. {
  19337. public:
  19338. /** Creates an ApplicationCommandManager.
  19339. Once created, you'll need to register all your app's commands with it, using
  19340. ApplicationCommandManager::registerAllCommandsForTarget() or
  19341. ApplicationCommandManager::registerCommand().
  19342. */
  19343. ApplicationCommandManager();
  19344. /** Destructor.
  19345. Make sure that you don't delete this if pointers to it are still being used by
  19346. objects such as PopupMenus or Buttons.
  19347. */
  19348. virtual ~ApplicationCommandManager();
  19349. /** Clears the current list of all commands.
  19350. Note that this will also clear the contents of the KeyPressMappingSet.
  19351. */
  19352. void clearCommands();
  19353. /** Adds a command to the list of registered commands.
  19354. @see registerAllCommandsForTarget
  19355. */
  19356. void registerCommand (const ApplicationCommandInfo& newCommand);
  19357. /** Adds all the commands that this target publishes to the manager's list.
  19358. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  19359. to get details about all the commands that this target can do, and will call
  19360. registerCommand() to add each one to the manger's list.
  19361. @see registerCommand
  19362. */
  19363. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  19364. /** Removes the command with a specified ID.
  19365. Note that this will also remove any key mappings that are mapped to the command.
  19366. */
  19367. void removeCommand (const CommandID commandID);
  19368. /** This should be called to tell the manager that one of its registered commands may have changed
  19369. its active status.
  19370. Because the command manager only finds out whether a command is active or inactive by querying
  19371. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  19372. allows things like buttons to update their enablement, etc.
  19373. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  19374. for any registered listeners.
  19375. */
  19376. void commandStatusChanged();
  19377. /** Returns the number of commands that have been registered.
  19378. @see registerCommand
  19379. */
  19380. int getNumCommands() const throw() { return commands.size(); }
  19381. /** Returns the details about one of the registered commands.
  19382. The index is between 0 and (getNumCommands() - 1).
  19383. */
  19384. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  19385. /** Returns the details about a given command ID.
  19386. This will search the list of registered commands for one with the given command
  19387. ID number, and return its associated info. If no matching command is found, this
  19388. will return 0.
  19389. */
  19390. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  19391. /** Returns the name field for a command.
  19392. An empty string is returned if no command with this ID has been registered.
  19393. @see getDescriptionOfCommand
  19394. */
  19395. const String getNameOfCommand (const CommandID commandID) const throw();
  19396. /** Returns the description field for a command.
  19397. An empty string is returned if no command with this ID has been registered. If the
  19398. command has no description, this will return its short name field instead.
  19399. @see getNameOfCommand
  19400. */
  19401. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  19402. /** Returns the list of categories.
  19403. This will go through all registered commands, and return a list of all the distict
  19404. categoryName values from their ApplicationCommandInfo structure.
  19405. @see getCommandsInCategory()
  19406. */
  19407. const StringArray getCommandCategories() const throw();
  19408. /** Returns a list of all the command UIDs in a particular category.
  19409. @see getCommandCategories()
  19410. */
  19411. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  19412. /** Returns the manager's internal set of key mappings.
  19413. This object can be used to edit the keypresses. To actually link this object up
  19414. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  19415. class.
  19416. @see KeyPressMappingSet
  19417. */
  19418. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  19419. /** Invokes the given command directly, sending it to the default target.
  19420. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  19421. structure.
  19422. */
  19423. bool invokeDirectly (const CommandID commandID,
  19424. const bool asynchronously);
  19425. /** Sends a command to the default target.
  19426. This will choose a target using getFirstCommandTarget(), and send the specified command
  19427. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  19428. first target can't handle the command, it will be passed on to targets further down the
  19429. chain (see ApplicationCommandTarget::invoke() for more info).
  19430. @param invocationInfo this must be correctly filled-in, describing the context for
  19431. the invocation.
  19432. @param asynchronously if false, the command will be performed before this method returns.
  19433. If true, a message will be posted so that the command will be performed
  19434. later on the message thread, and this method will return immediately.
  19435. @see ApplicationCommandTarget::invoke
  19436. */
  19437. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  19438. const bool asynchronously);
  19439. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  19440. Whenever the manager needs to know which target a command should be sent to, it calls
  19441. this method to determine the first one to try.
  19442. By default, this method will return the target that was set by calling setFirstCommandTarget().
  19443. If no target is set, it will return the result of findDefaultComponentTarget().
  19444. If you need to make sure all commands go via your own custom target, then you can
  19445. either use setFirstCommandTarget() to specify a single target, or override this method
  19446. if you need more complex logic to choose one.
  19447. It may return 0 if no targets are available.
  19448. @see getTargetForCommand, invoke, invokeDirectly
  19449. */
  19450. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  19451. /** Sets a target to be returned by getFirstCommandTarget().
  19452. If this is set to 0, then getFirstCommandTarget() will by default return the
  19453. result of findDefaultComponentTarget().
  19454. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  19455. deleting the target object.
  19456. */
  19457. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  19458. /** Tries to find the best target to use to perform a given command.
  19459. This will call getFirstCommandTarget() to find the preferred target, and will
  19460. check whether that target can handle the given command. If it can't, then it'll use
  19461. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  19462. so on until no more are available.
  19463. If no targets are found that can perform the command, this method will return 0.
  19464. If a target is found, then it will get the target to fill-in the upToDateInfo
  19465. structure with the latest info about that command, so that the caller can see
  19466. whether the command is disabled, ticked, etc.
  19467. */
  19468. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  19469. ApplicationCommandInfo& upToDateInfo);
  19470. /** Registers a listener that will be called when various events occur. */
  19471. void addListener (ApplicationCommandManagerListener* const listener) throw();
  19472. /** Deregisters a previously-added listener. */
  19473. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  19474. /** Looks for a suitable command target based on which Components have the keyboard focus.
  19475. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  19476. but is exposed here in case it's useful.
  19477. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  19478. windows, etc., and using the findTargetForComponent() method.
  19479. */
  19480. static ApplicationCommandTarget* findDefaultComponentTarget();
  19481. /** Examines this component and all its parents in turn, looking for the first one
  19482. which is a ApplicationCommandTarget.
  19483. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  19484. that class.
  19485. */
  19486. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  19487. juce_UseDebuggingNewOperator
  19488. private:
  19489. OwnedArray <ApplicationCommandInfo> commands;
  19490. SortedSet <void*> listeners;
  19491. KeyPressMappingSet* keyMappings;
  19492. ApplicationCommandTarget* firstTarget;
  19493. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  19494. void handleAsyncUpdate();
  19495. void globalFocusChanged (Component*);
  19496. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  19497. // version of this method.
  19498. virtual short getFirstCommandTarget() { return 0; }
  19499. };
  19500. /**
  19501. A listener that receives callbacks from an ApplicationCommandManager when
  19502. commands are invoked or the command list is changed.
  19503. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  19504. */
  19505. class JUCE_API ApplicationCommandManagerListener
  19506. {
  19507. public:
  19508. /** Destructor. */
  19509. virtual ~ApplicationCommandManagerListener() {}
  19510. /** Called when an app command is about to be invoked. */
  19511. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  19512. /** Called when commands are registered or deregistered from the
  19513. command manager, or when commands are made active or inactive.
  19514. Note that if you're using this to watch for changes to whether a command is disabled,
  19515. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  19516. whenever the status of your command might have changed.
  19517. */
  19518. virtual void applicationCommandListChanged() = 0;
  19519. };
  19520. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19521. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  19522. #endif
  19523. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  19524. #endif
  19525. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19526. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  19527. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19528. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19529. /********* Start of inlined file: juce_PropertiesFile.h *********/
  19530. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  19531. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  19532. /** Wrapper on a file that stores a list of key/value data pairs.
  19533. Useful for storing application settings, etc. See the PropertySet class for
  19534. the interfaces that read and write values.
  19535. Not designed for very large amounts of data, as it keeps all the values in
  19536. memory and writes them out to disk lazily when they are changed.
  19537. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  19538. with it, and these will be signalled when a value changes.
  19539. @see PropertySet
  19540. */
  19541. class JUCE_API PropertiesFile : public PropertySet,
  19542. public ChangeBroadcaster,
  19543. private Timer
  19544. {
  19545. public:
  19546. enum FileFormatOptions
  19547. {
  19548. ignoreCaseOfKeyNames = 1,
  19549. storeAsBinary = 2,
  19550. storeAsCompressedBinary = 4,
  19551. storeAsXML = 8
  19552. };
  19553. /**
  19554. Creates a PropertiesFile object.
  19555. @param file the file to use
  19556. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  19557. is changed, the object will wait for this amount
  19558. of time and then save the file. If zero, the file
  19559. will be written to disk immediately on being changed
  19560. (which might be slow, as it'll re-write synchronously
  19561. each time a value-change method is called). If it is
  19562. less than zero, the file won't be saved until
  19563. save() or saveIfNeeded() are explicitly called.
  19564. @param options a combination of the flags in the FileFormatOptions
  19565. enum, which specify the type of file to save, and other
  19566. options.
  19567. */
  19568. PropertiesFile (const File& file,
  19569. const int millisecondsBeforeSaving,
  19570. const int options) throw();
  19571. /** Destructor.
  19572. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  19573. */
  19574. ~PropertiesFile();
  19575. /** This will flush all the values to disk if they've changed since the last
  19576. time they were saved.
  19577. Returns false if it fails to write to the file for some reason (maybe because
  19578. it's read-only or the directory doesn't exist or something).
  19579. @see save
  19580. */
  19581. bool saveIfNeeded();
  19582. /** This will force a write-to-disk of the current values, regardless of whether
  19583. anything has changed since the last save.
  19584. Returns false if it fails to write to the file for some reason (maybe because
  19585. it's read-only or the directory doesn't exist or something).
  19586. @see saveIfNeeded
  19587. */
  19588. bool save();
  19589. /** Returns true if the properties have been altered since the last time they were
  19590. saved.
  19591. */
  19592. bool needsToBeSaved() const throw();
  19593. /** Returns the file that's being used. */
  19594. const File getFile() const throw();
  19595. /** Handy utility to create a properties file in whatever the standard OS-specific
  19596. location is for these things.
  19597. This uses getDefaultAppSettingsFile() to decide what file to create, then
  19598. creates a PropertiesFile object with the specified properties. See
  19599. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  19600. what the parameters do.
  19601. @see getDefaultAppSettingsFile
  19602. */
  19603. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  19604. const String& fileNameSuffix,
  19605. const String& folderName,
  19606. const bool commonToAllUsers,
  19607. const int millisecondsBeforeSaving,
  19608. const int propertiesFileOptions);
  19609. /** Handy utility to choose a file in the standard OS-dependent location for application
  19610. settings files.
  19611. So on a Mac, this will return a file called:
  19612. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  19613. On Windows it'll return something like:
  19614. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  19615. On Linux it'll return
  19616. ~/.[folderName]/[applicationName].[fileNameSuffix]
  19617. If you pass an empty string as the folder name, it'll use the app name for this (or
  19618. omit the folder name on the Mac).
  19619. If commonToAllUsers is true, then this will return the same file for all users of the
  19620. computer, regardless of the current user. If it is false, the file will be specific to
  19621. only the current user. Use this to choose whether you're saving settings that are common
  19622. or user-specific.
  19623. */
  19624. static const File getDefaultAppSettingsFile (const String& applicationName,
  19625. const String& fileNameSuffix,
  19626. const String& folderName,
  19627. const bool commonToAllUsers);
  19628. juce_UseDebuggingNewOperator
  19629. protected:
  19630. virtual void propertyChanged();
  19631. private:
  19632. File file;
  19633. int timerInterval;
  19634. const int options;
  19635. bool needsWriting;
  19636. void timerCallback();
  19637. PropertiesFile (const PropertiesFile&);
  19638. const PropertiesFile& operator= (const PropertiesFile&);
  19639. };
  19640. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  19641. /********* End of inlined file: juce_PropertiesFile.h *********/
  19642. /**
  19643. Manages a collection of properties.
  19644. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  19645. as a singleton.
  19646. It holds two different PropertiesFile objects internally, one for user-specific
  19647. settings (stored in your user directory), and one for settings that are common to
  19648. all users (stored in a folder accessible to all users).
  19649. The class manages the creation of these files on-demand, allowing access via the
  19650. getUserSettings() and getCommonSettings() methods. It also has a few handy
  19651. methods like testWriteAccess() to check that the files can be saved.
  19652. If you're using one of these as a singleton, then your app's start-up code should
  19653. first of all call setStorageParameters() to tell it the parameters to use to create
  19654. the properties files.
  19655. @see PropertiesFile
  19656. */
  19657. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  19658. {
  19659. public:
  19660. /**
  19661. Creates an ApplicationProperties object.
  19662. Before using it, you must call setStorageParameters() to give it the info
  19663. it needs to create the property files.
  19664. */
  19665. ApplicationProperties() throw();
  19666. /** Destructor.
  19667. */
  19668. ~ApplicationProperties();
  19669. juce_DeclareSingleton (ApplicationProperties, false)
  19670. /** Gives the object the information it needs to create the appropriate properties files.
  19671. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  19672. info about how these parameters are used.
  19673. */
  19674. void setStorageParameters (const String& applicationName,
  19675. const String& fileNameSuffix,
  19676. const String& folderName,
  19677. const int millisecondsBeforeSaving,
  19678. const int propertiesFileOptions) throw();
  19679. /** Tests whether the files can be successfully written to, and can show
  19680. an error message if not.
  19681. Returns true if none of the tests fail.
  19682. @param testUserSettings if true, the user settings file will be tested
  19683. @param testCommonSettings if true, the common settings file will be tested
  19684. @param showWarningDialogOnFailure if true, the method will show a helpful error
  19685. message box if either of the tests fail
  19686. */
  19687. bool testWriteAccess (const bool testUserSettings,
  19688. const bool testCommonSettings,
  19689. const bool showWarningDialogOnFailure);
  19690. /** Returns the user settings file.
  19691. The first time this is called, it will create and load the properties file.
  19692. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  19693. the common settings are used as a second-chance place to look. This is done via the
  19694. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  19695. to the fallback for the user settings.
  19696. @see getCommonSettings
  19697. */
  19698. PropertiesFile* getUserSettings() throw();
  19699. /** Returns the common settings file.
  19700. The first time this is called, it will create and load the properties file.
  19701. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  19702. read-only (e.g. because the user doesn't have permission to write
  19703. to shared files), then this will return the user settings instead,
  19704. (like getUserSettings() would do). This is handy if you'd like to
  19705. write a value to the common settings, but if that's no possible,
  19706. then you'd rather write to the user settings than none at all.
  19707. If returnUserPropsIfReadOnly is false, this method will always return
  19708. the common settings, even if any changes to them can't be saved.
  19709. @see getUserSettings
  19710. */
  19711. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  19712. /** Saves both files if they need to be saved.
  19713. @see PropertiesFile::saveIfNeeded
  19714. */
  19715. bool saveIfNeeded();
  19716. /** Flushes and closes both files if they are open.
  19717. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  19718. and closes both files. They will then be re-opened the next time getUserSettings()
  19719. or getCommonSettings() is called.
  19720. */
  19721. void closeFiles();
  19722. juce_UseDebuggingNewOperator
  19723. private:
  19724. PropertiesFile* userProps;
  19725. PropertiesFile* commonProps;
  19726. String appName, fileSuffix, folderName;
  19727. int msBeforeSaving, options;
  19728. int commonSettingsAreReadOnly;
  19729. ApplicationProperties (const ApplicationProperties&);
  19730. const ApplicationProperties& operator= (const ApplicationProperties&);
  19731. void openFiles() throw();
  19732. };
  19733. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19734. /********* End of inlined file: juce_ApplicationProperties.h *********/
  19735. #endif
  19736. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  19737. /********* Start of inlined file: juce_MidiBuffer.h *********/
  19738. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  19739. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  19740. /********* Start of inlined file: juce_MidiMessage.h *********/
  19741. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19742. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  19743. /**
  19744. Encapsulates a MIDI message.
  19745. @see MidiMessageSequence, MidiOutput, MidiInput
  19746. */
  19747. class JUCE_API MidiMessage
  19748. {
  19749. public:
  19750. /** Creates a 3-byte short midi message.
  19751. @param byte1 message byte 1
  19752. @param byte2 message byte 2
  19753. @param byte3 message byte 3
  19754. @param timeStamp the time to give the midi message - this value doesn't
  19755. use any particular units, so will be application-specific
  19756. */
  19757. MidiMessage (const int byte1,
  19758. const int byte2,
  19759. const int byte3,
  19760. const double timeStamp = 0) throw();
  19761. /** Creates a 2-byte short midi message.
  19762. @param byte1 message byte 1
  19763. @param byte2 message byte 2
  19764. @param timeStamp the time to give the midi message - this value doesn't
  19765. use any particular units, so will be application-specific
  19766. */
  19767. MidiMessage (const int byte1,
  19768. const int byte2,
  19769. const double timeStamp = 0) throw();
  19770. /** Creates a 1-byte short midi message.
  19771. @param byte1 message byte 1
  19772. @param timeStamp the time to give the midi message - this value doesn't
  19773. use any particular units, so will be application-specific
  19774. */
  19775. MidiMessage (const int byte1,
  19776. const double timeStamp = 0) throw();
  19777. /** Creates a midi message from a block of data. */
  19778. MidiMessage (const uint8* const data,
  19779. const int dataSize,
  19780. const double timeStamp = 0) throw();
  19781. /** Reads the next midi message from some data.
  19782. This will read as many bytes from a data stream as it needs to make a
  19783. complete message, and will return the number of bytes it used. This lets
  19784. you read a sequence of midi messages from a file or stream.
  19785. @param data the data to read from
  19786. @param size the maximum number of bytes it's allowed to read
  19787. @param numBytesUsed returns the number of bytes that were actually needed
  19788. @param lastStatusByte in a sequence of midi messages, the initial byte
  19789. can be dropped from a message if it's the same as the
  19790. first byte of the previous message, so this lets you
  19791. supply the byte to use if the first byte of the message
  19792. has in fact been dropped.
  19793. @param timeStamp the time to give the midi message - this value doesn't
  19794. use any particular units, so will be application-specific
  19795. */
  19796. MidiMessage (const uint8* data,
  19797. int size,
  19798. int& numBytesUsed,
  19799. uint8 lastStatusByte,
  19800. double timeStamp = 0) throw();
  19801. /** Creates a copy of another midi message. */
  19802. MidiMessage (const MidiMessage& other) throw();
  19803. /** Creates a copy of another midi message, with a different timestamp. */
  19804. MidiMessage (const MidiMessage& other,
  19805. const double newTimeStamp) throw();
  19806. /** Destructor. */
  19807. ~MidiMessage() throw();
  19808. /** Copies this message from another one. */
  19809. const MidiMessage& operator= (const MidiMessage& other) throw();
  19810. /** Returns a pointer to the raw midi data.
  19811. @see getRawDataSize
  19812. */
  19813. uint8* getRawData() const throw() { return data; }
  19814. /** Returns the number of bytes of data in the message.
  19815. @see getRawData
  19816. */
  19817. int getRawDataSize() const throw() { return size; }
  19818. /** Returns the timestamp associated with this message.
  19819. The exact meaning of this time and its units will vary, as messages are used in
  19820. a variety of different contexts.
  19821. If you're getting the message from a midi file, this could be a time in seconds, or
  19822. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  19823. If the message is being used in a MidiBuffer, it might indicate the number of
  19824. audio samples from the start of the buffer.
  19825. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  19826. for details of the way that it initialises this value.
  19827. @see setTimeStamp, addToTimeStamp
  19828. */
  19829. double getTimeStamp() const throw() { return timeStamp; }
  19830. /** Changes the message's associated timestamp.
  19831. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  19832. @see addToTimeStamp, getTimeStamp
  19833. */
  19834. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  19835. /** Adds a value to the message's timestamp.
  19836. The units for the timestamp will be application-specific.
  19837. */
  19838. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  19839. /** Returns the midi channel associated with the message.
  19840. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  19841. if it's a sysex)
  19842. @see isForChannel, setChannel
  19843. */
  19844. int getChannel() const throw();
  19845. /** Returns true if the message applies to the given midi channel.
  19846. @param channelNumber the channel number to look for, in the range 1 to 16
  19847. @see getChannel, setChannel
  19848. */
  19849. bool isForChannel (const int channelNumber) const throw();
  19850. /** Changes the message's midi channel.
  19851. This won't do anything for non-channel messages like sysexes.
  19852. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  19853. */
  19854. void setChannel (const int newChannelNumber) throw();
  19855. /** Returns true if this is a system-exclusive message.
  19856. */
  19857. bool isSysEx() const throw();
  19858. /** Returns a pointer to the sysex data inside the message.
  19859. If this event isn't a sysex event, it'll return 0.
  19860. @see getSysExDataSize
  19861. */
  19862. const uint8* getSysExData() const throw();
  19863. /** Returns the size of the sysex data.
  19864. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  19865. @see getSysExData
  19866. */
  19867. int getSysExDataSize() const throw();
  19868. /** Returns true if this message is a 'key-down' event.
  19869. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  19870. velocity 0, it will still be considered to be a note-on and the
  19871. method will return true. If returnTrueForVelocity0 is false, then
  19872. if this is a note-on event with velocity 0, it'll be regarded as
  19873. a note-off, and the method will return false
  19874. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  19875. */
  19876. bool isNoteOn (const bool returnTrueForVelocity0 = false) const throw();
  19877. /** Creates a key-down message (using a floating-point velocity).
  19878. @param channel the midi channel, in the range 1 to 16
  19879. @param noteNumber the key number, 0 to 127
  19880. @param velocity in the range 0 to 1.0
  19881. @see isNoteOn
  19882. */
  19883. static const MidiMessage noteOn (const int channel,
  19884. const int noteNumber,
  19885. const float velocity) throw();
  19886. /** Creates a key-down message (using an integer velocity).
  19887. @param channel the midi channel, in the range 1 to 16
  19888. @param noteNumber the key number, 0 to 127
  19889. @param velocity in the range 0 to 127
  19890. @see isNoteOn
  19891. */
  19892. static const MidiMessage noteOn (const int channel,
  19893. const int noteNumber,
  19894. const uint8 velocity) throw();
  19895. /** Returns true if this message is a 'key-up' event.
  19896. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  19897. for a note-on event with a velocity of 0.
  19898. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  19899. */
  19900. bool isNoteOff (const bool returnTrueForNoteOnVelocity0 = true) const throw();
  19901. /** Creates a key-up message.
  19902. @param channel the midi channel, in the range 1 to 16
  19903. @param noteNumber the key number, 0 to 127
  19904. @see isNoteOff
  19905. */
  19906. static const MidiMessage noteOff (const int channel,
  19907. const int noteNumber) throw();
  19908. /** Returns true if this message is a 'key-down' or 'key-up' event.
  19909. @see isNoteOn, isNoteOff
  19910. */
  19911. bool isNoteOnOrOff() const throw();
  19912. /** Returns the midi note number for note-on and note-off messages.
  19913. If the message isn't a note-on or off, the value returned will be
  19914. meaningless.
  19915. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  19916. */
  19917. int getNoteNumber() const throw();
  19918. /** Changes the midi note number of a note-on or note-off message.
  19919. If the message isn't a note on or off, this will do nothing.
  19920. */
  19921. void setNoteNumber (const int newNoteNumber) throw();
  19922. /** Returns the velocity of a note-on or note-off message.
  19923. The value returned will be in the range 0 to 127.
  19924. If the message isn't a note-on or off event, it will return 0.
  19925. @see getFloatVelocity
  19926. */
  19927. uint8 getVelocity() const throw();
  19928. /** Returns the velocity of a note-on or note-off message.
  19929. The value returned will be in the range 0 to 1.0
  19930. If the message isn't a note-on or off event, it will return 0.
  19931. @see getVelocity, setVelocity
  19932. */
  19933. float getFloatVelocity() const throw();
  19934. /** Changes the velocity of a note-on or note-off message.
  19935. If the message isn't a note on or off, this will do nothing.
  19936. @param newVelocity the new velocity, in the range 0 to 1.0
  19937. @see getFloatVelocity, multiplyVelocity
  19938. */
  19939. void setVelocity (const float newVelocity) throw();
  19940. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  19941. If the message isn't a note on or off, this will do nothing.
  19942. @param scaleFactor the value by which to multiply the velocity
  19943. @see setVelocity
  19944. */
  19945. void multiplyVelocity (const float scaleFactor) throw();
  19946. /** Returns true if the message is a program (patch) change message.
  19947. @see getProgramChangeNumber, getGMInstrumentName
  19948. */
  19949. bool isProgramChange() const throw();
  19950. /** Returns the new program number of a program change message.
  19951. If the message isn't a program change, the value returned will be
  19952. nonsense.
  19953. @see isProgramChange, getGMInstrumentName
  19954. */
  19955. int getProgramChangeNumber() const throw();
  19956. /** Creates a program-change message.
  19957. @param channel the midi channel, in the range 1 to 16
  19958. @param programNumber the midi program number, 0 to 127
  19959. @see isProgramChange, getGMInstrumentName
  19960. */
  19961. static const MidiMessage programChange (const int channel,
  19962. const int programNumber) throw();
  19963. /** Returns true if the message is a pitch-wheel move.
  19964. @see getPitchWheelValue, pitchWheel
  19965. */
  19966. bool isPitchWheel() const throw();
  19967. /** Returns the pitch wheel position from a pitch-wheel move message.
  19968. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  19969. If called for messages which aren't pitch wheel events, the number returned will be
  19970. nonsense.
  19971. @see isPitchWheel
  19972. */
  19973. int getPitchWheelValue() const throw();
  19974. /** Creates a pitch-wheel move message.
  19975. @param channel the midi channel, in the range 1 to 16
  19976. @param position the wheel position, in the range 0 to 16383
  19977. @see isPitchWheel
  19978. */
  19979. static const MidiMessage pitchWheel (const int channel,
  19980. const int position) throw();
  19981. /** Returns true if the message is an aftertouch event.
  19982. For aftertouch events, use the getNoteNumber() method to find out the key
  19983. that it applies to, and getAftertouchValue() to find out the amount. Use
  19984. getChannel() to find out the channel.
  19985. @see getAftertouchValue, getNoteNumber
  19986. */
  19987. bool isAftertouch() const throw();
  19988. /** Returns the amount of aftertouch from an aftertouch messages.
  19989. The value returned is in the range 0 to 127, and will be nonsense for messages
  19990. other than aftertouch messages.
  19991. @see isAftertouch
  19992. */
  19993. int getAfterTouchValue() const throw();
  19994. /** Creates an aftertouch message.
  19995. @param channel the midi channel, in the range 1 to 16
  19996. @param noteNumber the key number, 0 to 127
  19997. @param aftertouchAmount the amount of aftertouch, 0 to 127
  19998. @see isAftertouch
  19999. */
  20000. static const MidiMessage aftertouchChange (const int channel,
  20001. const int noteNumber,
  20002. const int aftertouchAmount) throw();
  20003. /** Returns true if the message is a channel-pressure change event.
  20004. This is like aftertouch, but common to the whole channel rather than a specific
  20005. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  20006. to find out the channel.
  20007. @see channelPressureChange
  20008. */
  20009. bool isChannelPressure() const throw();
  20010. /** Returns the pressure from a channel pressure change message.
  20011. @returns the pressure, in the range 0 to 127
  20012. @see isChannelPressure, channelPressureChange
  20013. */
  20014. int getChannelPressureValue() const throw();
  20015. /** Creates a channel-pressure change event.
  20016. @param channel the midi channel: 1 to 16
  20017. @param pressure the pressure, 0 to 127
  20018. @see isChannelPressure
  20019. */
  20020. static const MidiMessage channelPressureChange (const int channel,
  20021. const int pressure) throw();
  20022. /** Returns true if this is a midi controller message.
  20023. @see getControllerNumber, getControllerValue, controllerEvent
  20024. */
  20025. bool isController() const throw();
  20026. /** Returns the controller number of a controller message.
  20027. The name of the controller can be looked up using the getControllerName() method.
  20028. Note that the value returned is invalid for messages that aren't controller changes.
  20029. @see isController, getControllerName, getControllerValue
  20030. */
  20031. int getControllerNumber() const throw();
  20032. /** Returns the controller value from a controller message.
  20033. A value 0 to 127 is returned to indicate the new controller position.
  20034. Note that the value returned is invalid for messages that aren't controller changes.
  20035. @see isController, getControllerNumber
  20036. */
  20037. int getControllerValue() const throw();
  20038. /** Creates a controller message.
  20039. @param channel the midi channel, in the range 1 to 16
  20040. @param controllerType the type of controller
  20041. @param value the controller value
  20042. @see isController
  20043. */
  20044. static const MidiMessage controllerEvent (const int channel,
  20045. const int controllerType,
  20046. const int value) throw();
  20047. /** Checks whether this message is an all-notes-off message.
  20048. @see allNotesOff
  20049. */
  20050. bool isAllNotesOff() const throw();
  20051. /** Checks whether this message is an all-sound-off message.
  20052. @see allSoundOff
  20053. */
  20054. bool isAllSoundOff() const throw();
  20055. /** Creates an all-notes-off message.
  20056. @param channel the midi channel, in the range 1 to 16
  20057. @see isAllNotesOff
  20058. */
  20059. static const MidiMessage allNotesOff (const int channel) throw();
  20060. /** Creates an all-sound-off message.
  20061. @param channel the midi channel, in the range 1 to 16
  20062. @see isAllSoundOff
  20063. */
  20064. static const MidiMessage allSoundOff (const int channel) throw();
  20065. /** Creates an all-controllers-off message.
  20066. @param channel the midi channel, in the range 1 to 16
  20067. */
  20068. static const MidiMessage allControllersOff (const int channel) throw();
  20069. /** Returns true if this event is a meta-event.
  20070. Meta-events are things like tempo changes, track names, etc.
  20071. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  20072. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  20073. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  20074. */
  20075. bool isMetaEvent() const throw();
  20076. /** Returns a meta-event's type number.
  20077. If the message isn't a meta-event, this will return -1.
  20078. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  20079. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  20080. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  20081. */
  20082. int getMetaEventType() const throw();
  20083. /** Returns a pointer to the data in a meta-event.
  20084. @see isMetaEvent, getMetaEventLength
  20085. */
  20086. const uint8* getMetaEventData() const throw();
  20087. /** Returns the length of the data for a meta-event.
  20088. @see isMetaEvent, getMetaEventData
  20089. */
  20090. int getMetaEventLength() const throw();
  20091. /** Returns true if this is a 'track' meta-event. */
  20092. bool isTrackMetaEvent() const throw();
  20093. /** Returns true if this is an 'end-of-track' meta-event. */
  20094. bool isEndOfTrackMetaEvent() const throw();
  20095. /** Creates an end-of-track meta-event.
  20096. @see isEndOfTrackMetaEvent
  20097. */
  20098. static const MidiMessage endOfTrack() throw();
  20099. /** Returns true if this is an 'track name' meta-event.
  20100. You can use the getTextFromTextMetaEvent() method to get the track's name.
  20101. */
  20102. bool isTrackNameEvent() const throw();
  20103. /** Returns true if this is a 'text' meta-event.
  20104. @see getTextFromTextMetaEvent
  20105. */
  20106. bool isTextMetaEvent() const throw();
  20107. /** Returns the text from a text meta-event.
  20108. @see isTextMetaEvent
  20109. */
  20110. const String getTextFromTextMetaEvent() const throw();
  20111. /** Returns true if this is a 'tempo' meta-event.
  20112. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  20113. */
  20114. bool isTempoMetaEvent() const throw();
  20115. /** Returns the tick length from a tempo meta-event.
  20116. @param timeFormat the 16-bit time format value from the midi file's header.
  20117. @returns the tick length (in seconds).
  20118. @see isTempoMetaEvent
  20119. */
  20120. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  20121. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  20122. @see isTempoMetaEvent, getTempoMetaEventTickLength
  20123. */
  20124. double getTempoSecondsPerQuarterNote() const throw();
  20125. /** Creates a tempo meta-event.
  20126. @see isTempoMetaEvent
  20127. */
  20128. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  20129. /** Returns true if this is a 'time-signature' meta-event.
  20130. @see getTimeSignatureInfo
  20131. */
  20132. bool isTimeSignatureMetaEvent() const throw();
  20133. /** Returns the time-signature values from a time-signature meta-event.
  20134. @see isTimeSignatureMetaEvent
  20135. */
  20136. void getTimeSignatureInfo (int& numerator,
  20137. int& denominator) const throw();
  20138. /** Creates a time-signature meta-event.
  20139. @see isTimeSignatureMetaEvent
  20140. */
  20141. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  20142. const int denominator) throw();
  20143. /** Returns true if this is a 'key-signature' meta-event.
  20144. @see getKeySignatureNumberOfSharpsOrFlats
  20145. */
  20146. bool isKeySignatureMetaEvent() const throw();
  20147. /** Returns the key from a key-signature meta-event.
  20148. @see isKeySignatureMetaEvent
  20149. */
  20150. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  20151. /** Returns true if this is a 'channel' meta-event.
  20152. A channel meta-event specifies the midi channel that should be used
  20153. for subsequent meta-events.
  20154. @see getMidiChannelMetaEventChannel
  20155. */
  20156. bool isMidiChannelMetaEvent() const throw();
  20157. /** Returns the channel number from a channel meta-event.
  20158. @returns the channel, in the range 1 to 16.
  20159. @see isMidiChannelMetaEvent
  20160. */
  20161. int getMidiChannelMetaEventChannel() const throw();
  20162. /** Creates a midi channel meta-event.
  20163. @param channel the midi channel, in the range 1 to 16
  20164. @see isMidiChannelMetaEvent
  20165. */
  20166. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  20167. /** Returns true if this is an active-sense message. */
  20168. bool isActiveSense() const throw();
  20169. /** Returns true if this is a midi start event.
  20170. @see midiStart
  20171. */
  20172. bool isMidiStart() const throw();
  20173. /** Creates a midi start event. */
  20174. static const MidiMessage midiStart() throw();
  20175. /** Returns true if this is a midi continue event.
  20176. @see midiContinue
  20177. */
  20178. bool isMidiContinue() const throw();
  20179. /** Creates a midi continue event. */
  20180. static const MidiMessage midiContinue() throw();
  20181. /** Returns true if this is a midi stop event.
  20182. @see midiStop
  20183. */
  20184. bool isMidiStop() const throw();
  20185. /** Creates a midi stop event. */
  20186. static const MidiMessage midiStop() throw();
  20187. /** Returns true if this is a midi clock event.
  20188. @see midiClock, songPositionPointer
  20189. */
  20190. bool isMidiClock() const throw();
  20191. /** Creates a midi clock event. */
  20192. static const MidiMessage midiClock() throw();
  20193. /** Returns true if this is a song-position-pointer message.
  20194. @see getSongPositionPointerMidiBeat, songPositionPointer
  20195. */
  20196. bool isSongPositionPointer() const throw();
  20197. /** Returns the midi beat-number of a song-position-pointer message.
  20198. @see isSongPositionPointer, songPositionPointer
  20199. */
  20200. int getSongPositionPointerMidiBeat() const throw();
  20201. /** Creates a song-position-pointer message.
  20202. The position is a number of midi beats from the start of the song, where 1 midi
  20203. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  20204. are 4 midi beats in a quarter-note.
  20205. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  20206. */
  20207. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  20208. /** Returns true if this is a quarter-frame midi timecode message.
  20209. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  20210. */
  20211. bool isQuarterFrame() const throw();
  20212. /** Returns the sequence number of a quarter-frame midi timecode message.
  20213. This will be a value between 0 and 7.
  20214. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  20215. */
  20216. int getQuarterFrameSequenceNumber() const throw();
  20217. /** Returns the value from a quarter-frame message.
  20218. This will be the lower nybble of the message's data-byte, a value
  20219. between 0 and 15
  20220. */
  20221. int getQuarterFrameValue() const throw();
  20222. /** Creates a quarter-frame MTC message.
  20223. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  20224. @param value a value 0 to 15 for the lower nybble of the message's data byte
  20225. */
  20226. static const MidiMessage quarterFrame (const int sequenceNumber,
  20227. const int value) throw();
  20228. /** SMPTE timecode types.
  20229. Used by the getFullFrameParameters() and fullFrame() methods.
  20230. */
  20231. enum SmpteTimecodeType
  20232. {
  20233. fps24 = 0,
  20234. fps25 = 1,
  20235. fps30drop = 2,
  20236. fps30 = 3
  20237. };
  20238. /** Returns true if this is a full-frame midi timecode message.
  20239. */
  20240. bool isFullFrame() const throw();
  20241. /** Extracts the timecode information from a full-frame midi timecode message.
  20242. You should only call this on messages where you've used isFullFrame() to
  20243. check that they're the right kind.
  20244. */
  20245. void getFullFrameParameters (int& hours,
  20246. int& minutes,
  20247. int& seconds,
  20248. int& frames,
  20249. SmpteTimecodeType& timecodeType) const throw();
  20250. /** Creates a full-frame MTC message.
  20251. */
  20252. static const MidiMessage fullFrame (const int hours,
  20253. const int minutes,
  20254. const int seconds,
  20255. const int frames,
  20256. SmpteTimecodeType timecodeType);
  20257. /** Types of MMC command.
  20258. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  20259. */
  20260. enum MidiMachineControlCommand
  20261. {
  20262. mmc_stop = 1,
  20263. mmc_play = 2,
  20264. mmc_deferredplay = 3,
  20265. mmc_fastforward = 4,
  20266. mmc_rewind = 5,
  20267. mmc_recordStart = 6,
  20268. mmc_recordStop = 7,
  20269. mmc_pause = 9
  20270. };
  20271. /** Checks whether this is an MMC message.
  20272. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  20273. */
  20274. bool isMidiMachineControlMessage() const throw();
  20275. /** For an MMC message, this returns its type.
  20276. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  20277. calling this method.
  20278. */
  20279. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  20280. /** Creates an MMC message.
  20281. */
  20282. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  20283. /** Checks whether this is an MMC "goto" message.
  20284. If it is, the parameters passed-in are set to the time that the message contains.
  20285. @see midiMachineControlGoto
  20286. */
  20287. bool isMidiMachineControlGoto (int& hours,
  20288. int& minutes,
  20289. int& seconds,
  20290. int& frames) const throw();
  20291. /** Creates an MMC "goto" message.
  20292. This messages tells the device to go to a specific frame.
  20293. @see isMidiMachineControlGoto
  20294. */
  20295. static const MidiMessage midiMachineControlGoto (int hours,
  20296. int minutes,
  20297. int seconds,
  20298. int frames);
  20299. /** Creates a master-volume change message.
  20300. @param volume the volume, 0 to 1.0
  20301. */
  20302. static const MidiMessage masterVolume (const float volume) throw();
  20303. /** Creates a system-exclusive message.
  20304. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  20305. */
  20306. static const MidiMessage createSysExMessage (const uint8* sysexData,
  20307. const int dataSize) throw();
  20308. /** Reads a midi variable-length integer.
  20309. @param data the data to read the number from
  20310. @param numBytesUsed on return, this will be set to the number of bytes that were read
  20311. */
  20312. static int readVariableLengthVal (const uint8* data,
  20313. int& numBytesUsed) throw();
  20314. /** Based on the first byte of a short midi message, this uses a lookup table
  20315. to return the message length (either 1, 2, or 3 bytes).
  20316. The value passed in must be 0x80 or higher.
  20317. */
  20318. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  20319. /** Returns the name of a midi note number.
  20320. E.g "C", "D#", etc.
  20321. @param noteNumber the midi note number, 0 to 127
  20322. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  20323. they'll be flattened, e.g. "Db"
  20324. @param includeOctaveNumber if true, the octave number will be appended to the string,
  20325. e.g. "C#4"
  20326. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  20327. number that will be used for middle C's octave
  20328. @see getMidiNoteInHertz
  20329. */
  20330. static const String getMidiNoteName (int noteNumber,
  20331. bool useSharps,
  20332. bool includeOctaveNumber,
  20333. int octaveNumForMiddleC) throw();
  20334. /** Returns the frequency of a midi note number.
  20335. @see getMidiNoteName
  20336. */
  20337. static const double getMidiNoteInHertz (int noteNumber) throw();
  20338. /** Returns the standard name of a GM instrument.
  20339. @param midiInstrumentNumber the program number 0 to 127
  20340. @see getProgramChangeNumber
  20341. */
  20342. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  20343. /** Returns the name of a bank of GM instruments.
  20344. @param midiBankNumber the bank, 0 to 15
  20345. */
  20346. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  20347. /** Returns the standard name of a channel 10 percussion sound.
  20348. @param midiNoteNumber the key number, 35 to 81
  20349. */
  20350. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  20351. /** Returns the name of a controller type number.
  20352. @see getControllerNumber
  20353. */
  20354. static const String getControllerName (int controllerNumber) throw();
  20355. juce_UseDebuggingNewOperator
  20356. private:
  20357. double timeStamp;
  20358. uint8* data;
  20359. int message, size;
  20360. };
  20361. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  20362. /********* End of inlined file: juce_MidiMessage.h *********/
  20363. /**
  20364. Holds a sequence of time-stamped midi events.
  20365. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  20366. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  20367. @see MidiMessage
  20368. */
  20369. class JUCE_API MidiBuffer
  20370. {
  20371. public:
  20372. /** Creates an empty MidiBuffer. */
  20373. MidiBuffer() throw();
  20374. /** Creates a MidiBuffer containing a single midi message. */
  20375. MidiBuffer (const MidiMessage& message) throw();
  20376. /** Creates a copy of another MidiBuffer. */
  20377. MidiBuffer (const MidiBuffer& other) throw();
  20378. /** Makes a copy of another MidiBuffer. */
  20379. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  20380. /** Destructor */
  20381. ~MidiBuffer() throw();
  20382. /** Removes all events from the buffer. */
  20383. void clear() throw();
  20384. /** Removes all events between two times from the buffer.
  20385. All events for which (start <= event position < start + numSamples) will
  20386. be removed.
  20387. */
  20388. void clear (const int start,
  20389. const int numSamples) throw();
  20390. /** Returns true if the buffer is empty.
  20391. To actually retrieve the events, use a MidiBuffer::Iterator object
  20392. */
  20393. bool isEmpty() const throw();
  20394. /** Counts the number of events in the buffer.
  20395. This is actually quite a slow operation, as it has to iterate through all
  20396. the events, so you might prefer to call isEmpty() if that's all you need
  20397. to know.
  20398. */
  20399. int getNumEvents() const throw();
  20400. /** Adds an event to the buffer.
  20401. The sample number will be used to determine the position of the event in
  20402. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  20403. ignored.
  20404. If an event is added whose sample position is the same as one or more events
  20405. already in the buffer, the new event will be placed after the existing ones.
  20406. To retrieve events, use a MidiBuffer::Iterator object
  20407. */
  20408. void addEvent (const MidiMessage& midiMessage,
  20409. const int sampleNumber) throw();
  20410. /** Adds an event to the buffer from raw midi data.
  20411. The sample number will be used to determine the position of the event in
  20412. the buffer, which is always kept sorted.
  20413. If an event is added whose sample position is the same as one or more events
  20414. already in the buffer, the new event will be placed after the existing ones.
  20415. The event data will be inspected to calculate the number of bytes in length that
  20416. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  20417. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  20418. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  20419. add an event at all.
  20420. To retrieve events, use a MidiBuffer::Iterator object
  20421. */
  20422. void addEvent (const uint8* const rawMidiData,
  20423. const int maxBytesOfMidiData,
  20424. const int sampleNumber) throw();
  20425. /** Adds some events from another buffer to this one.
  20426. @param otherBuffer the buffer containing the events you want to add
  20427. @param startSample the lowest sample number in the source buffer for which
  20428. events should be added. Any source events whose timestamp is
  20429. less than this will be ignored
  20430. @param numSamples the valid range of samples from the source buffer for which
  20431. events should be added - i.e. events in the source buffer whose
  20432. timestamp is greater than or equal to (startSample + numSamples)
  20433. will be ignored. If this value is less than 0, all events after
  20434. startSample will be taken.
  20435. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  20436. that are added to this buffer
  20437. */
  20438. void addEvents (const MidiBuffer& otherBuffer,
  20439. const int startSample,
  20440. const int numSamples,
  20441. const int sampleDeltaToAdd) throw();
  20442. /** Returns the sample number of the first event in the buffer.
  20443. If the buffer's empty, this will just return 0.
  20444. */
  20445. int getFirstEventTime() const throw();
  20446. /** Returns the sample number of the last event in the buffer.
  20447. If the buffer's empty, this will just return 0.
  20448. */
  20449. int getLastEventTime() const throw();
  20450. /** Exchanges the contents of this buffer with another one.
  20451. This is a quick operation, because no memory allocating or copying is done, it
  20452. just swaps the internal state of the two buffers.
  20453. */
  20454. void swap (MidiBuffer& other);
  20455. /**
  20456. Used to iterate through the events in a MidiBuffer.
  20457. Note that altering the buffer while an iterator is using it isn't a
  20458. safe operation.
  20459. @see MidiBuffer
  20460. */
  20461. class Iterator
  20462. {
  20463. public:
  20464. /** Creates an Iterator for this MidiBuffer. */
  20465. Iterator (const MidiBuffer& buffer) throw();
  20466. /** Destructor. */
  20467. ~Iterator() throw();
  20468. /** Repositions the iterator so that the next event retrieved will be the first
  20469. one whose sample position is at greater than or equal to the given position.
  20470. */
  20471. void setNextSamplePosition (const int samplePosition) throw();
  20472. /** Retrieves a copy of the next event from the buffer.
  20473. @param result on return, this will be the message (the MidiMessage's timestamp
  20474. is not set)
  20475. @param samplePosition on return, this will be the position of the event
  20476. @returns true if an event was found, or false if the iterator has reached
  20477. the end of the buffer
  20478. */
  20479. bool getNextEvent (MidiMessage& result,
  20480. int& samplePosition) throw();
  20481. /** Retrieves the next event from the buffer.
  20482. @param midiData on return, this pointer will be set to a block of data containing
  20483. the midi message. Note that to make it fast, this is a pointer
  20484. directly into the MidiBuffer's internal data, so is only valid
  20485. temporarily until the MidiBuffer is altered.
  20486. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  20487. midi message
  20488. @param samplePosition on return, this will be the position of the event
  20489. @returns true if an event was found, or false if the iterator has reached
  20490. the end of the buffer
  20491. */
  20492. bool getNextEvent (const uint8* &midiData,
  20493. int& numBytesOfMidiData,
  20494. int& samplePosition) throw();
  20495. juce_UseDebuggingNewOperator
  20496. private:
  20497. const MidiBuffer& buffer;
  20498. const uint8* data;
  20499. Iterator (const Iterator&);
  20500. const Iterator& operator= (const Iterator&);
  20501. };
  20502. juce_UseDebuggingNewOperator
  20503. private:
  20504. friend class MidiBuffer::Iterator;
  20505. ArrayAllocationBase <uint8> data;
  20506. int bytesUsed;
  20507. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  20508. };
  20509. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  20510. /********* End of inlined file: juce_MidiBuffer.h *********/
  20511. #endif
  20512. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  20513. /********* Start of inlined file: juce_MidiFile.h *********/
  20514. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  20515. #define __JUCE_MIDIFILE_JUCEHEADER__
  20516. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  20517. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20518. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20519. /**
  20520. A sequence of timestamped midi messages.
  20521. This allows the sequence to be manipulated, and also to be read from and
  20522. written to a standard midi file.
  20523. @see MidiMessage, MidiFile
  20524. */
  20525. class JUCE_API MidiMessageSequence
  20526. {
  20527. public:
  20528. /** Creates an empty midi sequence object. */
  20529. MidiMessageSequence();
  20530. /** Creates a copy of another sequence. */
  20531. MidiMessageSequence (const MidiMessageSequence& other);
  20532. /** Replaces this sequence with another one. */
  20533. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  20534. /** Destructor. */
  20535. ~MidiMessageSequence();
  20536. /** Structure used to hold midi events in the sequence.
  20537. These structures act as 'handles' on the events as they are moved about in
  20538. the list, and make it quick to find the matching note-offs for note-on events.
  20539. @see MidiMessageSequence::getEventPointer
  20540. */
  20541. class MidiEventHolder
  20542. {
  20543. public:
  20544. /** Destructor. */
  20545. ~MidiEventHolder();
  20546. /** The message itself, whose timestamp is used to specify the event's time.
  20547. */
  20548. MidiMessage message;
  20549. /** The matching note-off event (if this is a note-on event).
  20550. If this isn't a note-on, this pointer will be null.
  20551. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  20552. note-offs up-to-date after events have been moved around in the sequence
  20553. or deleted.
  20554. */
  20555. MidiEventHolder* noteOffObject;
  20556. juce_UseDebuggingNewOperator
  20557. private:
  20558. friend class MidiMessageSequence;
  20559. MidiEventHolder (const MidiMessage& message);
  20560. };
  20561. /** Clears the sequence. */
  20562. void clear();
  20563. /** Returns the number of events in the sequence. */
  20564. int getNumEvents() const;
  20565. /** Returns a pointer to one of the events. */
  20566. MidiEventHolder* getEventPointer (const int index) const;
  20567. /** Returns the time of the note-up that matches the note-on at this index.
  20568. If the event at this index isn't a note-on, it'll just return 0.
  20569. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  20570. */
  20571. double getTimeOfMatchingKeyUp (const int index) const;
  20572. /** Returns the index of the note-up that matches the note-on at this index.
  20573. If the event at this index isn't a note-on, it'll just return -1.
  20574. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  20575. */
  20576. int getIndexOfMatchingKeyUp (const int index) const;
  20577. /** Returns the index of an event. */
  20578. int getIndexOf (MidiEventHolder* const event) const;
  20579. /** Returns the index of the first event on or after the given timestamp.
  20580. If the time is beyond the end of the sequence, this will return the
  20581. number of events.
  20582. */
  20583. int getNextIndexAtTime (const double timeStamp) const;
  20584. /** Returns the timestamp of the first event in the sequence.
  20585. @see getEndTime
  20586. */
  20587. double getStartTime() const;
  20588. /** Returns the timestamp of the last event in the sequence.
  20589. @see getStartTime
  20590. */
  20591. double getEndTime() const;
  20592. /** Returns the timestamp of the event at a given index.
  20593. If the index is out-of-range, this will return 0.0
  20594. */
  20595. double getEventTime (const int index) const;
  20596. /** Inserts a midi message into the sequence.
  20597. The index at which the new message gets inserted will depend on its timestamp,
  20598. because the sequence is kept sorted.
  20599. Remember to call updateMatchedPairs() after adding note-on events.
  20600. @param newMessage the new message to add (an internal copy will be made)
  20601. @param timeAdjustment an optional value to add to the timestamp of the message
  20602. that will be inserted
  20603. @see updateMatchedPairs
  20604. */
  20605. void addEvent (const MidiMessage& newMessage,
  20606. double timeAdjustment = 0);
  20607. /** Deletes one of the events in the sequence.
  20608. Remember to call updateMatchedPairs() after removing events.
  20609. @param index the index of the event to delete
  20610. @param deleteMatchingNoteUp whether to also remove the matching note-off
  20611. if the event you're removing is a note-on
  20612. */
  20613. void deleteEvent (const int index,
  20614. const bool deleteMatchingNoteUp);
  20615. /** Merges another sequence into this one.
  20616. Remember to call updateMatchedPairs() after using this method.
  20617. @param other the sequence to add from
  20618. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  20619. as they are read from the other sequence
  20620. @param firstAllowableDestTime events will not be added if their time is earlier
  20621. than this time. (This is after their time has been adjusted
  20622. by the timeAdjustmentDelta)
  20623. @param endOfAllowableDestTimes events will not be added if their time is equal to
  20624. or greater than this time. (This is after their time has
  20625. been adjusted by the timeAdjustmentDelta)
  20626. */
  20627. void addSequence (const MidiMessageSequence& other,
  20628. double timeAdjustmentDelta,
  20629. double firstAllowableDestTime,
  20630. double endOfAllowableDestTimes);
  20631. /** Makes sure all the note-on and note-off pairs are up-to-date.
  20632. Call this after moving messages about or deleting/adding messages, and it
  20633. will scan the list and make sure all the note-offs in the MidiEventHolder
  20634. structures are pointing at the correct ones.
  20635. */
  20636. void updateMatchedPairs();
  20637. /** Copies all the messages for a particular midi channel to another sequence.
  20638. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  20639. @param destSequence the sequence that the chosen events should be copied to
  20640. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  20641. channel) will also be copied across.
  20642. @see extractSysExMessages
  20643. */
  20644. void extractMidiChannelMessages (const int channelNumberToExtract,
  20645. MidiMessageSequence& destSequence,
  20646. const bool alsoIncludeMetaEvents) const;
  20647. /** Copies all midi sys-ex messages to another sequence.
  20648. @param destSequence this is the sequence to which any sys-exes in this sequence
  20649. will be added
  20650. @see extractMidiChannelMessages
  20651. */
  20652. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  20653. /** Removes any messages in this sequence that have a specific midi channel.
  20654. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  20655. */
  20656. void deleteMidiChannelMessages (const int channelNumberToRemove);
  20657. /** Removes any sys-ex messages from this sequence.
  20658. */
  20659. void deleteSysExMessages();
  20660. /** Adds an offset to the timestamps of all events in the sequence.
  20661. @param deltaTime the amount to add to each timestamp.
  20662. */
  20663. void addTimeToMessages (const double deltaTime);
  20664. /** Scans through the sequence to determine the state of any midi controllers at
  20665. a given time.
  20666. This will create a sequence of midi controller changes that can be
  20667. used to set all midi controllers to the state they would be in at the
  20668. specified time within this sequence.
  20669. As well as controllers, it will also recreate the midi program number
  20670. and pitch bend position.
  20671. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  20672. for other channels will be ignored.
  20673. @param time the time at which you want to find out the state - there are
  20674. no explicit units for this time measurement, it's the same units
  20675. as used for the timestamps of the messages
  20676. @param resultMessages an array to which midi controller-change messages will be added. This
  20677. will be the minimum number of controller changes to recreate the
  20678. state at the required time.
  20679. */
  20680. void createControllerUpdatesForTime (const int channelNumber,
  20681. const double time,
  20682. OwnedArray<MidiMessage>& resultMessages);
  20683. juce_UseDebuggingNewOperator
  20684. /** @internal */
  20685. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20686. const MidiMessageSequence::MidiEventHolder* const second) throw();
  20687. private:
  20688. friend class MidiComparator;
  20689. friend class MidiFile;
  20690. OwnedArray <MidiEventHolder> list;
  20691. void sort();
  20692. };
  20693. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20694. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  20695. /**
  20696. Reads/writes standard midi format files.
  20697. To read a midi file, create a MidiFile object and call its readFrom() method. You
  20698. can then get the individual midi tracks from it using the getTrack() method.
  20699. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  20700. to it using the addTrack() method, and then call its writeTo() method to stream
  20701. it out.
  20702. @see MidiMessageSequence
  20703. */
  20704. class JUCE_API MidiFile
  20705. {
  20706. public:
  20707. /** Creates an empty MidiFile object.
  20708. */
  20709. MidiFile() throw();
  20710. /** Destructor. */
  20711. ~MidiFile() throw();
  20712. /** Returns the number of tracks in the file.
  20713. @see getTrack, addTrack
  20714. */
  20715. int getNumTracks() const throw();
  20716. /** Returns a pointer to one of the tracks in the file.
  20717. @returns a pointer to the track, or 0 if the index is out-of-range
  20718. @see getNumTracks, addTrack
  20719. */
  20720. const MidiMessageSequence* getTrack (const int index) const throw();
  20721. /** Adds a midi track to the file.
  20722. This will make its own internal copy of the sequence that is passed-in.
  20723. @see getNumTracks, getTrack
  20724. */
  20725. void addTrack (const MidiMessageSequence& trackSequence) throw();
  20726. /** Removes all midi tracks from the file.
  20727. @see getNumTracks
  20728. */
  20729. void clear() throw();
  20730. /** Returns the raw time format code that will be written to a stream.
  20731. After reading a midi file, this method will return the time-format that
  20732. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  20733. or setSmpteTimeFormat() methods.
  20734. If the value returned is positive, it indicates the number of midi ticks
  20735. per quarter-note - see setTicksPerQuarterNote().
  20736. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  20737. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  20738. */
  20739. short getTimeFormat() const throw();
  20740. /** Sets the time format to use when this file is written to a stream.
  20741. If this is called, the file will be written as bars/beats using the
  20742. specified resolution, rather than SMPTE absolute times, as would be
  20743. used if setSmpteTimeFormat() had been called instead.
  20744. @param ticksPerQuarterNote e.g. 96, 960
  20745. @see setSmpteTimeFormat
  20746. */
  20747. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  20748. /** Sets the time format to use when this file is written to a stream.
  20749. If this is called, the file will be written using absolute times, rather
  20750. than bars/beats as would be the case if setTicksPerBeat() had been called
  20751. instead.
  20752. @param framesPerSecond must be 24, 25, 29 or 30
  20753. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  20754. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  20755. timing, setSmpteTimeFormat (25, 40)
  20756. @see setTicksPerBeat
  20757. */
  20758. void setSmpteTimeFormat (const int framesPerSecond,
  20759. const int subframeResolution) throw();
  20760. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  20761. Useful for finding the positions of all the tempo changes in a file.
  20762. @param tempoChangeEvents a list to which all the events will be added
  20763. */
  20764. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  20765. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  20766. Useful for finding the positions of all the tempo changes in a file.
  20767. @param timeSigEvents a list to which all the events will be added
  20768. */
  20769. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  20770. /** Returns the latest timestamp in any of the tracks.
  20771. (Useful for finding the length of the file).
  20772. */
  20773. double getLastTimestamp() const;
  20774. /** Reads a midi file format stream.
  20775. After calling this, you can get the tracks that were read from the file by using the
  20776. getNumTracks() and getTrack() methods.
  20777. The timestamps of the midi events in the tracks will represent their positions in
  20778. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  20779. method.
  20780. @returns true if the stream was read successfully
  20781. */
  20782. bool readFrom (InputStream& sourceStream);
  20783. /** Writes the midi tracks as a standard midi file.
  20784. @returns true if the operation succeeded.
  20785. */
  20786. bool writeTo (OutputStream& destStream);
  20787. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  20788. This will use the midi time format and tempo/time signature info in the
  20789. tracks to convert all the timestamps to absolute values in seconds.
  20790. */
  20791. void convertTimestampTicksToSeconds();
  20792. juce_UseDebuggingNewOperator
  20793. /** @internal */
  20794. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20795. const MidiMessageSequence::MidiEventHolder* const second) throw();
  20796. private:
  20797. MidiMessageSequence* tracks [128];
  20798. short numTracks, timeFormat;
  20799. MidiFile (const MidiFile&);
  20800. const MidiFile& operator= (const MidiFile&);
  20801. void readNextTrack (const char* data, int size);
  20802. void writeTrack (OutputStream& mainOut, const int trackNum);
  20803. };
  20804. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  20805. /********* End of inlined file: juce_MidiFile.h *********/
  20806. #endif
  20807. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20808. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  20809. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20810. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20811. class MidiKeyboardState;
  20812. /**
  20813. Receives events from a MidiKeyboardState object.
  20814. @see MidiKeyboardState
  20815. */
  20816. class JUCE_API MidiKeyboardStateListener
  20817. {
  20818. public:
  20819. MidiKeyboardStateListener() throw() {}
  20820. virtual ~MidiKeyboardStateListener() {}
  20821. /** Called when one of the MidiKeyboardState's keys is pressed.
  20822. This will be called synchronously when the state is either processing a
  20823. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  20824. when a note is being played with its MidiKeyboardState::noteOn() method.
  20825. Note that this callback could happen from an audio callback thread, so be
  20826. careful not to block, and avoid any UI activity in the callback.
  20827. */
  20828. virtual void handleNoteOn (MidiKeyboardState* source,
  20829. int midiChannel, int midiNoteNumber, float velocity) = 0;
  20830. /** Called when one of the MidiKeyboardState's keys is released.
  20831. This will be called synchronously when the state is either processing a
  20832. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  20833. when a note is being played with its MidiKeyboardState::noteOff() method.
  20834. Note that this callback could happen from an audio callback thread, so be
  20835. careful not to block, and avoid any UI activity in the callback.
  20836. */
  20837. virtual void handleNoteOff (MidiKeyboardState* source,
  20838. int midiChannel, int midiNoteNumber) = 0;
  20839. };
  20840. /**
  20841. Represents a piano keyboard, keeping track of which keys are currently pressed.
  20842. This object can parse a stream of midi events, using them to update its idea
  20843. of which keys are pressed for each individiual midi channel.
  20844. When keys go up or down, it can broadcast these events to listener objects.
  20845. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  20846. methods, and midi messages for these events will be merged into the
  20847. midi stream that gets processed by processNextMidiBuffer().
  20848. */
  20849. class JUCE_API MidiKeyboardState
  20850. {
  20851. public:
  20852. MidiKeyboardState();
  20853. ~MidiKeyboardState();
  20854. /** Resets the state of the object.
  20855. All internal data for all the channels is reset, but no events are sent as a
  20856. result.
  20857. If you want to release any keys that are currently down, and to send out note-up
  20858. midi messages for this, use the allNotesOff() method instead.
  20859. */
  20860. void reset();
  20861. /** Returns true if the given midi key is currently held down for the given midi channel.
  20862. The channel number must be between 1 and 16. If you want to see if any notes are
  20863. on for a range of channels, use the isNoteOnForChannels() method.
  20864. */
  20865. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  20866. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  20867. The channel mask has a bit set for each midi channel you want to test for - bit
  20868. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  20869. If a note is on for at least one of the specified channels, this returns true.
  20870. */
  20871. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  20872. /** Turns a specified note on.
  20873. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  20874. next call to processNextMidiBuffer().
  20875. It will also trigger a synchronous callback to the listeners to tell them that the key has
  20876. gone down.
  20877. */
  20878. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  20879. /** Turns a specified note off.
  20880. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  20881. next call to processNextMidiBuffer().
  20882. It will also trigger a synchronous callback to the listeners to tell them that the key has
  20883. gone up.
  20884. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  20885. */
  20886. void noteOff (const int midiChannel, const int midiNoteNumber);
  20887. /** This will turn off any currently-down notes for the given midi channel.
  20888. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  20889. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  20890. and events being added to the midi stream.
  20891. */
  20892. void allNotesOff (const int midiChannel);
  20893. /** Looks at a key-up/down event and uses it to update the state of this object.
  20894. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  20895. instead.
  20896. */
  20897. void processNextMidiEvent (const MidiMessage& message);
  20898. /** Scans a midi stream for up/down events and adds its own events to it.
  20899. This will look for any up/down events and use them to update the internal state,
  20900. synchronously making suitable callbacks to the listeners.
  20901. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  20902. and noteOff() calls will be added into the buffer.
  20903. Only the section of the buffer whose timestamps are between startSample and
  20904. (startSample + numSamples) will be affected, and any events added will be placed
  20905. between these times.
  20906. If you're going to use this method, you'll need to keep calling it regularly for
  20907. it to work satisfactorily.
  20908. To process a single midi event at a time, use the processNextMidiEvent() method
  20909. instead.
  20910. */
  20911. void processNextMidiBuffer (MidiBuffer& buffer,
  20912. const int startSample,
  20913. const int numSamples,
  20914. const bool injectIndirectEvents);
  20915. /** Registers a listener for callbacks when keys go up or down.
  20916. @see removeListener
  20917. */
  20918. void addListener (MidiKeyboardStateListener* const listener) throw();
  20919. /** Deregisters a listener.
  20920. @see addListener
  20921. */
  20922. void removeListener (MidiKeyboardStateListener* const listener) throw();
  20923. juce_UseDebuggingNewOperator
  20924. private:
  20925. CriticalSection lock;
  20926. uint16 noteStates [128];
  20927. MidiBuffer eventsToAdd;
  20928. VoidArray listeners;
  20929. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  20930. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  20931. MidiKeyboardState (const MidiKeyboardState&);
  20932. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  20933. };
  20934. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20935. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  20936. #endif
  20937. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20938. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  20939. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20940. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20941. /********* Start of inlined file: juce_MidiInput.h *********/
  20942. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  20943. #define __JUCE_MIDIINPUT_JUCEHEADER__
  20944. class MidiInput;
  20945. /**
  20946. Receives midi messages from a midi input device.
  20947. This class is overridden to handle incoming midi messages. See the MidiInput
  20948. class for more details.
  20949. @see MidiInput
  20950. */
  20951. class JUCE_API MidiInputCallback
  20952. {
  20953. public:
  20954. /** Destructor. */
  20955. virtual ~MidiInputCallback() {}
  20956. /** Receives an incoming message.
  20957. A MidiInput object will call this method when a midi event arrives. It'll be
  20958. called on a high-priority system thread, so avoid doing anything time-consuming
  20959. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  20960. for queueing incoming messages for use later.
  20961. @param source the MidiInput object that generated the message
  20962. @param message the incoming message. The message's timestamp is set to a value
  20963. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  20964. time when the message arrived.
  20965. */
  20966. virtual void handleIncomingMidiMessage (MidiInput* source,
  20967. const MidiMessage& message) = 0;
  20968. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  20969. If a long sysex message is broken up into multiple packets, this callback is made
  20970. for each packet that arrives until the message is finished, at which point
  20971. the normal handleIncomingMidiMessage() callback will be made with the entire
  20972. message.
  20973. The message passed in will contain the start of a sysex, but won't be finished
  20974. with the terminating 0xf7 byte.
  20975. */
  20976. virtual void handlePartialSysexMessage (MidiInput* source,
  20977. const uint8* messageData,
  20978. const int numBytesSoFar,
  20979. const double timestamp)
  20980. {
  20981. // (this bit is just to avoid compiler warnings about unused variables)
  20982. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  20983. }
  20984. };
  20985. /**
  20986. Represents a midi input device.
  20987. To create one of these, use the static getDevices() method to find out what inputs are
  20988. available, and then use the openDevice() method to try to open one.
  20989. @see MidiOutput
  20990. */
  20991. class JUCE_API MidiInput
  20992. {
  20993. public:
  20994. /** Returns a list of the available midi input devices.
  20995. You can open one of the devices by passing its index into the
  20996. openDevice() method.
  20997. @see getDefaultDeviceIndex, openDevice
  20998. */
  20999. static const StringArray getDevices();
  21000. /** Returns the index of the default midi input device to use.
  21001. This refers to the index in the list returned by getDevices().
  21002. */
  21003. static int getDefaultDeviceIndex();
  21004. /** Tries to open one of the midi input devices.
  21005. This will return a MidiInput object if it manages to open it. You can then
  21006. call start() and stop() on this device, and delete it when no longer needed.
  21007. If the device can't be opened, this will return a null pointer.
  21008. @param deviceIndex the index of a device from the list returned by getDevices()
  21009. @param callback the object that will receive the midi messages from this device.
  21010. @see MidiInputCallback, getDevices
  21011. */
  21012. static MidiInput* openDevice (int deviceIndex,
  21013. MidiInputCallback* callback);
  21014. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  21015. /** This will try to create a new midi input device (Not available on Windows).
  21016. This will attempt to create a new midi input device with the specified name,
  21017. for other apps to connect to.
  21018. Returns 0 if a device can't be created.
  21019. @param deviceName the name to use for the new device
  21020. @param callback the object that will receive the midi messages from this device.
  21021. */
  21022. static MidiInput* createNewDevice (const String& deviceName,
  21023. MidiInputCallback* callback);
  21024. #endif
  21025. /** Destructor. */
  21026. virtual ~MidiInput();
  21027. /** Returns the name of this device.
  21028. */
  21029. virtual const String getName() const throw() { return name; }
  21030. /** Allows you to set a custom name for the device, in case you don't like the name
  21031. it was given when created.
  21032. */
  21033. virtual void setName (const String& newName) throw() { name = newName; }
  21034. /** Starts the device running.
  21035. After calling this, the device will start sending midi messages to the
  21036. MidiInputCallback object that was specified when the openDevice() method
  21037. was called.
  21038. @see stop
  21039. */
  21040. virtual void start();
  21041. /** Stops the device running.
  21042. @see start
  21043. */
  21044. virtual void stop();
  21045. juce_UseDebuggingNewOperator
  21046. protected:
  21047. String name;
  21048. void* internal;
  21049. MidiInput (const String& name);
  21050. MidiInput (const MidiInput&);
  21051. };
  21052. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  21053. /********* End of inlined file: juce_MidiInput.h *********/
  21054. /**
  21055. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  21056. processing by a block-based audio callback.
  21057. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  21058. so it can easily use a midi input or keyboard component as its source.
  21059. @see MidiMessage, MidiInput
  21060. */
  21061. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  21062. public MidiInputCallback
  21063. {
  21064. public:
  21065. /** Creates a MidiMessageCollector. */
  21066. MidiMessageCollector();
  21067. /** Destructor. */
  21068. ~MidiMessageCollector();
  21069. /** Clears any messages from the queue.
  21070. You need to call this method before starting to use the collector, so that
  21071. it knows the correct sample rate to use.
  21072. */
  21073. void reset (const double sampleRate);
  21074. /** Takes an incoming real-time message and adds it to the queue.
  21075. The message's timestamp is taken, and it will be ready for retrieval as part
  21076. of the block returned by the next call to removeNextBlockOfMessages().
  21077. This method is fully thread-safe when overlapping calls are made with
  21078. removeNextBlockOfMessages().
  21079. */
  21080. void addMessageToQueue (const MidiMessage& message);
  21081. /** Removes all the pending messages from the queue as a buffer.
  21082. This will also correct the messages' timestamps to make sure they're in
  21083. the range 0 to numSamples - 1.
  21084. This call should be made regularly by something like an audio processing
  21085. callback, because the time that it happens is used in calculating the
  21086. midi event positions.
  21087. This method is fully thread-safe when overlapping calls are made with
  21088. addMessageToQueue().
  21089. */
  21090. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  21091. const int numSamples);
  21092. /** @internal */
  21093. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  21094. /** @internal */
  21095. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  21096. /** @internal */
  21097. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  21098. juce_UseDebuggingNewOperator
  21099. private:
  21100. double lastCallbackTime;
  21101. CriticalSection midiCallbackLock;
  21102. MidiBuffer incomingMessages;
  21103. double sampleRate;
  21104. MidiMessageCollector (const MidiMessageCollector&);
  21105. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  21106. };
  21107. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  21108. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  21109. #endif
  21110. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  21111. #endif
  21112. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  21113. #endif
  21114. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  21115. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  21116. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  21117. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  21118. /**
  21119. A set of routines to convert buffers of 32-bit floating point data to and from
  21120. various integer formats.
  21121. */
  21122. class JUCE_API AudioDataConverters
  21123. {
  21124. public:
  21125. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  21126. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  21127. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  21128. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  21129. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  21130. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  21131. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  21132. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  21133. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  21134. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  21135. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  21136. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  21137. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  21138. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  21139. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  21140. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  21141. enum DataFormat
  21142. {
  21143. int16LE,
  21144. int16BE,
  21145. int24LE,
  21146. int24BE,
  21147. int32LE,
  21148. int32BE,
  21149. float32LE,
  21150. float32BE,
  21151. };
  21152. static void convertFloatToFormat (const DataFormat destFormat,
  21153. const float* source, void* dest, int numSamples);
  21154. static void convertFormatToFloat (const DataFormat sourceFormat,
  21155. const void* source, float* dest, int numSamples);
  21156. static void interleaveSamples (const float** source, float* dest,
  21157. const int numSamples, const int numChannels);
  21158. static void deinterleaveSamples (const float* source, float** dest,
  21159. const int numSamples, const int numChannels);
  21160. };
  21161. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  21162. /********* End of inlined file: juce_AudioDataConverters.h *********/
  21163. #endif
  21164. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21165. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  21166. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21167. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21168. class AudioFormatReader;
  21169. class AudioFormatWriter;
  21170. /**
  21171. A multi-channel buffer of 32-bit floating point audio samples.
  21172. */
  21173. class JUCE_API AudioSampleBuffer
  21174. {
  21175. public:
  21176. /** Creates a buffer with a specified number of channels and samples.
  21177. The contents of the buffer will initially be undefined, so use clear() to
  21178. set all the samples to zero.
  21179. The buffer will allocate its memory internally, and this will be released
  21180. when the buffer is deleted.
  21181. */
  21182. AudioSampleBuffer (const int numChannels,
  21183. const int numSamples) throw();
  21184. /** Creates a buffer using a pre-allocated block of memory.
  21185. Note that if the buffer is resized or its number of channels is changed, it
  21186. will re-allocate memory internally and copy the existing data to this new area,
  21187. so it will then stop directly addressing this memory.
  21188. @param dataToReferTo a pre-allocated array containing pointers to the data
  21189. for each channel that should be used by this buffer. The
  21190. buffer will only refer to this memory, it won't try to delete
  21191. it when the buffer is deleted or resized.
  21192. @param numChannels the number of channels to use - this must correspond to the
  21193. number of elements in the array passed in
  21194. @param numSamples the number of samples to use - this must correspond to the
  21195. size of the arrays passed in
  21196. */
  21197. AudioSampleBuffer (float** dataToReferTo,
  21198. const int numChannels,
  21199. const int numSamples) throw();
  21200. /** Copies another buffer.
  21201. This buffer will make its own copy of the other's data, unless the buffer was created
  21202. using an external data buffer, in which case boths buffers will just point to the same
  21203. shared block of data.
  21204. */
  21205. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  21206. /** Copies another buffer onto this one.
  21207. This buffer's size will be changed to that of the other buffer.
  21208. */
  21209. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  21210. /** Destructor.
  21211. This will free any memory allocated by the buffer.
  21212. */
  21213. virtual ~AudioSampleBuffer() throw();
  21214. /** Returns the number of channels of audio data that this buffer contains.
  21215. @see getSampleData
  21216. */
  21217. int getNumChannels() const throw() { return numChannels; }
  21218. /** Returns the number of samples allocated in each of the buffer's channels.
  21219. @see getSampleData
  21220. */
  21221. int getNumSamples() const throw() { return size; }
  21222. /** Returns a pointer one of the buffer's channels.
  21223. For speed, this doesn't check whether the channel number is out of range,
  21224. so be careful when using it!
  21225. */
  21226. float* getSampleData (const int channelNumber) const throw()
  21227. {
  21228. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21229. return channels [channelNumber];
  21230. }
  21231. /** Returns a pointer to a sample in one of the buffer's channels.
  21232. For speed, this doesn't check whether the channel and sample number
  21233. are out-of-range, so be careful when using it!
  21234. */
  21235. float* getSampleData (const int channelNumber,
  21236. const int sampleOffset) const throw()
  21237. {
  21238. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21239. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  21240. return channels [channelNumber] + sampleOffset;
  21241. }
  21242. /** Returns an array of pointers to the channels in the buffer.
  21243. Don't modify any of the pointers that are returned, and bear in mind that
  21244. these will become invalid if the buffer is resized.
  21245. */
  21246. float** getArrayOfChannels() const throw() { return channels; }
  21247. /** Chages the buffer's size or number of channels.
  21248. This can expand or contract the buffer's length, and add or remove channels.
  21249. If keepExistingContent is true, it will try to preserve as much of the
  21250. old data as it can in the new buffer.
  21251. If clearExtraSpace is true, then any extra channels or space that is
  21252. allocated will be also be cleared. If false, then this space is left
  21253. uninitialised.
  21254. If avoidReallocating is true, then changing the buffer's size won't reduce the
  21255. amount of memory that is currently allocated (but it will still increase it if
  21256. the new size is bigger than the amount it currently has). If this is false, then
  21257. a new allocation will be done so that the buffer uses takes up the minimum amount
  21258. of memory that it needs.
  21259. */
  21260. void setSize (const int newNumChannels,
  21261. const int newNumSamples,
  21262. const bool keepExistingContent = false,
  21263. const bool clearExtraSpace = false,
  21264. const bool avoidReallocating = false) throw();
  21265. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  21266. There's also a constructor that lets you specify arrays like this, but this
  21267. lets you change the channels dynamically.
  21268. Note that if the buffer is resized or its number of channels is changed, it
  21269. will re-allocate memory internally and copy the existing data to this new area,
  21270. so it will then stop directly addressing this memory.
  21271. @param dataToReferTo a pre-allocated array containing pointers to the data
  21272. for each channel that should be used by this buffer. The
  21273. buffer will only refer to this memory, it won't try to delete
  21274. it when the buffer is deleted or resized.
  21275. @param numChannels the number of channels to use - this must correspond to the
  21276. number of elements in the array passed in
  21277. @param numSamples the number of samples to use - this must correspond to the
  21278. size of the arrays passed in
  21279. */
  21280. void setDataToReferTo (float** dataToReferTo,
  21281. const int numChannels,
  21282. const int numSamples) throw();
  21283. /** Clears all the samples in all channels. */
  21284. void clear() throw();
  21285. /** Clears a specified region of all the channels.
  21286. For speed, this doesn't check whether the channel and sample number
  21287. are in-range, so be careful!
  21288. */
  21289. void clear (const int startSample,
  21290. const int numSamples) throw();
  21291. /** Clears a specified region of just one channel.
  21292. For speed, this doesn't check whether the channel and sample number
  21293. are in-range, so be careful!
  21294. */
  21295. void clear (const int channel,
  21296. const int startSample,
  21297. const int numSamples) throw();
  21298. /** Applies a gain multiple to a region of one channel.
  21299. For speed, this doesn't check whether the channel and sample number
  21300. are in-range, so be careful!
  21301. */
  21302. void applyGain (const int channel,
  21303. const int startSample,
  21304. int numSamples,
  21305. const float gain) throw();
  21306. /** Applies a gain multiple to a region of all the channels.
  21307. For speed, this doesn't check whether the sample numbers
  21308. are in-range, so be careful!
  21309. */
  21310. void applyGain (const int startSample,
  21311. const int numSamples,
  21312. const float gain) throw();
  21313. /** Applies a range of gains to a region of a channel.
  21314. The gain that is applied to each sample will vary from
  21315. startGain on the first sample to endGain on the last Sample,
  21316. so it can be used to do basic fades.
  21317. For speed, this doesn't check whether the sample numbers
  21318. are in-range, so be careful!
  21319. */
  21320. void applyGainRamp (const int channel,
  21321. const int startSample,
  21322. int numSamples,
  21323. float startGain,
  21324. float endGain) throw();
  21325. /** Adds samples from another buffer to this one.
  21326. @param destChannel the channel within this buffer to add the samples to
  21327. @param destStartSample the start sample within this buffer's channel
  21328. @param source the source buffer to add from
  21329. @param sourceChannel the channel within the source buffer to read from
  21330. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  21331. @param numSamples the number of samples to process
  21332. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  21333. added to this buffer's samples
  21334. @see copyFrom
  21335. */
  21336. void addFrom (const int destChannel,
  21337. const int destStartSample,
  21338. const AudioSampleBuffer& source,
  21339. const int sourceChannel,
  21340. const int sourceStartSample,
  21341. int numSamples,
  21342. const float gainToApplyToSource = 1.0f) throw();
  21343. /** Adds samples from an array of floats to one of the channels.
  21344. @param destChannel the channel within this buffer to add the samples to
  21345. @param destStartSample the start sample within this buffer's channel
  21346. @param source the source data to use
  21347. @param numSamples the number of samples to process
  21348. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  21349. added to this buffer's samples
  21350. @see copyFrom
  21351. */
  21352. void addFrom (const int destChannel,
  21353. const int destStartSample,
  21354. const float* source,
  21355. int numSamples,
  21356. const float gainToApplyToSource = 1.0f) throw();
  21357. /** Adds samples from an array of floats, applying a gain ramp to them.
  21358. @param destChannel the channel within this buffer to add the samples to
  21359. @param destStartSample the start sample within this buffer's channel
  21360. @param source the source data to use
  21361. @param numSamples the number of samples to process
  21362. @param startGain the gain to apply to the first sample (this is multiplied with
  21363. the source samples before they are added to this buffer)
  21364. @param endGain the gain to apply to the final sample. The gain is linearly
  21365. interpolated between the first and last samples.
  21366. */
  21367. void addFromWithRamp (const int destChannel,
  21368. const int destStartSample,
  21369. const float* source,
  21370. int numSamples,
  21371. float startGain,
  21372. float endGain) throw();
  21373. /** Copies samples from another buffer to this one.
  21374. @param destChannel the channel within this buffer to copy the samples to
  21375. @param destStartSample the start sample within this buffer's channel
  21376. @param source the source buffer to read from
  21377. @param sourceChannel the channel within the source buffer to read from
  21378. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  21379. @param numSamples the number of samples to process
  21380. @see addFrom
  21381. */
  21382. void copyFrom (const int destChannel,
  21383. const int destStartSample,
  21384. const AudioSampleBuffer& source,
  21385. const int sourceChannel,
  21386. const int sourceStartSample,
  21387. int numSamples) throw();
  21388. /** Copies samples from an array of floats into one of the channels.
  21389. @param destChannel the channel within this buffer to copy the samples to
  21390. @param destStartSample the start sample within this buffer's channel
  21391. @param source the source buffer to read from
  21392. @param numSamples the number of samples to process
  21393. @see addFrom
  21394. */
  21395. void copyFrom (const int destChannel,
  21396. const int destStartSample,
  21397. const float* source,
  21398. int numSamples) throw();
  21399. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  21400. @param destChannel the channel within this buffer to copy the samples to
  21401. @param destStartSample the start sample within this buffer's channel
  21402. @param source the source buffer to read from
  21403. @param numSamples the number of samples to process
  21404. @param gain the gain to apply
  21405. @see addFrom
  21406. */
  21407. void copyFrom (const int destChannel,
  21408. const int destStartSample,
  21409. const float* source,
  21410. int numSamples,
  21411. const float gain) throw();
  21412. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  21413. @param destChannel the channel within this buffer to copy the samples to
  21414. @param destStartSample the start sample within this buffer's channel
  21415. @param source the source buffer to read from
  21416. @param numSamples the number of samples to process
  21417. @param startGain the gain to apply to the first sample (this is multiplied with
  21418. the source samples before they are copied to this buffer)
  21419. @param endGain the gain to apply to the final sample. The gain is linearly
  21420. interpolated between the first and last samples.
  21421. @see addFrom
  21422. */
  21423. void copyFromWithRamp (const int destChannel,
  21424. const int destStartSample,
  21425. const float* source,
  21426. int numSamples,
  21427. float startGain,
  21428. float endGain) throw();
  21429. /** Finds the highest and lowest sample values in a given range.
  21430. @param channel the channel to read from
  21431. @param startSample the start sample within the channel
  21432. @param numSamples the number of samples to check
  21433. @param minVal on return, the lowest value that was found
  21434. @param maxVal on return, the highest value that was found
  21435. */
  21436. void findMinMax (const int channel,
  21437. const int startSample,
  21438. int numSamples,
  21439. float& minVal,
  21440. float& maxVal) const throw();
  21441. /** Finds the highest absolute sample value within a region of a channel.
  21442. */
  21443. float getMagnitude (const int channel,
  21444. const int startSample,
  21445. const int numSamples) const throw();
  21446. /** Finds the highest absolute sample value within a region on all channels.
  21447. */
  21448. float getMagnitude (const int startSample,
  21449. const int numSamples) const throw();
  21450. /** Returns the root mean squared level for a region of a channel.
  21451. */
  21452. float getRMSLevel (const int channel,
  21453. const int startSample,
  21454. const int numSamples) const throw();
  21455. /** Fills a section of the buffer using an AudioReader as its source.
  21456. This will convert the reader's fixed- or floating-point data to
  21457. the buffer's floating-point format, and will try to intelligently
  21458. cope with mismatches between the number of channels in the reader
  21459. and the buffer.
  21460. @see writeToAudioWriter
  21461. */
  21462. void readFromAudioReader (AudioFormatReader* reader,
  21463. const int startSample,
  21464. const int numSamples,
  21465. const int readerStartSample,
  21466. const bool useReaderLeftChan,
  21467. const bool useReaderRightChan) throw();
  21468. /** Writes a section of this buffer to an audio writer.
  21469. This saves you having to mess about with channels or floating/fixed
  21470. point conversion.
  21471. @see readFromAudioReader
  21472. */
  21473. void writeToAudioWriter (AudioFormatWriter* writer,
  21474. const int startSample,
  21475. const int numSamples) const throw();
  21476. juce_UseDebuggingNewOperator
  21477. private:
  21478. int numChannels, size, allocatedBytes;
  21479. float** channels;
  21480. float* allocatedData;
  21481. float* preallocatedChannelSpace [32];
  21482. };
  21483. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21484. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  21485. #endif
  21486. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  21487. /********* Start of inlined file: juce_IIRFilter.h *********/
  21488. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  21489. #define __JUCE_IIRFILTER_JUCEHEADER__
  21490. /**
  21491. An IIR filter that can perform low, high, or band-pass filtering on an
  21492. audio signal.
  21493. @see IIRFilterAudioSource
  21494. */
  21495. class JUCE_API IIRFilter
  21496. {
  21497. public:
  21498. /** Creates a filter.
  21499. Initially the filter is inactive, so will have no effect on samples that
  21500. you process with it. Use the appropriate method to turn it into the type
  21501. of filter needed.
  21502. */
  21503. IIRFilter() throw();
  21504. /** Creates a copy of another filter. */
  21505. IIRFilter (const IIRFilter& other) throw();
  21506. /** Destructor. */
  21507. ~IIRFilter() throw();
  21508. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  21509. Note that this clears the processing state, but the type of filter and
  21510. its coefficients aren't changed. To put a filter into an inactive state, use
  21511. the makeInactive() method.
  21512. */
  21513. void reset() throw();
  21514. /** Performs the filter operation on the given set of samples.
  21515. */
  21516. void processSamples (float* const samples,
  21517. const int numSamples) throw();
  21518. /** Processes a single sample, without any locking or checking.
  21519. Use this if you need fast processing of a single value, but be aware that
  21520. this isn't thread-safe in the way that processSamples() is.
  21521. */
  21522. float processSingleSampleRaw (const float sample) throw();
  21523. /** Sets the filter up to act as a low-pass filter.
  21524. */
  21525. void makeLowPass (const double sampleRate,
  21526. const double frequency) throw();
  21527. /** Sets the filter up to act as a high-pass filter.
  21528. */
  21529. void makeHighPass (const double sampleRate,
  21530. const double frequency) throw();
  21531. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  21532. The gain is a scale factor that the low frequencies are multiplied by, so values
  21533. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  21534. attenuate them.
  21535. */
  21536. void makeLowShelf (const double sampleRate,
  21537. const double cutOffFrequency,
  21538. const double Q,
  21539. const float gainFactor) throw();
  21540. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  21541. The gain is a scale factor that the high frequencies are multiplied by, so values
  21542. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  21543. attenuate them.
  21544. */
  21545. void makeHighShelf (const double sampleRate,
  21546. const double cutOffFrequency,
  21547. const double Q,
  21548. const float gainFactor) throw();
  21549. /** Sets the filter up to act as a band pass filter centred around a
  21550. frequency, with a variable Q and gain.
  21551. The gain is a scale factor that the centre frequencies are multiplied by, so
  21552. values greater than 1.0 will boost the centre frequencies, values less than
  21553. 1.0 will attenuate them.
  21554. */
  21555. void makeBandPass (const double sampleRate,
  21556. const double centreFrequency,
  21557. const double Q,
  21558. const float gainFactor) throw();
  21559. /** Clears the filter's coefficients so that it becomes inactive.
  21560. */
  21561. void makeInactive() throw();
  21562. /** Makes this filter duplicate the set-up of another one.
  21563. */
  21564. void copyCoefficientsFrom (const IIRFilter& other) throw();
  21565. juce_UseDebuggingNewOperator
  21566. protected:
  21567. CriticalSection processLock;
  21568. void setCoefficients (double c1, double c2, double c3,
  21569. double c4, double c5, double c6) throw();
  21570. bool active;
  21571. float coefficients[6];
  21572. float x1, x2, y1, y2;
  21573. // (use the copyCoefficientsFrom() method instead of this operator)
  21574. const IIRFilter& operator= (const IIRFilter&);
  21575. };
  21576. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  21577. /********* End of inlined file: juce_IIRFilter.h *********/
  21578. #endif
  21579. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21580. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  21581. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21582. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21583. /**
  21584. A subclass of AudioPlayHead can supply information about the position and
  21585. status of a moving play head during audio playback.
  21586. One of these can be supplied to an AudioProcessor object so that it can find
  21587. out about the position of the audio that it is rendering.
  21588. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  21589. */
  21590. class JUCE_API AudioPlayHead
  21591. {
  21592. protected:
  21593. AudioPlayHead() {}
  21594. public:
  21595. virtual ~AudioPlayHead() {}
  21596. /** Frame rate types. */
  21597. enum FrameRateType
  21598. {
  21599. fps24 = 0,
  21600. fps25 = 1,
  21601. fps2997 = 2,
  21602. fps30 = 3,
  21603. fps2997drop = 4,
  21604. fps30drop = 5,
  21605. fpsUnknown = 99
  21606. };
  21607. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  21608. */
  21609. struct CurrentPositionInfo
  21610. {
  21611. /** The tempo in BPM */
  21612. double bpm;
  21613. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  21614. int timeSigNumerator;
  21615. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  21616. int timeSigDenominator;
  21617. /** The current play position, in seconds from the start of the edit. */
  21618. double timeInSeconds;
  21619. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  21620. double editOriginTime;
  21621. /** The current play position in pulses-per-quarter-note.
  21622. This is the number of quarter notes since the edit start.
  21623. */
  21624. double ppqPosition;
  21625. /** The position of the start of the last bar, in pulses-per-quarter-note.
  21626. This is the number of quarter notes from the start of the edit to the
  21627. start of the current bar.
  21628. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  21629. it's not available, the value will be 0.
  21630. */
  21631. double ppqPositionOfLastBarStart;
  21632. /** The video frame rate, if applicable. */
  21633. FrameRateType frameRate;
  21634. /** True if the transport is currently playing. */
  21635. bool isPlaying;
  21636. /** True if the transport is currently recording.
  21637. (When isRecording is true, then isPlaying will also be true).
  21638. */
  21639. bool isRecording;
  21640. };
  21641. /** Fills-in the given structure with details about the transport's
  21642. position at the start of the current processing block.
  21643. */
  21644. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  21645. };
  21646. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  21647. /********* End of inlined file: juce_AudioPlayHead.h *********/
  21648. #endif
  21649. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21650. /********* Start of inlined file: juce_AudioProcessor.h *********/
  21651. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21652. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21653. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  21654. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21655. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21656. class AudioProcessor;
  21657. /**
  21658. Base class for the component that acts as the GUI for an AudioProcessor.
  21659. Derive your editor component from this class, and create an instance of it
  21660. by overriding the AudioProcessor::createEditor() method.
  21661. @see AudioProcessor, GenericAudioProcessorEditor
  21662. */
  21663. class JUCE_API AudioProcessorEditor : public Component
  21664. {
  21665. protected:
  21666. /** Creates an editor for the specified processor.
  21667. */
  21668. AudioProcessorEditor (AudioProcessor* const owner);
  21669. public:
  21670. /** Destructor. */
  21671. ~AudioProcessorEditor();
  21672. /** Returns a pointer to the processor that this editor represents. */
  21673. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  21674. private:
  21675. AudioProcessor* const owner;
  21676. };
  21677. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21678. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  21679. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  21680. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21681. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21682. class AudioProcessor;
  21683. /**
  21684. Base class for listeners that want to know about changes to an AudioProcessor.
  21685. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  21686. @see AudioProcessor
  21687. */
  21688. class JUCE_API AudioProcessorListener
  21689. {
  21690. public:
  21691. /** Destructor. */
  21692. virtual ~AudioProcessorListener() {}
  21693. /** Receives a callback when a parameter is changed.
  21694. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  21695. many audio processors will change their parameter during their audio callback.
  21696. This means that not only has your handler code got to be completely thread-safe,
  21697. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  21698. this event on your message thread, use this callback to trigger an AsyncUpdater
  21699. or ChangeBroadcaster which you can respond to on the message thread.
  21700. */
  21701. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  21702. int parameterIndex,
  21703. float newValue) = 0;
  21704. /** Called to indicate that something else in the plugin has changed, like its
  21705. program, number of parameters, etc.
  21706. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  21707. call it during their audio callback. This means that not only has your handler code
  21708. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  21709. blocking. If you need to handle this event on your message thread, use this callback
  21710. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  21711. message thread.
  21712. */
  21713. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  21714. /** Indicates that a parameter change gesture has started.
  21715. E.g. if the user is dragging a slider, this would be called when they first
  21716. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  21717. called when they release it.
  21718. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  21719. call it during their audio callback. This means that not only has your handler code
  21720. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  21721. blocking. If you need to handle this event on your message thread, use this callback
  21722. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  21723. message thread.
  21724. @see audioProcessorParameterChangeGestureEnd
  21725. */
  21726. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  21727. int parameterIndex);
  21728. /** Indicates that a parameter change gesture has finished.
  21729. E.g. if the user is dragging a slider, this would be called when they release
  21730. the mouse button.
  21731. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  21732. call it during their audio callback. This means that not only has your handler code
  21733. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  21734. blocking. If you need to handle this event on your message thread, use this callback
  21735. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  21736. message thread.
  21737. @see audioPluginParameterChangeGestureStart
  21738. */
  21739. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  21740. int parameterIndex);
  21741. };
  21742. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21743. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  21744. /**
  21745. Base class for audio processing filters or plugins.
  21746. This is intended to act as a base class of audio filter that is general enough to
  21747. be wrapped as a VST, AU, RTAS, etc, or used internally.
  21748. It is also used by the plugin hosting code as the wrapper around an instance
  21749. of a loaded plugin.
  21750. Derive your filter class from this base class, and if you're building a plugin,
  21751. you should implement a global function called createPluginFilter() which creates
  21752. and returns a new instance of your subclass.
  21753. */
  21754. class JUCE_API AudioProcessor
  21755. {
  21756. protected:
  21757. /** Constructor.
  21758. You can also do your initialisation tasks in the initialiseFilterInfo()
  21759. call, which will be made after this object has been created.
  21760. */
  21761. AudioProcessor();
  21762. public:
  21763. /** Destructor. */
  21764. virtual ~AudioProcessor();
  21765. /** Returns the name of this processor.
  21766. */
  21767. virtual const String getName() const = 0;
  21768. /** Called before playback starts, to let the filter prepare itself.
  21769. The sample rate is the target sample rate, and will remain constant until
  21770. playback stops.
  21771. The estimatedSamplesPerBlock value is a HINT about the typical number of
  21772. samples that will be processed for each callback, but isn't any kind
  21773. of guarantee. The actual block sizes that the host uses may be different
  21774. each time the callback happens, and may be more or less than this value.
  21775. */
  21776. virtual void prepareToPlay (double sampleRate,
  21777. int estimatedSamplesPerBlock) = 0;
  21778. /** Called after playback has stopped, to let the filter free up any resources it
  21779. no longer needs.
  21780. */
  21781. virtual void releaseResources() = 0;
  21782. /** Renders the next block.
  21783. When this method is called, the buffer contains a number of channels which is
  21784. at least as great as the maximum number of input and output channels that
  21785. this filter is using. It will be filled with the filter's input data and
  21786. should be replaced with the filter's output.
  21787. So for example if your filter has 2 input channels and 4 output channels, then
  21788. the buffer will contain 4 channels, the first two being filled with the
  21789. input data. Your filter should read these, do its processing, and replace
  21790. the contents of all 4 channels with its output.
  21791. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  21792. all filled with data, and your filter should overwrite the first 2 of these
  21793. with its output. But be VERY careful not to write anything to the last 3
  21794. channels, as these might be mapped to memory that the host assumes is read-only!
  21795. Note that if you have more outputs than inputs, then only those channels that
  21796. correspond to an input channel are guaranteed to contain sensible data - e.g.
  21797. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  21798. but the last two channels may contain garbage, so you should be careful not to
  21799. let this pass through without being overwritten or cleared.
  21800. Also note that the buffer may have more channels than are strictly necessary,
  21801. but your should only read/write from the ones that your filter is supposed to
  21802. be using.
  21803. The number of samples in these buffers is NOT guaranteed to be the same for every
  21804. callback, and may be more or less than the estimated value given to prepareToPlay().
  21805. Your code must be able to cope with variable-sized blocks, or you're going to get
  21806. clicks and crashes!
  21807. If the filter is receiving a midi input, then the midiMessages array will be filled
  21808. with the midi messages for this block. Each message's timestamp will indicate the
  21809. message's time, as a number of samples from the start of the block.
  21810. Any messages left in the midi buffer when this method has finished are assumed to
  21811. be the filter's midi output. This means that your filter should be careful to
  21812. clear any incoming messages from the array if it doesn't want them to be passed-on.
  21813. Be very careful about what you do in this callback - it's going to be called by
  21814. the audio thread, so any kind of interaction with the UI is absolutely
  21815. out of the question. If you change a parameter in here and need to tell your UI to
  21816. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  21817. the UI components register as listeners, and then call sendChangeMessage() inside the
  21818. processBlock() method to send out an asynchronous message. You could also use
  21819. the AsyncUpdater class in a similar way.
  21820. */
  21821. virtual void processBlock (AudioSampleBuffer& buffer,
  21822. MidiBuffer& midiMessages) = 0;
  21823. /** Returns the current AudioPlayHead object that should be used to find
  21824. out the state and position of the playhead.
  21825. You can call this from your processBlock() method, and use the AudioPlayHead
  21826. object to get the details about the time of the start of the block currently
  21827. being processed.
  21828. If the host hasn't supplied a playhead object, this will return 0.
  21829. */
  21830. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  21831. /** Returns the current sample rate.
  21832. This can be called from your processBlock() method - it's not guaranteed
  21833. to be valid at any other time, and may return 0 if it's unknown.
  21834. */
  21835. double getSampleRate() const throw() { return sampleRate; }
  21836. /** Returns the current typical block size that is being used.
  21837. This can be called from your processBlock() method - it's not guaranteed
  21838. to be valid at any other time.
  21839. Remember it's not the ONLY block size that may be used when calling
  21840. processBlock, it's just the normal one. The actual block sizes used may be
  21841. larger or smaller than this, and will vary between successive calls.
  21842. */
  21843. int getBlockSize() const throw() { return blockSize; }
  21844. /** Returns the number of input channels that the host will be sending the filter.
  21845. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  21846. number of channels that your filter would prefer to have, and this method lets
  21847. you know how many the host is actually using.
  21848. Note that this method is only valid during or after the prepareToPlay()
  21849. method call. Until that point, the number of channels will be unknown.
  21850. */
  21851. int getNumInputChannels() const throw() { return numInputChannels; }
  21852. /** Returns the number of output channels that the host will be sending the filter.
  21853. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  21854. number of channels that your filter would prefer to have, and this method lets
  21855. you know how many the host is actually using.
  21856. Note that this method is only valid during or after the prepareToPlay()
  21857. method call. Until that point, the number of channels will be unknown.
  21858. */
  21859. int getNumOutputChannels() const throw() { return numOutputChannels; }
  21860. /** Returns the name of one of the input channels, as returned by the host.
  21861. The host might not supply very useful names for channels, and this might be
  21862. something like "1", "2", "left", "right", etc.
  21863. */
  21864. virtual const String getInputChannelName (const int channelIndex) const = 0;
  21865. /** Returns the name of one of the output channels, as returned by the host.
  21866. The host might not supply very useful names for channels, and this might be
  21867. something like "1", "2", "left", "right", etc.
  21868. */
  21869. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  21870. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  21871. virtual bool isInputChannelStereoPair (int index) const = 0;
  21872. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  21873. virtual bool isOutputChannelStereoPair (int index) const = 0;
  21874. /** This returns the number of samples delay that the filter imposes on the audio
  21875. passing through it.
  21876. The host will call this to find the latency - the filter itself should set this value
  21877. by calling setLatencySamples() as soon as it can during its initialisation.
  21878. */
  21879. int getLatencySamples() const throw() { return latencySamples; }
  21880. /** The filter should call this to set the number of samples delay that it introduces.
  21881. The filter should call this as soon as it can during initialisation, and can call it
  21882. later if the value changes.
  21883. */
  21884. void setLatencySamples (const int newLatency);
  21885. /** Returns true if the processor wants midi messages. */
  21886. virtual bool acceptsMidi() const = 0;
  21887. /** Returns true if the processor produces midi messages. */
  21888. virtual bool producesMidi() const = 0;
  21889. /** This returns a critical section that will automatically be locked while the host
  21890. is calling the processBlock() method.
  21891. Use it from your UI or other threads to lock access to variables that are used
  21892. by the process callback, but obviously be careful not to keep it locked for
  21893. too long, because that could cause stuttering playback. If you need to do something
  21894. that'll take a long time and need the processing to stop while it happens, use the
  21895. suspendProcessing() method instead.
  21896. @see suspendProcessing
  21897. */
  21898. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  21899. /** Enables and disables the processing callback.
  21900. If you need to do something time-consuming on a thread and would like to make sure
  21901. the audio processing callback doesn't happen until you've finished, use this
  21902. to disable the callback and re-enable it again afterwards.
  21903. E.g.
  21904. @code
  21905. void loadNewPatch()
  21906. {
  21907. suspendProcessing (true);
  21908. ..do something that takes ages..
  21909. suspendProcessing (false);
  21910. }
  21911. @endcode
  21912. If the host tries to make an audio callback while processing is suspended, the
  21913. filter will return an empty buffer, but won't block the audio thread like it would
  21914. do if you use the getCallbackLock() critical section to synchronise access.
  21915. If you're going to use this, your processBlock() method must call isSuspended() and
  21916. check whether it's suspended or not. If it is, then it should skip doing any real
  21917. processing, either emitting silence or passing the input through unchanged.
  21918. @see getCallbackLock
  21919. */
  21920. void suspendProcessing (const bool shouldBeSuspended);
  21921. /** Returns true if processing is currently suspended.
  21922. @see suspendProcessing
  21923. */
  21924. bool isSuspended() const throw() { return suspended; }
  21925. /** A plugin can override this to be told when it should reset any playing voices.
  21926. The default implementation does nothing, but a host may call this to tell the
  21927. plugin that it should stop any tails or sounds that have been left running.
  21928. */
  21929. virtual void reset();
  21930. /** Returns true if the processor is being run in an offline mode for rendering.
  21931. If the processor is being run live on realtime signals, this returns false.
  21932. If the mode is unknown, this will assume it's realtime and return false.
  21933. This value may be unreliable until the prepareToPlay() method has been called,
  21934. and could change each time prepareToPlay() is called.
  21935. @see setNonRealtime()
  21936. */
  21937. bool isNonRealtime() const throw() { return nonRealtime; }
  21938. /** Called by the host to tell this processor whether it's being used in a non-realime
  21939. capacity for offline rendering or bouncing.
  21940. Whatever value is passed-in will be
  21941. */
  21942. void setNonRealtime (const bool isNonRealtime) throw();
  21943. /** Creates the filter's UI.
  21944. This can return 0 if you want a UI-less filter, in which case the host may create
  21945. a generic UI that lets the user twiddle the parameters directly.
  21946. If you do want to pass back a component, the component should be created and set to
  21947. the correct size before returning it.
  21948. Remember not to do anything silly like allowing your filter to keep a pointer to
  21949. the component that gets created - it could be deleted later without any warning, which
  21950. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  21951. The correct way to handle the connection between an editor component and its
  21952. filter is to use something like a ChangeBroadcaster so that the editor can
  21953. register itself as a listener, and be told when a change occurs. This lets them
  21954. safely unregister themselves when they are deleted.
  21955. Here are a few things to bear in mind when writing an editor:
  21956. - Initially there won't be an editor, until the user opens one, or they might
  21957. not open one at all. Your filter mustn't rely on it being there.
  21958. - An editor object may be deleted and a replacement one created again at any time.
  21959. - It's safe to assume that an editor will be deleted before its filter.
  21960. */
  21961. virtual AudioProcessorEditor* createEditor() = 0;
  21962. /** Returns the active editor, if there is one.
  21963. Bear in mind this can return 0, even if an editor has previously been
  21964. opened.
  21965. */
  21966. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  21967. /** Returns the active editor, or if there isn't one, it will create one.
  21968. This may call createEditor() internally to create the component.
  21969. */
  21970. AudioProcessorEditor* createEditorIfNeeded();
  21971. /** This must return the correct value immediately after the object has been
  21972. created, and mustn't change the number of parameters later.
  21973. */
  21974. virtual int getNumParameters() = 0;
  21975. /** Returns the name of a particular parameter. */
  21976. virtual const String getParameterName (int parameterIndex) = 0;
  21977. /** Called by the host to find out the value of one of the filter's parameters.
  21978. The host will expect the value returned to be between 0 and 1.0.
  21979. This could be called quite frequently, so try to make your code efficient.
  21980. It's also likely to be called by non-UI threads, so the code in here should
  21981. be thread-aware.
  21982. */
  21983. virtual float getParameter (int parameterIndex) = 0;
  21984. /** Returns the value of a parameter as a text string. */
  21985. virtual const String getParameterText (int parameterIndex) = 0;
  21986. /** The host will call this method to change the value of one of the filter's parameters.
  21987. The host may call this at any time, including during the audio processing
  21988. callback, so the filter has to process this very fast and avoid blocking.
  21989. If you want to set the value of a parameter internally, e.g. from your
  21990. editor component, then don't call this directly - instead, use the
  21991. setParameterNotifyingHost() method, which will also send a message to
  21992. the host telling it about the change. If the message isn't sent, the host
  21993. won't be able to automate your parameters properly.
  21994. The value passed will be between 0 and 1.0.
  21995. */
  21996. virtual void setParameter (int parameterIndex,
  21997. float newValue) = 0;
  21998. /** Your filter can call this when it needs to change one of its parameters.
  21999. This could happen when the editor or some other internal operation changes
  22000. a parameter. This method will call the setParameter() method to change the
  22001. value, and will then send a message to the host telling it about the change.
  22002. Note that to make sure the host correctly handles automation, you should call
  22003. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  22004. tell the host when the user has started and stopped changing the parameter.
  22005. */
  22006. void setParameterNotifyingHost (int parameterIndex,
  22007. float newValue);
  22008. /** Returns true if the host can automate this parameter.
  22009. By default, this returns true for all parameters.
  22010. */
  22011. virtual bool isParameterAutomatable (int parameterIndex) const;
  22012. /** Should return true if this parameter is a "meta" parameter.
  22013. A meta-parameter is a parameter that changes other params. It is used
  22014. by some hosts (e.g. AudioUnit hosts).
  22015. By default this returns false.
  22016. */
  22017. virtual bool isMetaParameter (int parameterIndex) const;
  22018. /** Sends a signal to the host to tell it that the user is about to start changing this
  22019. parameter.
  22020. This allows the host to know when a parameter is actively being held by the user, and
  22021. it may use this information to help it record automation.
  22022. If you call this, it must be matched by a later call to endParameterChangeGesture().
  22023. */
  22024. void beginParameterChangeGesture (int parameterIndex);
  22025. /** Tells the host that the user has finished changing this parameter.
  22026. This allows the host to know when a parameter is actively being held by the user, and
  22027. it may use this information to help it record automation.
  22028. A call to this method must follow a call to beginParameterChangeGesture().
  22029. */
  22030. void endParameterChangeGesture (int parameterIndex);
  22031. /** The filter can call this when something (apart from a parameter value) has changed.
  22032. It sends a hint to the host that something like the program, number of parameters,
  22033. etc, has changed, and that it should update itself.
  22034. */
  22035. void updateHostDisplay();
  22036. /** Returns the number of preset programs the filter supports.
  22037. The value returned must be valid as soon as this object is created, and
  22038. must not change over its lifetime.
  22039. This value shouldn't be less than 1.
  22040. */
  22041. virtual int getNumPrograms() = 0;
  22042. /** Returns the number of the currently active program.
  22043. */
  22044. virtual int getCurrentProgram() = 0;
  22045. /** Called by the host to change the current program.
  22046. */
  22047. virtual void setCurrentProgram (int index) = 0;
  22048. /** Must return the name of a given program. */
  22049. virtual const String getProgramName (int index) = 0;
  22050. /** Called by the host to rename a program.
  22051. */
  22052. virtual void changeProgramName (int index, const String& newName) = 0;
  22053. /** The host will call this method when it wants to save the filter's internal state.
  22054. This must copy any info about the filter's state into the block of memory provided,
  22055. so that the host can store this and later restore it using setStateInformation().
  22056. Note that there's also a getCurrentProgramStateInformation() method, which only
  22057. stores the current program, not the state of the entire filter.
  22058. See also the helper function copyXmlToBinary() for storing settings as XML.
  22059. @see getCurrentProgramStateInformation
  22060. */
  22061. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  22062. /** The host will call this method if it wants to save the state of just the filter's
  22063. current program.
  22064. Unlike getStateInformation, this should only return the current program's state.
  22065. Not all hosts support this, and if you don't implement it, the base class
  22066. method just calls getStateInformation() instead. If you do implement it, be
  22067. sure to also implement getCurrentProgramStateInformation.
  22068. @see getStateInformation, setCurrentProgramStateInformation
  22069. */
  22070. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22071. /** This must restore the filter's state from a block of data previously created
  22072. using getStateInformation().
  22073. Note that there's also a setCurrentProgramStateInformation() method, which tries
  22074. to restore just the current program, not the state of the entire filter.
  22075. See also the helper function getXmlFromBinary() for loading settings as XML.
  22076. @see setCurrentProgramStateInformation
  22077. */
  22078. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  22079. /** The host will call this method if it wants to restore the state of just the filter's
  22080. current program.
  22081. Not all hosts support this, and if you don't implement it, the base class
  22082. method just calls setStateInformation() instead. If you do implement it, be
  22083. sure to also implement getCurrentProgramStateInformation.
  22084. @see setStateInformation, getCurrentProgramStateInformation
  22085. */
  22086. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22087. /** Adds a listener that will be called when an aspect of this processor changes. */
  22088. void addListener (AudioProcessorListener* const newListener) throw();
  22089. /** Removes a previously added listener. */
  22090. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  22091. /** Not for public use - this is called before deleting an editor component. */
  22092. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  22093. /** Not for public use - this is called to initialise the processor. */
  22094. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  22095. /** Not for public use - this is called to initialise the processor before playing. */
  22096. void setPlayConfigDetails (const int numIns, const int numOuts,
  22097. const double sampleRate,
  22098. const int blockSize) throw();
  22099. juce_UseDebuggingNewOperator
  22100. protected:
  22101. /** Helper function that just converts an xml element into a binary blob.
  22102. Use this in your filter's getStateInformation() method if you want to
  22103. store its state as xml.
  22104. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  22105. from a binary blob.
  22106. */
  22107. static void copyXmlToBinary (const XmlElement& xml,
  22108. JUCE_NAMESPACE::MemoryBlock& destData);
  22109. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  22110. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  22111. an XmlElement object that the caller must delete when no longer needed.
  22112. */
  22113. static XmlElement* getXmlFromBinary (const void* data,
  22114. const int sizeInBytes);
  22115. /** @internal */
  22116. AudioPlayHead* playHead;
  22117. /** @internal */
  22118. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  22119. private:
  22120. VoidArray listeners;
  22121. AudioProcessorEditor* activeEditor;
  22122. double sampleRate;
  22123. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  22124. bool suspended, nonRealtime;
  22125. CriticalSection callbackLock, listenerLock;
  22126. #ifdef JUCE_DEBUG
  22127. BitArray changingParams;
  22128. #endif
  22129. AudioProcessor (const AudioProcessor&);
  22130. const AudioProcessor& operator= (const AudioProcessor&);
  22131. };
  22132. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  22133. /********* End of inlined file: juce_AudioProcessor.h *********/
  22134. #endif
  22135. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  22136. #endif
  22137. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  22138. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  22139. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  22140. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  22141. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  22142. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  22143. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  22144. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  22145. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  22146. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  22147. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  22148. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  22149. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  22150. /********* Start of inlined file: juce_PluginDescription.h *********/
  22151. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  22152. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  22153. /**
  22154. A small class to represent some facts about a particular type of plugin.
  22155. This class is for storing and managing the details about a plugin without
  22156. actually having to load an instance of it.
  22157. A KnownPluginList contains a list of PluginDescription objects.
  22158. @see KnownPluginList
  22159. */
  22160. class JUCE_API PluginDescription
  22161. {
  22162. public:
  22163. PluginDescription() throw();
  22164. PluginDescription (const PluginDescription& other) throw();
  22165. const PluginDescription& operator= (const PluginDescription& other) throw();
  22166. ~PluginDescription() throw();
  22167. /** The name of the plugin. */
  22168. String name;
  22169. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  22170. */
  22171. String pluginFormatName;
  22172. /** A category, such as "Dynamics", "Reverbs", etc.
  22173. */
  22174. String category;
  22175. /** The manufacturer. */
  22176. String manufacturerName;
  22177. /** The version. This string doesn't have any particular format. */
  22178. String version;
  22179. /** Either the file containing the plugin module, or some other unique way
  22180. of identifying it.
  22181. E.g. for an AU, this would be an ID string that the component manager
  22182. could use to retrieve the plugin. For a VST, it's the file path.
  22183. */
  22184. String fileOrIdentifier;
  22185. /** The last time the plugin file was changed.
  22186. This is handy when scanning for new or changed plugins.
  22187. */
  22188. Time lastFileModTime;
  22189. /** A unique ID for the plugin.
  22190. Note that this might not be unique between formats, e.g. a VST and some
  22191. other format might actually have the same id.
  22192. @see createIdentifierString
  22193. */
  22194. int uid;
  22195. /** True if the plugin identifies itself as a synthesiser. */
  22196. bool isInstrument;
  22197. /** The number of inputs. */
  22198. int numInputChannels;
  22199. /** The number of outputs. */
  22200. int numOutputChannels;
  22201. /** Returns true if the two descriptions refer the the same plugin.
  22202. This isn't quite as simple as them just having the same file (because of
  22203. shell plugins).
  22204. */
  22205. bool isDuplicateOf (const PluginDescription& other) const;
  22206. /** Returns a string that can be saved and used to uniquely identify the
  22207. plugin again.
  22208. This contains less info than the XML encoding, and is independent of the
  22209. plugin's file location, so can be used to store a plugin ID for use
  22210. across different machines.
  22211. */
  22212. const String createIdentifierString() const throw();
  22213. /** Creates an XML object containing these details.
  22214. @see loadFromXml
  22215. */
  22216. XmlElement* createXml() const;
  22217. /** Reloads the info in this structure from an XML record that was previously
  22218. saved with createXML().
  22219. Returns true if the XML was a valid plugin description.
  22220. */
  22221. bool loadFromXml (const XmlElement& xml);
  22222. juce_UseDebuggingNewOperator
  22223. };
  22224. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  22225. /********* End of inlined file: juce_PluginDescription.h *********/
  22226. /**
  22227. Base class for an active instance of a plugin.
  22228. This derives from the AudioProcessor class, and adds some extra functionality
  22229. that helps when wrapping dynamically loaded plugins.
  22230. @see AudioProcessor, AudioPluginFormat
  22231. */
  22232. class JUCE_API AudioPluginInstance : public AudioProcessor
  22233. {
  22234. public:
  22235. /** Destructor.
  22236. Make sure that you delete any UI components that belong to this plugin before
  22237. deleting the plugin.
  22238. */
  22239. virtual ~AudioPluginInstance();
  22240. /** Fills-in the appropriate parts of this plugin description object.
  22241. */
  22242. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  22243. juce_UseDebuggingNewOperator
  22244. protected:
  22245. AudioPluginInstance();
  22246. AudioPluginInstance (const AudioPluginInstance&);
  22247. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  22248. };
  22249. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  22250. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  22251. class PluginDescription;
  22252. /**
  22253. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  22254. Use the static getNumFormats() and getFormat() calls to find the types
  22255. of format that are available.
  22256. */
  22257. class JUCE_API AudioPluginFormat
  22258. {
  22259. public:
  22260. /** Destructor. */
  22261. virtual ~AudioPluginFormat();
  22262. /** Returns the format name.
  22263. E.g. "VST", "AudioUnit", etc.
  22264. */
  22265. virtual const String getName() const = 0;
  22266. /** This tries to create descriptions for all the plugin types available in
  22267. a binary module file.
  22268. The file will be some kind of DLL or bundle.
  22269. Normally there will only be one type returned, but some plugins
  22270. (e.g. VST shells) can use a single DLL to create a set of different plugin
  22271. subtypes, so in that case, each subtype is returned as a separate object.
  22272. */
  22273. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  22274. const String& fileOrIdentifier) = 0;
  22275. /** Tries to recreate a type from a previously generated PluginDescription.
  22276. @see PluginDescription::createInstance
  22277. */
  22278. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  22279. /** Should do a quick check to see if this file or directory might be a plugin of
  22280. this format.
  22281. This is for searching for potential files, so it shouldn't actually try to
  22282. load the plugin or do anything time-consuming.
  22283. */
  22284. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  22285. /** Returns a readable version of the name of the plugin that this identifier refers to.
  22286. */
  22287. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  22288. /** Checks whether this plugin could possibly be loaded.
  22289. It doesn't actually need to load it, just to check whether the file or component
  22290. still exists.
  22291. */
  22292. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  22293. /** Searches a suggested set of directories for any plugins in this format.
  22294. The path might be ignored, e.g. by AUs, which are found by the OS rather
  22295. than manually.
  22296. */
  22297. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  22298. const bool recursive) = 0;
  22299. /** Returns the typical places to look for this kind of plugin.
  22300. Note that if this returns no paths, it means that the format can't be scanned-for
  22301. (i.e. it's an internal format that doesn't live in files)
  22302. */
  22303. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  22304. juce_UseDebuggingNewOperator
  22305. protected:
  22306. AudioPluginFormat() throw();
  22307. AudioPluginFormat (const AudioPluginFormat&);
  22308. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  22309. };
  22310. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  22311. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  22312. /**
  22313. This maintains a list of known AudioPluginFormats.
  22314. @see AudioPluginFormat
  22315. */
  22316. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  22317. {
  22318. public:
  22319. AudioPluginFormatManager() throw();
  22320. /** Destructor. */
  22321. ~AudioPluginFormatManager() throw();
  22322. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  22323. /** Adds any formats that it knows about, e.g. VST.
  22324. */
  22325. void addDefaultFormats();
  22326. /** Returns the number of types of format that are available.
  22327. Use getFormat() to get one of them.
  22328. */
  22329. int getNumFormats() throw();
  22330. /** Returns one of the available formats.
  22331. @see getNumFormats
  22332. */
  22333. AudioPluginFormat* getFormat (const int index) throw();
  22334. /** Adds a format to the list.
  22335. The object passed in will be owned and deleted by the manager.
  22336. */
  22337. void addFormat (AudioPluginFormat* const format) throw();
  22338. /** Tries to load the type for this description, by trying all the formats
  22339. that this manager knows about.
  22340. The caller is responsible for deleting the object that is returned.
  22341. If it can't load the plugin, it returns 0 and leaves a message in the
  22342. errorMessage string.
  22343. */
  22344. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  22345. String& errorMessage) const;
  22346. /** Checks that the file or component for this plugin actually still exists.
  22347. (This won't try to load the plugin)
  22348. */
  22349. bool doesPluginStillExist (const PluginDescription& description) const;
  22350. juce_UseDebuggingNewOperator
  22351. private:
  22352. OwnedArray <AudioPluginFormat> formats;
  22353. AudioPluginFormatManager (const AudioPluginFormatManager&);
  22354. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  22355. };
  22356. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  22357. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  22358. /********* Start of inlined file: juce_KnownPluginList.h *********/
  22359. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  22360. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  22361. /********* Start of inlined file: juce_PopupMenu.h *********/
  22362. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  22363. #define __JUCE_POPUPMENU_JUCEHEADER__
  22364. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  22365. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  22366. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  22367. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  22368. @see PopupMenu::addCustomItem
  22369. */
  22370. class JUCE_API PopupMenuCustomComponent : public Component
  22371. {
  22372. public:
  22373. /** Destructor. */
  22374. ~PopupMenuCustomComponent();
  22375. /** Chooses the size that this component would like to have.
  22376. Note that the size which this method returns isn't necessarily the one that
  22377. the menu will give it, as it will be stretched to fit the other items in
  22378. the menu.
  22379. */
  22380. virtual void getIdealSize (int& idealWidth,
  22381. int& idealHeight) = 0;
  22382. /** Dismisses the menu indicating that this item has been chosen.
  22383. This will cause the menu to exit from its modal state, returning
  22384. this item's id as the result.
  22385. */
  22386. void triggerMenuItem();
  22387. /** Returns true if this item should be highlighted because the mouse is
  22388. over it.
  22389. You can call this method in your paint() method to find out whether
  22390. to draw a highlight.
  22391. */
  22392. bool isItemHighlighted() const throw() { return isHighlighted; }
  22393. protected:
  22394. /** Constructor.
  22395. If isTriggeredAutomatically is true, then the menu will automatically detect
  22396. a click on this component and use that to trigger it. If it's false, then it's
  22397. up to your class to manually trigger the item if it wants to.
  22398. */
  22399. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  22400. private:
  22401. friend class MenuItemInfo;
  22402. friend class MenuItemComponent;
  22403. friend class PopupMenuWindow;
  22404. int refCount_;
  22405. bool isHighlighted, isTriggeredAutomatically;
  22406. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  22407. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  22408. };
  22409. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  22410. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  22411. /** Creates and displays a popup-menu.
  22412. To show a popup-menu, you create one of these, add some items to it, then
  22413. call its show() method, which returns the id of the item the user selects.
  22414. E.g. @code
  22415. void MyWidget::mouseDown (const MouseEvent& e)
  22416. {
  22417. PopupMenu m;
  22418. m.addItem (1, "item 1");
  22419. m.addItem (2, "item 2");
  22420. const int result = m.show();
  22421. if (result == 0)
  22422. {
  22423. // user dismissed the menu without picking anything
  22424. }
  22425. else if (result == 1)
  22426. {
  22427. // user picked item 1
  22428. }
  22429. else if (result == 2)
  22430. {
  22431. // user picked item 2
  22432. }
  22433. }
  22434. @endcode
  22435. Submenus are easy too: @code
  22436. void MyWidget::mouseDown (const MouseEvent& e)
  22437. {
  22438. PopupMenu subMenu;
  22439. subMenu.addItem (1, "item 1");
  22440. subMenu.addItem (2, "item 2");
  22441. PopupMenu mainMenu;
  22442. mainMenu.addItem (3, "item 3");
  22443. mainMenu.addSubMenu ("other choices", subMenu);
  22444. const int result = m.show();
  22445. ...etc
  22446. }
  22447. @endcode
  22448. */
  22449. class JUCE_API PopupMenu
  22450. {
  22451. public:
  22452. /** Creates an empty popup menu. */
  22453. PopupMenu() throw();
  22454. /** Creates a copy of another menu. */
  22455. PopupMenu (const PopupMenu& other) throw();
  22456. /** Destructor. */
  22457. ~PopupMenu() throw();
  22458. /** Copies this menu from another one. */
  22459. const PopupMenu& operator= (const PopupMenu& other) throw();
  22460. /** Resets the menu, removing all its items. */
  22461. void clear() throw();
  22462. /** Appends a new text item for this menu to show.
  22463. @param itemResultId the number that will be returned from the show() method
  22464. if the user picks this item. The value should never be
  22465. zero, because that's used to indicate that the user didn't
  22466. select anything.
  22467. @param itemText the text to show.
  22468. @param isActive if false, the item will be shown 'greyed-out' and can't be
  22469. picked
  22470. @param isTicked if true, the item will be shown with a tick next to it
  22471. @param iconToUse if this is non-zero, it should be an image that will be
  22472. displayed to the left of the item. This method will take its
  22473. own copy of the image passed-in, so there's no need to keep
  22474. it hanging around.
  22475. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  22476. */
  22477. void addItem (const int itemResultId,
  22478. const String& itemText,
  22479. const bool isActive = true,
  22480. const bool isTicked = false,
  22481. const Image* const iconToUse = 0) throw();
  22482. /** Adds an item that represents one of the commands in a command manager object.
  22483. @param commandManager the manager to use to trigger the command and get information
  22484. about it
  22485. @param commandID the ID of the command
  22486. @param displayName if this is non-empty, then this string will be used instead of
  22487. the command's registered name
  22488. */
  22489. void addCommandItem (ApplicationCommandManager* commandManager,
  22490. const int commandID,
  22491. const String& displayName = String::empty) throw();
  22492. /** Appends a text item with a special colour.
  22493. This is the same as addItem(), but specifies a colour to use for the
  22494. text, which will override the default colours that are used by the
  22495. current look-and-feel. See addItem() for a description of the parameters.
  22496. */
  22497. void addColouredItem (const int itemResultId,
  22498. const String& itemText,
  22499. const Colour& itemTextColour,
  22500. const bool isActive = true,
  22501. const bool isTicked = false,
  22502. const Image* const iconToUse = 0) throw();
  22503. /** Appends a custom menu item.
  22504. This will add a user-defined component to use as a menu item. The component
  22505. passed in will be deleted by this menu when it's no longer needed.
  22506. @see PopupMenuCustomComponent
  22507. */
  22508. void addCustomItem (const int itemResultId,
  22509. PopupMenuCustomComponent* const customComponent) throw();
  22510. /** Appends a custom menu item that can't be used to trigger a result.
  22511. This will add a user-defined component to use as a menu item. Unlike the
  22512. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  22513. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  22514. delete the component when it's finished, so it's the caller's responsibility
  22515. to manage the component that is passed-in.
  22516. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  22517. detection of a mouse-click on your component, and use that to trigger the
  22518. menu ID specified in itemResultId. If this is false, the menu item can't
  22519. be triggered, so itemResultId is not used.
  22520. @see PopupMenuCustomComponent
  22521. */
  22522. void addCustomItem (const int itemResultId,
  22523. Component* customComponent,
  22524. int idealWidth, int idealHeight,
  22525. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  22526. /** Appends a sub-menu.
  22527. If the menu that's passed in is empty, it will appear as an inactive item.
  22528. */
  22529. void addSubMenu (const String& subMenuName,
  22530. const PopupMenu& subMenu,
  22531. const bool isActive = true,
  22532. Image* const iconToUse = 0,
  22533. const bool isTicked = false) throw();
  22534. /** Appends a separator to the menu, to help break it up into sections.
  22535. The menu class is smart enough not to display separators at the top or bottom
  22536. of the menu, and it will replace mutliple adjacent separators with a single
  22537. one, so your code can be quite free and easy about adding these, and it'll
  22538. always look ok.
  22539. */
  22540. void addSeparator() throw();
  22541. /** Adds a non-clickable text item to the menu.
  22542. This is a bold-font items which can be used as a header to separate the items
  22543. into named groups.
  22544. */
  22545. void addSectionHeader (const String& title) throw();
  22546. /** Returns the number of items that the menu currently contains.
  22547. (This doesn't count separators).
  22548. */
  22549. int getNumItems() const throw();
  22550. /** Returns true if the menu contains a command item that triggers the given command. */
  22551. bool containsCommandItem (const int commandID) const throw();
  22552. /** Returns true if the menu contains any items that can be used. */
  22553. bool containsAnyActiveItems() const throw();
  22554. /** Displays the menu and waits for the user to pick something.
  22555. This will display the menu modally, and return the ID of the item that the
  22556. user picks. If they click somewhere off the menu to get rid of it without
  22557. choosing anything, this will return 0.
  22558. The current location of the mouse will be used as the position to show the
  22559. menu - to explicitly set the menu's position, use showAt() instead. Depending
  22560. on where this point is on the screen, the menu will appear above, below or
  22561. to the side of the point.
  22562. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  22563. then when the menu first appears, it will make sure
  22564. that this item is visible. So if the menu has too many
  22565. items to fit on the screen, it will be scrolled to a
  22566. position where this item is visible.
  22567. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  22568. than this if some items are too long to fit.
  22569. @param maximumNumColumns if there are too many items to fit on-screen in a single
  22570. vertical column, the menu may be laid out as a series of
  22571. columns - this is the maximum number allowed. To use the
  22572. default value for this (probably about 7), you can pass
  22573. in zero.
  22574. @param standardItemHeight if this is non-zero, it will be used as the standard
  22575. height for menu items (apart from custom items)
  22576. @see showAt
  22577. */
  22578. int show (const int itemIdThatMustBeVisible = 0,
  22579. const int minimumWidth = 0,
  22580. const int maximumNumColumns = 0,
  22581. const int standardItemHeight = 0);
  22582. /** Displays the menu at a specific location.
  22583. This is the same as show(), but uses a specific location (in global screen
  22584. co-ordinates) rather than the current mouse position.
  22585. Note that the co-ordinates don't specify the top-left of the menu - they
  22586. indicate a point of interest, and the menu will position itself nearby to
  22587. this point, trying to keep it fully on-screen.
  22588. @see show()
  22589. */
  22590. int showAt (const int screenX,
  22591. const int screenY,
  22592. const int itemIdThatMustBeVisible = 0,
  22593. const int minimumWidth = 0,
  22594. const int maximumNumColumns = 0,
  22595. const int standardItemHeight = 0);
  22596. /** Displays the menu as if it's attached to a component such as a button.
  22597. This is similar to showAt(), but will position it next to the given component, e.g.
  22598. so that the menu's edge is aligned with that of the component. This is intended for
  22599. things like buttons that trigger a pop-up menu.
  22600. */
  22601. int showAt (Component* componentToAttachTo,
  22602. const int itemIdThatMustBeVisible = 0,
  22603. const int minimumWidth = 0,
  22604. const int maximumNumColumns = 0,
  22605. const int standardItemHeight = 0);
  22606. /** Closes any menus that are currently open.
  22607. This might be useful if you have a situation where your window is being closed
  22608. by some means other than a user action, and you'd like to make sure that menus
  22609. aren't left hanging around.
  22610. */
  22611. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  22612. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  22613. This can be called before show() if you need a customised menu. Be careful
  22614. not to delete the LookAndFeel object before the menu has been deleted.
  22615. */
  22616. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  22617. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  22618. These constants can be used either via the LookAndFeel::setColour()
  22619. method for the look and feel that is set for this menu with setLookAndFeel()
  22620. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  22621. */
  22622. enum ColourIds
  22623. {
  22624. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  22625. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  22626. colour is specified when the item is added). */
  22627. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  22628. addSectionHeader() method). */
  22629. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  22630. highlighted menu item. */
  22631. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  22632. highlighted item. */
  22633. };
  22634. /**
  22635. Allows you to iterate through the items in a pop-up menu, and examine
  22636. their properties.
  22637. To use this, just create one and repeatedly call its next() method. When this
  22638. returns true, all the member variables of the iterator are filled-out with
  22639. information describing the menu item. When it returns false, the end of the
  22640. list has been reached.
  22641. */
  22642. class JUCE_API MenuItemIterator
  22643. {
  22644. public:
  22645. /** Creates an iterator that will scan through the items in the specified
  22646. menu.
  22647. Be careful not to add any items to a menu while it is being iterated,
  22648. or things could get out of step.
  22649. */
  22650. MenuItemIterator (const PopupMenu& menu) throw();
  22651. /** Destructor. */
  22652. ~MenuItemIterator() throw();
  22653. /** Returns true if there is another item, and sets up all this object's
  22654. member variables to reflect that item's properties.
  22655. */
  22656. bool next() throw();
  22657. String itemName;
  22658. const PopupMenu* subMenu;
  22659. int itemId;
  22660. bool isSeparator;
  22661. bool isTicked;
  22662. bool isEnabled;
  22663. bool isCustomComponent;
  22664. bool isSectionHeader;
  22665. const Colour* customColour;
  22666. const Image* customImage;
  22667. ApplicationCommandManager* commandManager;
  22668. juce_UseDebuggingNewOperator
  22669. private:
  22670. const PopupMenu& menu;
  22671. int index;
  22672. MenuItemIterator (const MenuItemIterator&);
  22673. const MenuItemIterator& operator= (const MenuItemIterator&);
  22674. };
  22675. juce_UseDebuggingNewOperator
  22676. private:
  22677. friend class PopupMenuWindow;
  22678. friend class MenuItemIterator;
  22679. VoidArray items;
  22680. LookAndFeel* lookAndFeel;
  22681. bool separatorPending;
  22682. void addSeparatorIfPending();
  22683. int showMenu (const int x, const int y, const int w, const int h,
  22684. const int itemIdThatMustBeVisible,
  22685. const int minimumWidth,
  22686. const int maximumNumColumns,
  22687. const int standardItemHeight,
  22688. const bool alignToRectangle,
  22689. Component* const componentAttachedTo) throw();
  22690. friend class MenuBarComponent;
  22691. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  22692. const int itemIdThatMustBeVisible,
  22693. const int minimumWidth,
  22694. const int maximumNumColumns,
  22695. const int standardItemHeight,
  22696. const bool alignToRectangle,
  22697. Component* menuBarComponent,
  22698. ApplicationCommandManager** managerOfChosenCommand,
  22699. Component* const componentAttachedTo) throw();
  22700. };
  22701. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  22702. /********* End of inlined file: juce_PopupMenu.h *********/
  22703. /**
  22704. Manages a list of plugin types.
  22705. This can be easily edited, saved and loaded, and used to create instances of
  22706. the plugin types in it.
  22707. @see PluginListComponent
  22708. */
  22709. class JUCE_API KnownPluginList : public ChangeBroadcaster
  22710. {
  22711. public:
  22712. /** Creates an empty list.
  22713. */
  22714. KnownPluginList();
  22715. /** Destructor. */
  22716. ~KnownPluginList();
  22717. /** Clears the list. */
  22718. void clear();
  22719. /** Returns the number of types currently in the list.
  22720. @see getType
  22721. */
  22722. int getNumTypes() const throw() { return types.size(); }
  22723. /** Returns one of the types.
  22724. @see getNumTypes
  22725. */
  22726. PluginDescription* getType (const int index) const throw() { return types [index]; }
  22727. /** Looks for a type in the list which comes from this file.
  22728. */
  22729. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  22730. /** Looks for a type in the list which matches a plugin type ID.
  22731. The identifierString parameter must have been created by
  22732. PluginDescription::createIdentifierString().
  22733. */
  22734. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  22735. /** Adds a type manually from its description. */
  22736. bool addType (const PluginDescription& type);
  22737. /** Removes a type. */
  22738. void removeType (const int index) throw();
  22739. /** Looks for all types that can be loaded from a given file, and adds them
  22740. to the list.
  22741. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  22742. re-tested if it's not already in the list, or if the file's modification
  22743. time has changed since the list was created. If dontRescanIfAlreadyInList is
  22744. false, the file will always be reloaded and tested.
  22745. Returns true if any new types were added, and all the types found in this
  22746. file (even if it was already known and hasn't been re-scanned) get returned
  22747. in the array.
  22748. */
  22749. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  22750. const bool dontRescanIfAlreadyInList,
  22751. OwnedArray <PluginDescription>& typesFound,
  22752. AudioPluginFormat& formatToUse);
  22753. /** Returns true if the specified file is already known about and if it
  22754. hasn't been modified since our entry was created.
  22755. */
  22756. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  22757. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  22758. If any types are found in the files, their descriptions are returned in the array.
  22759. */
  22760. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  22761. OwnedArray <PluginDescription>& typesFound);
  22762. /** Sort methods used to change the order of the plugins in the list.
  22763. */
  22764. enum SortMethod
  22765. {
  22766. defaultOrder = 0,
  22767. sortAlphabetically,
  22768. sortByCategory,
  22769. sortByManufacturer,
  22770. sortByFileSystemLocation
  22771. };
  22772. /** Adds all the plugin types to a popup menu so that the user can select one.
  22773. Depending on the sort method, it may add sub-menus for categories,
  22774. manufacturers, etc.
  22775. Use getIndexChosenByMenu() to find out the type that was chosen.
  22776. */
  22777. void addToMenu (PopupMenu& menu,
  22778. const SortMethod sortMethod) const;
  22779. /** Converts a menu item index that has been chosen into its index in this list.
  22780. Returns -1 if it's not an ID that was used.
  22781. @see addToMenu
  22782. */
  22783. int getIndexChosenByMenu (const int menuResultCode) const;
  22784. /** Sorts the list. */
  22785. void sort (const SortMethod method);
  22786. /** Creates some XML that can be used to store the state of this list.
  22787. */
  22788. XmlElement* createXml() const;
  22789. /** Recreates the state of this list from its stored XML format.
  22790. */
  22791. void recreateFromXml (const XmlElement& xml);
  22792. juce_UseDebuggingNewOperator
  22793. private:
  22794. OwnedArray <PluginDescription> types;
  22795. KnownPluginList (const KnownPluginList&);
  22796. const KnownPluginList& operator= (const KnownPluginList&);
  22797. };
  22798. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  22799. /********* End of inlined file: juce_KnownPluginList.h *********/
  22800. /**
  22801. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  22802. Use one of these objects if you want to wire-up a set of AudioProcessors
  22803. and play back the result.
  22804. Processors can be added to the graph as "nodes" using addNode(), and once
  22805. added, you can connect any of their input or output channels to other
  22806. nodes using addConnection().
  22807. To play back a graph through an audio device, you might want to use an
  22808. AudioProcessorPlayer object.
  22809. */
  22810. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  22811. public AsyncUpdater
  22812. {
  22813. public:
  22814. /** Creates an empty graph.
  22815. */
  22816. AudioProcessorGraph();
  22817. /** Destructor.
  22818. Any processor objects that have been added to the graph will also be deleted.
  22819. */
  22820. ~AudioProcessorGraph();
  22821. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  22822. To create a node, call AudioProcessorGraph::addNode().
  22823. */
  22824. class JUCE_API Node : public ReferenceCountedObject
  22825. {
  22826. public:
  22827. /** Destructor.
  22828. */
  22829. ~Node();
  22830. /** The ID number assigned to this node.
  22831. This is assigned by the graph that owns it, and can't be changed.
  22832. */
  22833. const uint32 id;
  22834. /** The actual processor object that this node represents.
  22835. */
  22836. AudioProcessor* const processor;
  22837. /** A set of user-definable properties that are associated with this node.
  22838. This can be used to attach values to the node for whatever purpose seems
  22839. useful. For example, you might store an x and y position if your application
  22840. is displaying the nodes on-screen.
  22841. */
  22842. PropertySet properties;
  22843. /** A convenient typedef for referring to a pointer to a node object.
  22844. */
  22845. typedef ReferenceCountedObjectPtr <Node> Ptr;
  22846. juce_UseDebuggingNewOperator
  22847. private:
  22848. friend class AudioProcessorGraph;
  22849. bool isPrepared;
  22850. Node (const uint32 id, AudioProcessor* const processor) throw();
  22851. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  22852. void unprepare();
  22853. Node (const Node&);
  22854. const Node& operator= (const Node&);
  22855. };
  22856. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  22857. To create a connection, use AudioProcessorGraph::addConnection().
  22858. */
  22859. struct JUCE_API Connection
  22860. {
  22861. public:
  22862. /** The ID number of the node which is the input source for this connection.
  22863. @see AudioProcessorGraph::getNodeForId
  22864. */
  22865. uint32 sourceNodeId;
  22866. /** The index of the output channel of the source node from which this
  22867. connection takes its data.
  22868. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  22869. it is referring to the source node's midi output. Otherwise, it is the zero-based
  22870. index of an audio output channel in the source node.
  22871. */
  22872. int sourceChannelIndex;
  22873. /** The ID number of the node which is the destination for this connection.
  22874. @see AudioProcessorGraph::getNodeForId
  22875. */
  22876. uint32 destNodeId;
  22877. /** The index of the input channel of the destination node to which this
  22878. connection delivers its data.
  22879. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  22880. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  22881. index of an audio input channel in the destination node.
  22882. */
  22883. int destChannelIndex;
  22884. juce_UseDebuggingNewOperator
  22885. private:
  22886. };
  22887. /** Deletes all nodes and connections from this graph.
  22888. Any processor objects in the graph will be deleted.
  22889. */
  22890. void clear();
  22891. /** Returns the number of nodes in the graph. */
  22892. int getNumNodes() const throw() { return nodes.size(); }
  22893. /** Returns a pointer to one of the nodes in the graph.
  22894. This will return 0 if the index is out of range.
  22895. @see getNodeForId
  22896. */
  22897. Node* getNode (const int index) const throw() { return nodes [index]; }
  22898. /** Searches the graph for a node with the given ID number and returns it.
  22899. If no such node was found, this returns 0.
  22900. @see getNode
  22901. */
  22902. Node* getNodeForId (const uint32 nodeId) const throw();
  22903. /** Adds a node to the graph.
  22904. This creates a new node in the graph, for the specified processor. Once you have
  22905. added a processor to the graph, the graph owns it and will delete it later when
  22906. it is no longer needed.
  22907. The optional nodeId parameter lets you specify an ID to use for the node, but
  22908. if the value is already in use, this new node will overwrite the old one.
  22909. If this succeeds, it returns a pointer to the newly-created node.
  22910. */
  22911. Node* addNode (AudioProcessor* const newProcessor,
  22912. uint32 nodeId = 0);
  22913. /** Deletes a node within the graph which has the specified ID.
  22914. This will also delete any connections that are attached to this node.
  22915. */
  22916. bool removeNode (const uint32 nodeId);
  22917. /** Returns the number of connections in the graph. */
  22918. int getNumConnections() const throw() { return connections.size(); }
  22919. /** Returns a pointer to one of the connections in the graph. */
  22920. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  22921. /** Searches for a connection between some specified channels.
  22922. If no such connection is found, this returns 0.
  22923. */
  22924. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  22925. const int sourceChannelIndex,
  22926. const uint32 destNodeId,
  22927. const int destChannelIndex) const throw();
  22928. /** Returns true if there is a connection between any of the channels of
  22929. two specified nodes.
  22930. */
  22931. bool isConnected (const uint32 possibleSourceNodeId,
  22932. const uint32 possibleDestNodeId) const throw();
  22933. /** Returns true if it would be legal to connect the specified points.
  22934. */
  22935. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  22936. const uint32 destNodeId, const int destChannelIndex) const throw();
  22937. /** Attempts to connect two specified channels of two nodes.
  22938. If this isn't allowed (e.g. because you're trying to connect a midi channel
  22939. to an audio one or other such nonsense), then it'll return false.
  22940. */
  22941. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22942. const uint32 destNodeId, const int destChannelIndex);
  22943. /** Deletes the connection with the specified index.
  22944. Returns true if a connection was actually deleted.
  22945. */
  22946. void removeConnection (const int index);
  22947. /** Deletes any connection between two specified points.
  22948. Returns true if a connection was actually deleted.
  22949. */
  22950. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22951. const uint32 destNodeId, const int destChannelIndex);
  22952. /** Removes all connections from the specified node.
  22953. */
  22954. bool disconnectNode (const uint32 nodeId);
  22955. /** Performs a sanity checks of all the connections.
  22956. This might be useful if some of the processors are doing things like changing
  22957. their channel counts, which could render some connections obsolete.
  22958. */
  22959. bool removeIllegalConnections();
  22960. /** A special number that represents the midi channel of a node.
  22961. This is used as a channel index value if you want to refer to the midi input
  22962. or output instead of an audio channel.
  22963. */
  22964. static const int midiChannelIndex;
  22965. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  22966. in order to use the audio that comes into and out of the graph itself.
  22967. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  22968. node in the graph which delivers the audio that is coming into the parent
  22969. graph. This allows you to stream the data to other nodes and process the
  22970. incoming audio.
  22971. Likewise, one of these in "output" mode can be sent data which it will add to
  22972. the sum of data being sent to the graph's output.
  22973. @see AudioProcessorGraph
  22974. */
  22975. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  22976. {
  22977. public:
  22978. /** Specifies the mode in which this processor will operate.
  22979. */
  22980. enum IODeviceType
  22981. {
  22982. audioInputNode, /**< In this mode, the processor has output channels
  22983. representing all the audio input channels that are
  22984. coming into its parent audio graph. */
  22985. audioOutputNode, /**< In this mode, the processor has input channels
  22986. representing all the audio output channels that are
  22987. going out of its parent audio graph. */
  22988. midiInputNode, /**< In this mode, the processor has a midi output which
  22989. delivers the same midi data that is arriving at its
  22990. parent graph. */
  22991. midiOutputNode /**< In this mode, the processor has a midi input and
  22992. any data sent to it will be passed out of the parent
  22993. graph. */
  22994. };
  22995. /** Returns the mode of this processor. */
  22996. IODeviceType getType() const throw() { return type; }
  22997. /** Returns the parent graph to which this processor belongs, or 0 if it
  22998. hasn't yet been added to one. */
  22999. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  23000. /** True if this is an audio or midi input. */
  23001. bool isInput() const throw();
  23002. /** True if this is an audio or midi output. */
  23003. bool isOutput() const throw();
  23004. AudioGraphIOProcessor (const IODeviceType type);
  23005. ~AudioGraphIOProcessor();
  23006. const String getName() const;
  23007. void fillInPluginDescription (PluginDescription& d) const;
  23008. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23009. void releaseResources();
  23010. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  23011. const String getInputChannelName (const int channelIndex) const;
  23012. const String getOutputChannelName (const int channelIndex) const;
  23013. bool isInputChannelStereoPair (int index) const;
  23014. bool isOutputChannelStereoPair (int index) const;
  23015. bool acceptsMidi() const;
  23016. bool producesMidi() const;
  23017. AudioProcessorEditor* createEditor();
  23018. int getNumParameters();
  23019. const String getParameterName (int);
  23020. float getParameter (int);
  23021. const String getParameterText (int);
  23022. void setParameter (int, float);
  23023. int getNumPrograms();
  23024. int getCurrentProgram();
  23025. void setCurrentProgram (int);
  23026. const String getProgramName (int);
  23027. void changeProgramName (int, const String&);
  23028. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  23029. void setStateInformation (const void* data, int sizeInBytes);
  23030. /** @internal */
  23031. void setParentGraph (AudioProcessorGraph* const graph) throw();
  23032. juce_UseDebuggingNewOperator
  23033. private:
  23034. const IODeviceType type;
  23035. AudioProcessorGraph* graph;
  23036. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  23037. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  23038. };
  23039. // AudioProcessor methods:
  23040. const String getName() const;
  23041. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23042. void releaseResources();
  23043. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  23044. const String getInputChannelName (const int channelIndex) const;
  23045. const String getOutputChannelName (const int channelIndex) const;
  23046. bool isInputChannelStereoPair (int index) const;
  23047. bool isOutputChannelStereoPair (int index) const;
  23048. bool acceptsMidi() const;
  23049. bool producesMidi() const;
  23050. AudioProcessorEditor* createEditor() { return 0; }
  23051. int getNumParameters() { return 0; }
  23052. const String getParameterName (int) { return String::empty; }
  23053. float getParameter (int) { return 0; }
  23054. const String getParameterText (int) { return String::empty; }
  23055. void setParameter (int, float) { }
  23056. int getNumPrograms() { return 0; }
  23057. int getCurrentProgram() { return 0; }
  23058. void setCurrentProgram (int) { }
  23059. const String getProgramName (int) { return String::empty; }
  23060. void changeProgramName (int, const String&) { }
  23061. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  23062. void setStateInformation (const void* data, int sizeInBytes);
  23063. /** @internal */
  23064. void handleAsyncUpdate();
  23065. juce_UseDebuggingNewOperator
  23066. private:
  23067. ReferenceCountedArray <Node> nodes;
  23068. OwnedArray <Connection> connections;
  23069. int lastNodeId;
  23070. AudioSampleBuffer renderingBuffers;
  23071. OwnedArray <MidiBuffer> midiBuffers;
  23072. CriticalSection renderLock;
  23073. VoidArray renderingOps;
  23074. friend class AudioGraphIOProcessor;
  23075. AudioSampleBuffer* currentAudioInputBuffer;
  23076. AudioSampleBuffer currentAudioOutputBuffer;
  23077. MidiBuffer* currentMidiInputBuffer;
  23078. MidiBuffer currentMidiOutputBuffer;
  23079. void clearRenderingSequence();
  23080. void buildRenderingSequence();
  23081. bool isAnInputTo (const uint32 possibleInputId,
  23082. const uint32 possibleDestinationId,
  23083. const int recursionCheck) const throw();
  23084. AudioProcessorGraph (const AudioProcessorGraph&);
  23085. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  23086. };
  23087. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  23088. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  23089. #endif
  23090. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  23091. #endif
  23092. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  23093. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  23094. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  23095. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  23096. /********* Start of inlined file: juce_AudioIODevice.h *********/
  23097. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23098. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23099. class AudioIODevice;
  23100. /**
  23101. One of these is passed to an AudioIODevice object to stream the audio data
  23102. in and out.
  23103. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  23104. method on its own high-priority audio thread, when it needs to send or receive
  23105. the next block of data.
  23106. @see AudioIODevice, AudioDeviceManager
  23107. */
  23108. class JUCE_API AudioIODeviceCallback
  23109. {
  23110. public:
  23111. /** Destructor. */
  23112. virtual ~AudioIODeviceCallback() {}
  23113. /** Processes a block of incoming and outgoing audio data.
  23114. The subclass's implementation should use the incoming audio for whatever
  23115. purposes it needs to, and must fill all the output channels with the next
  23116. block of output data before returning.
  23117. The channel data is arranged with the same array indices as the channel name
  23118. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  23119. that aren't specified in AudioIODevice::open() will have a null pointer for their
  23120. associated channel, so remember to check for this.
  23121. @param inputChannelData a set of arrays containing the audio data for each
  23122. incoming channel - this data is valid until the function
  23123. returns. There will be one channel of data for each input
  23124. channel that was enabled when the audio device was opened
  23125. (see AudioIODevice::open())
  23126. @param numInputChannels the number of pointers to channel data in the
  23127. inputChannelData array.
  23128. @param outputChannelData a set of arrays which need to be filled with the data
  23129. that should be sent to each outgoing channel of the device.
  23130. There will be one channel of data for each output channel
  23131. that was enabled when the audio device was opened (see
  23132. AudioIODevice::open())
  23133. The initial contents of the array is undefined, so the
  23134. callback function must fill all the channels with zeros if
  23135. its output is silence. Failing to do this could cause quite
  23136. an unpleasant noise!
  23137. @param numOutputChannels the number of pointers to channel data in the
  23138. outputChannelData array.
  23139. @param numSamples the number of samples in each channel of the input and
  23140. output arrays. The number of samples will depend on the
  23141. audio device's buffer size and will usually remain constant,
  23142. although this isn't guaranteed, so make sure your code can
  23143. cope with reasonable changes in the buffer size from one
  23144. callback to the next.
  23145. */
  23146. virtual void audioDeviceIOCallback (const float** inputChannelData,
  23147. int numInputChannels,
  23148. float** outputChannelData,
  23149. int numOutputChannels,
  23150. int numSamples) = 0;
  23151. /** Called to indicate that the device is about to start calling back.
  23152. This will be called just before the audio callbacks begin, either when this
  23153. callback has just been added to an audio device, or after the device has been
  23154. restarted because of a sample-rate or block-size change.
  23155. You can use this opportunity to find out the sample rate and block size
  23156. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23157. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23158. @param device the audio IO device that will be used to drive the callback.
  23159. Note that if you're going to store this this pointer, it is
  23160. only valid until the next time that audioDeviceStopped is called.
  23161. */
  23162. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23163. /** Called to indicate that the device has stopped.
  23164. */
  23165. virtual void audioDeviceStopped() = 0;
  23166. };
  23167. /**
  23168. Base class for an audio device with synchronised input and output channels.
  23169. Subclasses of this are used to implement different protocols such as DirectSound,
  23170. ASIO, CoreAudio, etc.
  23171. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23172. documentation for that class for more info.
  23173. For an easier way of managing audio devices and their settings, have a look at the
  23174. AudioDeviceManager class.
  23175. @see AudioIODeviceType, AudioDeviceManager
  23176. */
  23177. class JUCE_API AudioIODevice
  23178. {
  23179. public:
  23180. /** Destructor. */
  23181. virtual ~AudioIODevice();
  23182. /** Returns the device's name, (as set in the constructor). */
  23183. const String& getName() const throw() { return name; }
  23184. /** Returns the type of the device.
  23185. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23186. */
  23187. const String& getTypeName() const throw() { return typeName; }
  23188. /** Returns the names of all the available output channels on this device.
  23189. To find out which of these are currently in use, call getActiveOutputChannels().
  23190. */
  23191. virtual const StringArray getOutputChannelNames() = 0;
  23192. /** Returns the names of all the available input channels on this device.
  23193. To find out which of these are currently in use, call getActiveInputChannels().
  23194. */
  23195. virtual const StringArray getInputChannelNames() = 0;
  23196. /** Returns the number of sample-rates this device supports.
  23197. To find out which rates are available on this device, use this method to
  23198. find out how many there are, and getSampleRate() to get the rates.
  23199. @see getSampleRate
  23200. */
  23201. virtual int getNumSampleRates() = 0;
  23202. /** Returns one of the sample-rates this device supports.
  23203. To find out which rates are available on this device, use getNumSampleRates() to
  23204. find out how many there are, and getSampleRate() to get the individual rates.
  23205. The sample rate is set by the open() method.
  23206. (Note that for DirectSound some rates might not work, depending on combinations
  23207. of i/o channels that are being opened).
  23208. @see getNumSampleRates
  23209. */
  23210. virtual double getSampleRate (int index) = 0;
  23211. /** Returns the number of sizes of buffer that are available.
  23212. @see getBufferSizeSamples, getDefaultBufferSize
  23213. */
  23214. virtual int getNumBufferSizesAvailable() = 0;
  23215. /** Returns one of the possible buffer-sizes.
  23216. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23217. @returns a number of samples
  23218. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23219. */
  23220. virtual int getBufferSizeSamples (int index) = 0;
  23221. /** Returns the default buffer-size to use.
  23222. @returns a number of samples
  23223. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23224. */
  23225. virtual int getDefaultBufferSize() = 0;
  23226. /** Tries to open the device ready to play.
  23227. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  23228. input channel should be enabled
  23229. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  23230. output channel should be enabled
  23231. @param sampleRate the sample rate to try to use - to find out which rates are
  23232. available, see getNumSampleRates() and getSampleRate()
  23233. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23234. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23235. @returns an error description if there's a problem, or an empty string if it succeeds in
  23236. opening the device
  23237. @see close
  23238. */
  23239. virtual const String open (const BitArray& inputChannels,
  23240. const BitArray& outputChannels,
  23241. double sampleRate,
  23242. int bufferSizeSamples) = 0;
  23243. /** Closes and releases the device if it's open. */
  23244. virtual void close() = 0;
  23245. /** Returns true if the device is still open.
  23246. A device might spontaneously close itself if something goes wrong, so this checks if
  23247. it's still open.
  23248. */
  23249. virtual bool isOpen() = 0;
  23250. /** Starts the device actually playing.
  23251. This must be called after the device has been opened.
  23252. @param callback the callback to use for streaming the data.
  23253. @see AudioIODeviceCallback, open
  23254. */
  23255. virtual void start (AudioIODeviceCallback* callback) = 0;
  23256. /** Stops the device playing.
  23257. Once a device has been started, this will stop it. Any pending calls to the
  23258. callback class will be flushed before this method returns.
  23259. */
  23260. virtual void stop() = 0;
  23261. /** Returns true if the device is still calling back.
  23262. The device might mysteriously stop, so this checks whether it's
  23263. still playing.
  23264. */
  23265. virtual bool isPlaying() = 0;
  23266. /** Returns the last error that happened if anything went wrong. */
  23267. virtual const String getLastError() = 0;
  23268. /** Returns the buffer size that the device is currently using.
  23269. If the device isn't actually open, this value doesn't really mean much.
  23270. */
  23271. virtual int getCurrentBufferSizeSamples() = 0;
  23272. /** Returns the sample rate that the device is currently using.
  23273. If the device isn't actually open, this value doesn't really mean much.
  23274. */
  23275. virtual double getCurrentSampleRate() = 0;
  23276. /** Returns the device's current physical bit-depth.
  23277. If the device isn't actually open, this value doesn't really mean much.
  23278. */
  23279. virtual int getCurrentBitDepth() = 0;
  23280. /** Returns a mask showing which of the available output channels are currently
  23281. enabled.
  23282. @see getOutputChannelNames
  23283. */
  23284. virtual const BitArray getActiveOutputChannels() const = 0;
  23285. /** Returns a mask showing which of the available input channels are currently
  23286. enabled.
  23287. @see getInputChannelNames
  23288. */
  23289. virtual const BitArray getActiveInputChannels() const = 0;
  23290. /** Returns the device's output latency.
  23291. This is the delay in samples between a callback getting a block of data, and
  23292. that data actually getting played.
  23293. */
  23294. virtual int getOutputLatencyInSamples() = 0;
  23295. /** Returns the device's input latency.
  23296. This is the delay in samples between some audio actually arriving at the soundcard,
  23297. and the callback getting passed this block of data.
  23298. */
  23299. virtual int getInputLatencyInSamples() = 0;
  23300. /** True if this device can show a pop-up control panel for editing its settings.
  23301. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23302. to display it.
  23303. */
  23304. virtual bool hasControlPanel() const;
  23305. /** Shows a device-specific control panel if there is one.
  23306. This should only be called for devices which return true from hasControlPanel().
  23307. */
  23308. virtual bool showControlPanel();
  23309. protected:
  23310. /** Creates a device, setting its name and type member variables. */
  23311. AudioIODevice (const String& deviceName,
  23312. const String& typeName);
  23313. /** @internal */
  23314. String name, typeName;
  23315. };
  23316. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23317. /********* End of inlined file: juce_AudioIODevice.h *********/
  23318. /**
  23319. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  23320. To use one of these, just make it the callback used by your AudioIODevice, and
  23321. give it a processor to use by calling setProcessor().
  23322. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  23323. input to send both streams through the processor.
  23324. @see AudioProcessor, AudioProcessorGraph
  23325. */
  23326. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  23327. public MidiInputCallback
  23328. {
  23329. public:
  23330. /**
  23331. */
  23332. AudioProcessorPlayer();
  23333. /** Destructor. */
  23334. virtual ~AudioProcessorPlayer();
  23335. /** Sets the processor that should be played.
  23336. The processor that is passed in will not be deleted or owned by this object.
  23337. To stop anything playing, pass in 0 to this method.
  23338. */
  23339. void setProcessor (AudioProcessor* const processorToPlay);
  23340. /** Returns the current audio processor that is being played.
  23341. */
  23342. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  23343. /** Returns a midi message collector that you can pass midi messages to if you
  23344. want them to be injected into the midi stream that is being sent to the
  23345. processor.
  23346. */
  23347. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  23348. /** @internal */
  23349. void audioDeviceIOCallback (const float** inputChannelData,
  23350. int totalNumInputChannels,
  23351. float** outputChannelData,
  23352. int totalNumOutputChannels,
  23353. int numSamples);
  23354. /** @internal */
  23355. void audioDeviceAboutToStart (AudioIODevice* device);
  23356. /** @internal */
  23357. void audioDeviceStopped();
  23358. /** @internal */
  23359. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  23360. juce_UseDebuggingNewOperator
  23361. private:
  23362. AudioProcessor* processor;
  23363. CriticalSection lock;
  23364. double sampleRate;
  23365. int blockSize;
  23366. bool isPrepared;
  23367. int numInputChans, numOutputChans;
  23368. float* channels [128];
  23369. AudioSampleBuffer tempBuffer;
  23370. MidiBuffer incomingMidi;
  23371. MidiMessageCollector messageCollector;
  23372. AudioProcessorPlayer (const AudioProcessorPlayer&);
  23373. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  23374. };
  23375. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  23376. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  23377. #endif
  23378. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23379. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23380. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23381. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23382. /********* Start of inlined file: juce_PropertyPanel.h *********/
  23383. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  23384. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  23385. /********* Start of inlined file: juce_PropertyComponent.h *********/
  23386. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  23387. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  23388. class EditableProperty;
  23389. /********* Start of inlined file: juce_TooltipClient.h *********/
  23390. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23391. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23392. /**
  23393. Components that want to use pop-up tooltips should implement this interface.
  23394. A TooltipWindow will wait for the mouse to hover over a component that
  23395. implements the TooltipClient interface, and when it finds one, it will display
  23396. the tooltip returned by its getTooltip() method.
  23397. @see TooltipWindow, SettableTooltipClient
  23398. */
  23399. class JUCE_API TooltipClient
  23400. {
  23401. public:
  23402. /** Destructor. */
  23403. virtual ~TooltipClient() {}
  23404. /** Returns the string that this object wants to show as its tooltip. */
  23405. virtual const String getTooltip() = 0;
  23406. };
  23407. /**
  23408. An implementation of TooltipClient that stores the tooltip string and a method
  23409. for changing it.
  23410. This makes it easy to add a tooltip to a custom component, by simply adding this
  23411. as a base class and calling setTooltip().
  23412. Many of the Juce widgets already use this as a base class to implement their
  23413. tooltips.
  23414. @see TooltipClient, TooltipWindow
  23415. */
  23416. class JUCE_API SettableTooltipClient : public TooltipClient
  23417. {
  23418. public:
  23419. /** Destructor. */
  23420. virtual ~SettableTooltipClient() {}
  23421. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  23422. virtual const String getTooltip() { return tooltipString; }
  23423. juce_UseDebuggingNewOperator
  23424. protected:
  23425. String tooltipString;
  23426. };
  23427. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23428. /********* End of inlined file: juce_TooltipClient.h *********/
  23429. /**
  23430. A base class for a component that goes in a PropertyPanel and displays one of
  23431. an item's properties.
  23432. Subclasses of this are used to display a property in various forms, e.g. a
  23433. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  23434. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  23435. A subclass must implement the refresh() method which will be called to tell the
  23436. component to update itself, and is also responsible for calling this it when the
  23437. item that it refers to is changed.
  23438. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  23439. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  23440. */
  23441. class JUCE_API PropertyComponent : public Component,
  23442. public SettableTooltipClient
  23443. {
  23444. public:
  23445. /** Creates a PropertyComponent.
  23446. @param propertyName the name is stored as this component's name, and is
  23447. used as the name displayed next to this component in
  23448. a property panel
  23449. @param preferredHeight the height that the component should be given - some
  23450. items may need to be larger than a normal row height.
  23451. This value can also be set if a subclass changes the
  23452. preferredHeight member variable.
  23453. */
  23454. PropertyComponent (const String& propertyName,
  23455. const int preferredHeight = 25);
  23456. /** Destructor. */
  23457. ~PropertyComponent();
  23458. /** Returns this item's preferred height.
  23459. This value is specified either in the constructor or by a subclass changing the
  23460. preferredHeight member variable.
  23461. */
  23462. int getPreferredHeight() const throw() { return preferredHeight; }
  23463. /** Updates the property component if the item it refers to has changed.
  23464. A subclass must implement this method, and other objects may call it to
  23465. force it to refresh itself.
  23466. The subclass should be economical in the amount of work is done, so for
  23467. example it should check whether it really needs to do a repaint rather than
  23468. just doing one every time this method is called, as it may be called when
  23469. the value being displayed hasn't actually changed.
  23470. */
  23471. virtual void refresh() = 0;
  23472. /** The default paint method fills the background and draws a label for the
  23473. item's name.
  23474. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  23475. */
  23476. void paint (Graphics& g);
  23477. /** The default resize method positions any child component to the right of this
  23478. one, based on the look and feel's default label size.
  23479. */
  23480. void resized();
  23481. /** By default, this just repaints the component. */
  23482. void enablementChanged();
  23483. juce_UseDebuggingNewOperator
  23484. protected:
  23485. /** Used by the PropertyPanel to determine how high this component needs to be.
  23486. A subclass can update this value in its constructor but shouldn't alter it later
  23487. as changes won't necessarily be picked up.
  23488. */
  23489. int preferredHeight;
  23490. };
  23491. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  23492. /********* End of inlined file: juce_PropertyComponent.h *********/
  23493. /********* Start of inlined file: juce_Viewport.h *********/
  23494. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  23495. #define __JUCE_VIEWPORT_JUCEHEADER__
  23496. /********* Start of inlined file: juce_ScrollBar.h *********/
  23497. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  23498. #define __JUCE_SCROLLBAR_JUCEHEADER__
  23499. /********* Start of inlined file: juce_Button.h *********/
  23500. #ifndef __JUCE_BUTTON_JUCEHEADER__
  23501. #define __JUCE_BUTTON_JUCEHEADER__
  23502. /********* Start of inlined file: juce_TooltipWindow.h *********/
  23503. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23504. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23505. /**
  23506. A window that displays a pop-up tooltip when the mouse hovers over another component.
  23507. To enable tooltips in your app, just create a single instance of a TooltipWindow
  23508. object.
  23509. The TooltipWindow object will then stay invisible, waiting until the mouse
  23510. hovers for the specified length of time - it will then see if it's currently
  23511. over a component which implements the TooltipClient interface, and if so,
  23512. it will make itself visible to show the tooltip in the appropriate place.
  23513. @see TooltipClient, SettableTooltipClient
  23514. */
  23515. class JUCE_API TooltipWindow : public Component,
  23516. private Timer
  23517. {
  23518. public:
  23519. /** Creates a tooltip window.
  23520. Make sure your app only creates one instance of this class, otherwise you'll
  23521. get multiple overlaid tooltips appearing. The window will initially be invisible
  23522. and will make itself visible when it needs to display a tip.
  23523. To change the style of tooltips, see the LookAndFeel class for its tooltip
  23524. methods.
  23525. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  23526. otherwise the tooltip will be added to the given parent
  23527. component.
  23528. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  23529. before a tooltip will be shown
  23530. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  23531. */
  23532. TooltipWindow (Component* parentComponent = 0,
  23533. const int millisecondsBeforeTipAppears = 700);
  23534. /** Destructor. */
  23535. ~TooltipWindow();
  23536. /** Changes the time before the tip appears.
  23537. This lets you change the value that was set in the constructor.
  23538. */
  23539. void setMillisecondsBeforeTipAppears (const int newTimeMs = 700) throw();
  23540. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  23541. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23542. methods.
  23543. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23544. */
  23545. enum ColourIds
  23546. {
  23547. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  23548. textColourId = 0x1001c00, /**< The colour to use for the text. */
  23549. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  23550. };
  23551. juce_UseDebuggingNewOperator
  23552. private:
  23553. int millisecondsBeforeTipAppears;
  23554. int mouseX, mouseY, mouseClicks;
  23555. unsigned int lastCompChangeTime, lastHideTime;
  23556. Component* lastComponentUnderMouse;
  23557. bool changedCompsSinceShown;
  23558. String tipShowing, lastTipUnderMouse;
  23559. void paint (Graphics& g);
  23560. void mouseEnter (const MouseEvent& e);
  23561. void timerCallback();
  23562. static const String getTipFor (Component* const c);
  23563. void showFor (Component* const c, const String& tip);
  23564. void hide();
  23565. TooltipWindow (const TooltipWindow&);
  23566. const TooltipWindow& operator= (const TooltipWindow&);
  23567. };
  23568. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23569. /********* End of inlined file: juce_TooltipWindow.h *********/
  23570. class Button;
  23571. /**
  23572. Used to receive callbacks when a button is clicked.
  23573. @see Button::addButtonListener, Button::removeButtonListener
  23574. */
  23575. class JUCE_API ButtonListener
  23576. {
  23577. public:
  23578. /** Destructor. */
  23579. virtual ~ButtonListener() {}
  23580. /** Called when the button is clicked. */
  23581. virtual void buttonClicked (Button* button) = 0;
  23582. /** Called when the button's state changes. */
  23583. virtual void buttonStateChanged (Button*) {}
  23584. };
  23585. /**
  23586. A base class for buttons.
  23587. This contains all the logic for button behaviours such as enabling/disabling,
  23588. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  23589. and radio groups, etc.
  23590. @see TextButton, DrawableButton, ToggleButton
  23591. */
  23592. class JUCE_API Button : public Component,
  23593. public SettableTooltipClient,
  23594. public ApplicationCommandManagerListener,
  23595. private KeyListener
  23596. {
  23597. protected:
  23598. /** Creates a button.
  23599. @param buttonName the text to put in the button (the component's name is also
  23600. initially set to this string, but these can be changed later
  23601. using the setName() and setButtonText() methods)
  23602. */
  23603. Button (const String& buttonName);
  23604. public:
  23605. /** Destructor. */
  23606. virtual ~Button();
  23607. /** Changes the button's text.
  23608. @see getButtonText
  23609. */
  23610. void setButtonText (const String& newText) throw();
  23611. /** Returns the text displayed in the button.
  23612. @see setButtonText
  23613. */
  23614. const String getButtonText() const throw() { return text; }
  23615. /** Returns true if the button is currently being held down by the mouse.
  23616. @see isOver
  23617. */
  23618. bool isDown() const throw();
  23619. /** Returns true if the mouse is currently over the button.
  23620. This will be also be true if the mouse is being held down.
  23621. @see isDown
  23622. */
  23623. bool isOver() const throw();
  23624. /** A button has an on/off state associated with it, and this changes that.
  23625. By default buttons are 'off' and for simple buttons that you click to perform
  23626. an action you won't change this. Toggle buttons, however will want to
  23627. change their state when turned on or off.
  23628. @param shouldBeOn whether to set the button's toggle state to be on or
  23629. off. If it's a member of a button group, this will
  23630. always try to turn it on, and to turn off any other
  23631. buttons in the group
  23632. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  23633. the button will be repainted but no notification will
  23634. be sent
  23635. @see getToggleState, setRadioGroupId
  23636. */
  23637. void setToggleState (const bool shouldBeOn,
  23638. const bool sendChangeNotification);
  23639. /** Returns true if the button in 'on'.
  23640. By default buttons are 'off' and for simple buttons that you click to perform
  23641. an action you won't change this. Toggle buttons, however will want to
  23642. change their state when turned on or off.
  23643. @see setToggleState
  23644. */
  23645. bool getToggleState() const throw() { return isOn; }
  23646. /** This tells the button to automatically flip the toggle state when
  23647. the button is clicked.
  23648. If set to true, then before the clicked() callback occurs, the toggle-state
  23649. of the button is flipped.
  23650. */
  23651. void setClickingTogglesState (const bool shouldToggle) throw();
  23652. /** Returns true if this button is set to be an automatic toggle-button.
  23653. This returns the last value that was passed to setClickingTogglesState().
  23654. */
  23655. bool getClickingTogglesState() const throw();
  23656. /** Enables the button to act as a member of a mutually-exclusive group
  23657. of 'radio buttons'.
  23658. If the group ID is set to a non-zero number, then this button will
  23659. act as part of a group of buttons with the same ID, only one of
  23660. which can be 'on' at the same time. Note that when it's part of
  23661. a group, clicking a toggle-button that's 'on' won't turn it off.
  23662. To find other buttons with the same ID, this button will search through
  23663. its sibling components for ToggleButtons, so all the buttons for a
  23664. particular group must be placed inside the same parent component.
  23665. Set the group ID back to zero if you want it to act as a normal toggle
  23666. button again.
  23667. @see getRadioGroupId
  23668. */
  23669. void setRadioGroupId (const int newGroupId);
  23670. /** Returns the ID of the group to which this button belongs.
  23671. (See setRadioGroupId() for an explanation of this).
  23672. */
  23673. int getRadioGroupId() const throw() { return radioGroupId; }
  23674. /** Registers a listener to receive events when this button's state changes.
  23675. If the listener is already registered, this will not register it again.
  23676. @see removeButtonListener
  23677. */
  23678. void addButtonListener (ButtonListener* const newListener) throw();
  23679. /** Removes a previously-registered button listener
  23680. @see addButtonListener
  23681. */
  23682. void removeButtonListener (ButtonListener* const listener) throw();
  23683. /** Causes the button to act as if it's been clicked.
  23684. This will asynchronously make the button draw itself going down and up, and
  23685. will then call back the clicked() method as if mouse was clicked on it.
  23686. @see clicked
  23687. */
  23688. virtual void triggerClick();
  23689. /** Sets a command ID for this button to automatically invoke when it's clicked.
  23690. When the button is pressed, it will use the given manager to trigger the
  23691. command ID.
  23692. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  23693. before this button is. To disable the command triggering, call this method and
  23694. pass 0 for the parameters.
  23695. If generateTooltip is true, then the button's tooltip will be automatically
  23696. generated based on the name of this command and its current shortcut key.
  23697. @see addShortcut, getCommandID
  23698. */
  23699. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  23700. const int commandID,
  23701. const bool generateTooltip);
  23702. /** Returns the command ID that was set by setCommandToTrigger().
  23703. */
  23704. int getCommandID() const throw() { return commandID; }
  23705. /** Assigns a shortcut key to trigger the button.
  23706. The button registers itself with its top-level parent component for keypresses.
  23707. Note that a different way of linking buttons to keypresses is by using the
  23708. setCommandToTrigger() method to invoke a command.
  23709. @see clearShortcuts
  23710. */
  23711. void addShortcut (const KeyPress& key);
  23712. /** Removes all key shortcuts that had been set for this button.
  23713. @see addShortcut
  23714. */
  23715. void clearShortcuts();
  23716. /** Returns true if the given keypress is a shortcut for this button.
  23717. @see addShortcut
  23718. */
  23719. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  23720. /** Sets an auto-repeat speed for the button when it is held down.
  23721. (Auto-repeat is disabled by default).
  23722. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  23723. triggering the next click. If this is zero, auto-repeat
  23724. is disabled
  23725. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  23726. triggered
  23727. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  23728. get faster, the longer the button is held down, up to the
  23729. minimum interval specified here
  23730. */
  23731. void setRepeatSpeed (const int initialDelayInMillisecs,
  23732. const int repeatDelayInMillisecs,
  23733. const int minimumDelayInMillisecs = -1) throw();
  23734. /** Sets whether the button click should happen when the mouse is pressed or released.
  23735. By default the button is only considered to have been clicked when the mouse is
  23736. released, but setting this to true will make it call the clicked() method as soon
  23737. as the button is pressed.
  23738. This is useful if the button is being used to show a pop-up menu, as it allows
  23739. the click to be used as a drag onto the menu.
  23740. */
  23741. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  23742. /** Returns the number of milliseconds since the last time the button
  23743. went into the 'down' state.
  23744. */
  23745. uint32 getMillisecondsSinceButtonDown() const throw();
  23746. /** (overridden from Component to do special stuff). */
  23747. void setVisible (bool shouldBeVisible);
  23748. /** Sets the tooltip for this button.
  23749. @see TooltipClient, TooltipWindow
  23750. */
  23751. void setTooltip (const String& newTooltip);
  23752. // (implementation of the TooltipClient method)
  23753. const String getTooltip();
  23754. /** A combination of these flags are used by setConnectedEdges().
  23755. */
  23756. enum ConnectedEdgeFlags
  23757. {
  23758. ConnectedOnLeft = 1,
  23759. ConnectedOnRight = 2,
  23760. ConnectedOnTop = 4,
  23761. ConnectedOnBottom = 8
  23762. };
  23763. /** Hints about which edges of the button might be connected to adjoining buttons.
  23764. The value passed in is a bitwise combination of any of the values in the
  23765. ConnectedEdgeFlags enum.
  23766. E.g. if you are placing two buttons adjacent to each other, you could use this to
  23767. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  23768. without rounded corners on the edges that connect. It's only a hint, so the
  23769. LookAndFeel can choose to ignore it if it's not relevent for this type of
  23770. button.
  23771. */
  23772. void setConnectedEdges (const int connectedEdgeFlags) throw();
  23773. /** Returns the set of flags passed into setConnectedEdges(). */
  23774. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  23775. /** Indicates whether the button adjoins another one on its left edge.
  23776. @see setConnectedEdges
  23777. */
  23778. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  23779. /** Indicates whether the button adjoins another one on its right edge.
  23780. @see setConnectedEdges
  23781. */
  23782. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  23783. /** Indicates whether the button adjoins another one on its top edge.
  23784. @see setConnectedEdges
  23785. */
  23786. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  23787. /** Indicates whether the button adjoins another one on its bottom edge.
  23788. @see setConnectedEdges
  23789. */
  23790. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  23791. /** Used by setState(). */
  23792. enum ButtonState
  23793. {
  23794. buttonNormal,
  23795. buttonOver,
  23796. buttonDown
  23797. };
  23798. /** Can be used to force the button into a particular state.
  23799. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  23800. from happening.
  23801. The state that you set here will only last until it is automatically changed when the mouse
  23802. enters or exits the button, or the mouse-button is pressed or released.
  23803. */
  23804. void setState (const ButtonState newState);
  23805. juce_UseDebuggingNewOperator
  23806. protected:
  23807. /** This method is called when the button has been clicked.
  23808. Subclasses can override this to perform whatever they actions they need
  23809. to do.
  23810. Alternatively, a ButtonListener can be added to the button, and these listeners
  23811. will be called when the click occurs.
  23812. @see triggerClick
  23813. */
  23814. virtual void clicked();
  23815. /** This method is called when the button has been clicked.
  23816. By default it just calls clicked(), but you might want to override it to handle
  23817. things like clicking when a modifier key is pressed, etc.
  23818. @see ModifierKeys
  23819. */
  23820. virtual void clicked (const ModifierKeys& modifiers);
  23821. /** Subclasses should override this to actually paint the button's contents.
  23822. It's better to use this than the paint method, because it gives you information
  23823. about the over/down state of the button.
  23824. @param g the graphics context to use
  23825. @param isMouseOverButton true if the button is either in the 'over' or
  23826. 'down' state
  23827. @param isButtonDown true if the button should be drawn in the 'down' position
  23828. */
  23829. virtual void paintButton (Graphics& g,
  23830. bool isMouseOverButton,
  23831. bool isButtonDown) = 0;
  23832. /** Called when the button's up/down/over state changes.
  23833. Subclasses can override this if they need to do something special when the button
  23834. goes up or down.
  23835. @see isDown, isOver
  23836. */
  23837. virtual void buttonStateChanged();
  23838. /** @internal */
  23839. virtual void internalClickCallback (const ModifierKeys& modifiers);
  23840. /** @internal */
  23841. void handleCommandMessage (int commandId);
  23842. /** @internal */
  23843. void mouseEnter (const MouseEvent& e);
  23844. /** @internal */
  23845. void mouseExit (const MouseEvent& e);
  23846. /** @internal */
  23847. void mouseDown (const MouseEvent& e);
  23848. /** @internal */
  23849. void mouseDrag (const MouseEvent& e);
  23850. /** @internal */
  23851. void mouseUp (const MouseEvent& e);
  23852. /** @internal */
  23853. bool keyPressed (const KeyPress& key);
  23854. /** @internal */
  23855. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  23856. /** @internal */
  23857. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  23858. /** @internal */
  23859. void paint (Graphics& g);
  23860. /** @internal */
  23861. void parentHierarchyChanged();
  23862. /** @internal */
  23863. void focusGained (FocusChangeType cause);
  23864. /** @internal */
  23865. void focusLost (FocusChangeType cause);
  23866. /** @internal */
  23867. void enablementChanged();
  23868. /** @internal */
  23869. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  23870. /** @internal */
  23871. void applicationCommandListChanged();
  23872. private:
  23873. Array <KeyPress> shortcuts;
  23874. Component* keySource;
  23875. String text;
  23876. SortedSet <void*> buttonListeners;
  23877. friend class InternalButtonRepeatTimer;
  23878. Timer* repeatTimer;
  23879. uint32 buttonPressTime, lastTimeCallbackTime;
  23880. ApplicationCommandManager* commandManagerToUse;
  23881. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  23882. int radioGroupId, commandID, connectedEdgeFlags;
  23883. ButtonState buttonState;
  23884. bool isOn : 1;
  23885. bool clickTogglesState : 1;
  23886. bool needsToRelease : 1;
  23887. bool needsRepainting : 1;
  23888. bool isKeyDown : 1;
  23889. bool triggerOnMouseDown : 1;
  23890. bool generateTooltip : 1;
  23891. void repeatTimerCallback() throw();
  23892. Timer& getRepeatTimer() throw();
  23893. ButtonState updateState (const MouseEvent* const e) throw();
  23894. bool isShortcutPressed() const throw();
  23895. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  23896. void flashButtonState() throw();
  23897. void sendClickMessage (const ModifierKeys& modifiers);
  23898. void sendStateMessage();
  23899. Button (const Button&);
  23900. const Button& operator= (const Button&);
  23901. };
  23902. #endif // __JUCE_BUTTON_JUCEHEADER__
  23903. /********* End of inlined file: juce_Button.h *********/
  23904. class ScrollBar;
  23905. /**
  23906. A class for receiving events from a ScrollBar.
  23907. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  23908. method, and it will be called when the bar's position changes.
  23909. @see ScrollBar::addListener, ScrollBar::removeListener
  23910. */
  23911. class JUCE_API ScrollBarListener
  23912. {
  23913. public:
  23914. /** Destructor. */
  23915. virtual ~ScrollBarListener() {}
  23916. /** Called when a ScrollBar is moved.
  23917. @param scrollBarThatHasMoved the bar that has moved
  23918. @param newRangeStart the new range start of this bar
  23919. */
  23920. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  23921. const double newRangeStart) = 0;
  23922. };
  23923. /**
  23924. A scrollbar component.
  23925. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  23926. sets the range of values it can represent. Then you can use setCurrentRange() to
  23927. change the position and size of the scrollbar's 'thumb'.
  23928. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  23929. the user moves it, and you can use the getCurrentRangeStart() to find out where
  23930. they moved it to.
  23931. The scrollbar will adjust its own visibility according to whether its thumb size
  23932. allows it to actually be scrolled.
  23933. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  23934. instead of handling a scrollbar directly.
  23935. @see ScrollBarListener
  23936. */
  23937. class JUCE_API ScrollBar : public Component,
  23938. public AsyncUpdater,
  23939. private Timer
  23940. {
  23941. public:
  23942. /** Creates a Scrollbar.
  23943. @param isVertical whether it should be a vertical or horizontal bar
  23944. @param buttonsAreVisible whether to show the up/down or left/right buttons
  23945. */
  23946. ScrollBar (const bool isVertical,
  23947. const bool buttonsAreVisible = true);
  23948. /** Destructor. */
  23949. ~ScrollBar();
  23950. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  23951. bool isVertical() const throw() { return vertical; }
  23952. /** Changes the scrollbar's direction.
  23953. You'll also need to resize the bar appropriately - this just changes its internal
  23954. layout.
  23955. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  23956. */
  23957. void setOrientation (const bool shouldBeVertical) throw();
  23958. /** Shows or hides the scrollbar's buttons. */
  23959. void setButtonVisibility (const bool buttonsAreVisible);
  23960. /** Tells the scrollbar whether to make itself invisible when not needed.
  23961. The default behaviour is for a scrollbar to become invisible when the thumb
  23962. fills the whole of its range (i.e. when it can't be moved). Setting this
  23963. value to false forces the bar to always be visible.
  23964. */
  23965. void setAutoHide (const bool shouldHideWhenFullRange);
  23966. /** Sets the minimum and maximum values that the bar will move between.
  23967. The bar's thumb will always be constrained so that the top of the thumb
  23968. will be >= minimum, and the bottom of the thumb <= maximum.
  23969. @see setCurrentRange
  23970. */
  23971. void setRangeLimits (const double minimum,
  23972. const double maximum) throw();
  23973. /** Returns the lower value that the thumb can be set to.
  23974. This is the value set by setRangeLimits().
  23975. */
  23976. double getMinimumRangeLimit() const throw() { return minimum; }
  23977. /** Returns the upper value that the thumb can be set to.
  23978. This is the value set by setRangeLimits().
  23979. */
  23980. double getMaximumRangeLimit() const throw() { return maximum; }
  23981. /** Changes the position of the scrollbar's 'thumb'.
  23982. This sets both the position and size of the thumb - to just set the position without
  23983. changing the size, you can use setCurrentRangeStart().
  23984. If this method call actually changes the scrollbar's position, it will trigger an
  23985. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23986. are registered.
  23987. @param newStart the top (or left) of the thumb, in the range
  23988. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  23989. value is beyond these limits, it will be clipped.
  23990. @param newSize the size of the thumb, such that
  23991. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  23992. size is beyond these limits, it will be clipped.
  23993. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  23994. */
  23995. void setCurrentRange (double newStart,
  23996. double newSize) throw();
  23997. /** Moves the bar's thumb position.
  23998. This will move the thumb position without changing the thumb size. Note
  23999. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  24000. If this method call actually changes the scrollbar's position, it will trigger an
  24001. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  24002. are registered.
  24003. @see setCurrentRange
  24004. */
  24005. void setCurrentRangeStart (double newStart) throw();
  24006. /** Returns the position of the top of the thumb.
  24007. @see setCurrentRangeStart
  24008. */
  24009. double getCurrentRangeStart() const throw() { return rangeStart; }
  24010. /** Returns the current size of the thumb.
  24011. @see setCurrentRange
  24012. */
  24013. double getCurrentRangeSize() const throw() { return rangeSize; }
  24014. /** Sets the amount by which the up and down buttons will move the bar.
  24015. The value here is in terms of the total range, and is added or subtracted
  24016. from the thumb position when the user clicks an up/down (or left/right) button.
  24017. */
  24018. void setSingleStepSize (const double newSingleStepSize) throw();
  24019. /** Moves the scrollbar by a number of single-steps.
  24020. This will move the bar by a multiple of its single-step interval (as
  24021. specified using the setSingleStepSize() method).
  24022. A positive value here will move the bar down or to the right, a negative
  24023. value moves it up or to the left.
  24024. */
  24025. void moveScrollbarInSteps (const int howManySteps) throw();
  24026. /** Moves the scroll bar up or down in pages.
  24027. This will move the bar by a multiple of its current thumb size, effectively
  24028. doing a page-up or down.
  24029. A positive value here will move the bar down or to the right, a negative
  24030. value moves it up or to the left.
  24031. */
  24032. void moveScrollbarInPages (const int howManyPages) throw();
  24033. /** Scrolls to the top (or left).
  24034. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  24035. */
  24036. void scrollToTop() throw();
  24037. /** Scrolls to the bottom (or right).
  24038. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  24039. */
  24040. void scrollToBottom() throw();
  24041. /** Changes the delay before the up and down buttons autorepeat when they are held
  24042. down.
  24043. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  24044. @see Button::setRepeatSpeed
  24045. */
  24046. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  24047. const int repeatDelayInMillisecs,
  24048. const int minimumDelayInMillisecs = -1) throw();
  24049. /** A set of colour IDs to use to change the colour of various aspects of the component.
  24050. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24051. methods.
  24052. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24053. */
  24054. enum ColourIds
  24055. {
  24056. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  24057. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  24058. 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. */
  24059. };
  24060. /** Registers a listener that will be called when the scrollbar is moved. */
  24061. void addListener (ScrollBarListener* const listener) throw();
  24062. /** Deregisters a previously-registered listener. */
  24063. void removeListener (ScrollBarListener* const listener) throw();
  24064. /** @internal */
  24065. bool keyPressed (const KeyPress& key);
  24066. /** @internal */
  24067. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24068. /** @internal */
  24069. void lookAndFeelChanged();
  24070. /** @internal */
  24071. void handleAsyncUpdate();
  24072. /** @internal */
  24073. void mouseDown (const MouseEvent& e);
  24074. /** @internal */
  24075. void mouseDrag (const MouseEvent& e);
  24076. /** @internal */
  24077. void mouseUp (const MouseEvent& e);
  24078. /** @internal */
  24079. void paint (Graphics& g);
  24080. /** @internal */
  24081. void resized();
  24082. juce_UseDebuggingNewOperator
  24083. private:
  24084. double minimum, maximum;
  24085. double rangeStart, rangeSize;
  24086. double singleStepSize, dragStartRange;
  24087. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  24088. int dragStartMousePos, lastMousePos;
  24089. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  24090. bool vertical, isDraggingThumb, alwaysVisible;
  24091. Button* upButton;
  24092. Button* downButton;
  24093. SortedSet <void*> listeners;
  24094. void updateThumbPosition() throw();
  24095. void timerCallback();
  24096. ScrollBar (const ScrollBar&);
  24097. const ScrollBar& operator= (const ScrollBar&);
  24098. };
  24099. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  24100. /********* End of inlined file: juce_ScrollBar.h *********/
  24101. /**
  24102. A Viewport is used to contain a larger child component, and allows the child
  24103. to be automatically scrolled around.
  24104. To use a Viewport, just create one and set the component that goes inside it
  24105. using the setViewedComponent() method. When the child component changes size,
  24106. the Viewport will adjust its scrollbars accordingly.
  24107. A subclass of the viewport can be created which will receive calls to its
  24108. visibleAreaChanged() method when the subcomponent changes position or size.
  24109. */
  24110. class JUCE_API Viewport : public Component,
  24111. private ComponentListener,
  24112. private ScrollBarListener
  24113. {
  24114. public:
  24115. /** Creates a Viewport.
  24116. The viewport is initially empty - use the setViewedComponent() method to
  24117. add a child component for it to manage.
  24118. */
  24119. Viewport (const String& componentName = String::empty);
  24120. /** Destructor. */
  24121. ~Viewport();
  24122. /** Sets the component that this viewport will contain and scroll around.
  24123. This will add the given component to this Viewport and position it at
  24124. (0, 0).
  24125. (Don't add or remove any child components directly using the normal
  24126. Component::addChildComponent() methods).
  24127. @param newViewedComponent the component to add to this viewport (this pointer
  24128. may be null). The component passed in will be deleted
  24129. by the Viewport when it's no longer needed
  24130. @see getViewedComponent
  24131. */
  24132. void setViewedComponent (Component* const newViewedComponent);
  24133. /** Returns the component that's currently being used inside the Viewport.
  24134. @see setViewedComponent
  24135. */
  24136. Component* getViewedComponent() const throw() { return contentComp; }
  24137. /** Changes the position of the viewed component.
  24138. The inner component will be moved so that the pixel at the top left of
  24139. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  24140. within the inner component.
  24141. This will update the scrollbars and might cause a call to visibleAreaChanged().
  24142. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  24143. */
  24144. void setViewPosition (const int xPixelsOffset,
  24145. const int yPixelsOffset);
  24146. /** Changes the view position as a proportion of the distance it can move.
  24147. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  24148. visible area in the top-left, and (1, 1) would put it as far down and
  24149. to the right as it's possible to go whilst keeping the child component
  24150. on-screen.
  24151. */
  24152. void setViewPositionProportionately (const double proportionX,
  24153. const double proportionY);
  24154. /** If the specified position is at the edges of the viewport, this method scrolls
  24155. the viewport to bring that position nearer to the centre.
  24156. Call this if you're dragging an object inside a viewport and want to make it scroll
  24157. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  24158. useful when auto-scrolling.
  24159. @param mouseX the x position, relative to the Viewport's top-left
  24160. @param mouseY the y position, relative to the Viewport's top-left
  24161. @param distanceFromEdge specifies how close to an edge the position needs to be
  24162. before the viewport should scroll in that direction
  24163. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  24164. to scroll by.
  24165. @returns true if the viewport was scrolled
  24166. */
  24167. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  24168. /** Returns the position within the child component of the top-left of its visible area.
  24169. @see getViewWidth, setViewPosition
  24170. */
  24171. int getViewPositionX() const throw() { return lastVX; }
  24172. /** Returns the position within the child component of the top-left of its visible area.
  24173. @see getViewHeight, setViewPosition
  24174. */
  24175. int getViewPositionY() const throw() { return lastVY; }
  24176. /** Returns the width of the visible area of the child component.
  24177. This may be less than the width of this Viewport if there's a vertical scrollbar
  24178. or if the child component is itself smaller.
  24179. */
  24180. int getViewWidth() const throw() { return lastVW; }
  24181. /** Returns the height of the visible area of the child component.
  24182. This may be less than the height of this Viewport if there's a horizontal scrollbar
  24183. or if the child component is itself smaller.
  24184. */
  24185. int getViewHeight() const throw() { return lastVH; }
  24186. /** Returns the width available within this component for the contents.
  24187. This will be the width of the viewport component minus the width of a
  24188. vertical scrollbar (if visible).
  24189. */
  24190. int getMaximumVisibleWidth() const throw();
  24191. /** Returns the height available within this component for the contents.
  24192. This will be the height of the viewport component minus the space taken up
  24193. by a horizontal scrollbar (if visible).
  24194. */
  24195. int getMaximumVisibleHeight() const throw();
  24196. /** Callback method that is called when the visible area changes.
  24197. This will be called when the visible area is moved either be scrolling or
  24198. by calls to setViewPosition(), etc.
  24199. */
  24200. virtual void visibleAreaChanged (int visibleX, int visibleY,
  24201. int visibleW, int visibleH);
  24202. /** Turns scrollbars on or off.
  24203. If set to false, the scrollbars won't ever appear. When true (the default)
  24204. they will appear only when needed.
  24205. */
  24206. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  24207. const bool showHorizontalScrollbarIfNeeded);
  24208. /** True if the vertical scrollbar is enabled.
  24209. @see setScrollBarsShown
  24210. */
  24211. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  24212. /** True if the horizontal scrollbar is enabled.
  24213. @see setScrollBarsShown
  24214. */
  24215. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  24216. /** Changes the width of the scrollbars.
  24217. If this isn't specified, the default width from the LookAndFeel class will be used.
  24218. @see LookAndFeel::getDefaultScrollbarWidth
  24219. */
  24220. void setScrollBarThickness (const int thickness);
  24221. /** Returns the thickness of the scrollbars.
  24222. @see setScrollBarThickness
  24223. */
  24224. int getScrollBarThickness() const throw();
  24225. /** Changes the distance that a single-step click on a scrollbar button
  24226. will move the viewport.
  24227. */
  24228. void setSingleStepSizes (const int stepX, const int stepY);
  24229. /** Shows or hides the buttons on any scrollbars that are used.
  24230. @see ScrollBar::setButtonVisibility
  24231. */
  24232. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24233. /** Returns a pointer to the scrollbar component being used.
  24234. Handy if you need to customise the bar somehow.
  24235. */
  24236. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  24237. /** Returns a pointer to the scrollbar component being used.
  24238. Handy if you need to customise the bar somehow.
  24239. */
  24240. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  24241. juce_UseDebuggingNewOperator
  24242. /** @internal */
  24243. void resized();
  24244. /** @internal */
  24245. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  24246. /** @internal */
  24247. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24248. /** @internal */
  24249. bool keyPressed (const KeyPress& key);
  24250. /** @internal */
  24251. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24252. /** @internal */
  24253. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24254. private:
  24255. Component* contentComp;
  24256. int lastVX, lastVY, lastVW, lastVH;
  24257. int scrollBarThickness;
  24258. int singleStepX, singleStepY;
  24259. bool showHScrollbar, showVScrollbar;
  24260. Component* contentHolder;
  24261. ScrollBar* verticalScrollBar;
  24262. ScrollBar* horizontalScrollBar;
  24263. void updateVisibleRegion();
  24264. Viewport (const Viewport&);
  24265. const Viewport& operator= (const Viewport&);
  24266. };
  24267. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  24268. /********* End of inlined file: juce_Viewport.h *********/
  24269. /**
  24270. A panel that holds a list of PropertyComponent objects.
  24271. This panel displays a list of PropertyComponents, and allows them to be organised
  24272. into collapsible sections.
  24273. To use, simply create one of these and add your properties to it with addProperties()
  24274. or addSection().
  24275. @see PropertyComponent
  24276. */
  24277. class JUCE_API PropertyPanel : public Component
  24278. {
  24279. public:
  24280. /** Creates an empty property panel. */
  24281. PropertyPanel();
  24282. /** Destructor. */
  24283. ~PropertyPanel();
  24284. /** Deletes all property components from the panel.
  24285. */
  24286. void clear();
  24287. /** Adds a set of properties to the panel.
  24288. The components in the list will be owned by this object and will be automatically
  24289. deleted later on when no longer needed.
  24290. These properties are added without them being inside a named section. If you
  24291. want them to be kept together in a collapsible section, use addSection() instead.
  24292. */
  24293. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  24294. /** Adds a set of properties to the panel.
  24295. These properties are added at the bottom of the list, under a section heading with
  24296. a plus/minus button that allows it to be opened and closed.
  24297. The components in the list will be owned by this object and will be automatically
  24298. deleted later on when no longer needed.
  24299. To add properies without them being in a section, use addProperties().
  24300. */
  24301. void addSection (const String& sectionTitle,
  24302. const Array <PropertyComponent*>& newPropertyComponents,
  24303. const bool shouldSectionInitiallyBeOpen = true);
  24304. /** Calls the refresh() method of all PropertyComponents in the panel */
  24305. void refreshAll() const;
  24306. /** Returns a list of all the names of sections in the panel.
  24307. These are the sections that have been added with addSection().
  24308. */
  24309. const StringArray getSectionNames() const;
  24310. /** Returns true if the section at this index is currently open.
  24311. The index is from 0 up to the number of items returned by getSectionNames().
  24312. */
  24313. bool isSectionOpen (const int sectionIndex) const;
  24314. /** Opens or closes one of the sections.
  24315. The index is from 0 up to the number of items returned by getSectionNames().
  24316. */
  24317. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  24318. /** Enables or disables one of the sections.
  24319. The index is from 0 up to the number of items returned by getSectionNames().
  24320. */
  24321. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  24322. /** Saves the current state of open/closed sections so it can be restored later.
  24323. The caller is responsible for deleting the object that is returned.
  24324. To restore this state, use restoreOpennessState().
  24325. @see restoreOpennessState
  24326. */
  24327. XmlElement* getOpennessState() const;
  24328. /** Restores a previously saved arrangement of open/closed sections.
  24329. This will try to restore a snapshot of the panel's state that was created by
  24330. the getOpennessState() method. If any of the sections named in the original
  24331. XML aren't present, they will be ignored.
  24332. @see getOpennessState
  24333. */
  24334. void restoreOpennessState (const XmlElement& newState);
  24335. /** Sets a message to be displayed when there are no properties in the panel.
  24336. The default message is "nothing selected".
  24337. */
  24338. void setMessageWhenEmpty (const String& newMessage);
  24339. /** Returns the message that is displayed when there are no properties.
  24340. @see setMessageWhenEmpty
  24341. */
  24342. const String& getMessageWhenEmpty() const throw();
  24343. /** @internal */
  24344. void paint (Graphics& g);
  24345. /** @internal */
  24346. void resized();
  24347. juce_UseDebuggingNewOperator
  24348. private:
  24349. Viewport* viewport;
  24350. Component* propertyHolderComponent;
  24351. String messageWhenEmpty;
  24352. void updatePropHolderLayout() const;
  24353. void updatePropHolderLayout (const int width) const;
  24354. };
  24355. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  24356. /********* End of inlined file: juce_PropertyPanel.h *********/
  24357. /**
  24358. A type of UI component that displays the parameters of an AudioProcessor as
  24359. a simple list of sliders.
  24360. This can be used for showing an editor for a processor that doesn't supply
  24361. its own custom editor.
  24362. @see AudioProcessor
  24363. */
  24364. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  24365. {
  24366. public:
  24367. GenericAudioProcessorEditor (AudioProcessor* const owner);
  24368. ~GenericAudioProcessorEditor();
  24369. void paint (Graphics& g);
  24370. void resized();
  24371. juce_UseDebuggingNewOperator
  24372. private:
  24373. PropertyPanel* panel;
  24374. };
  24375. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  24376. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  24377. #endif
  24378. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  24379. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  24380. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  24381. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  24382. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  24383. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24384. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24385. /********* Start of inlined file: juce_AudioSource.h *********/
  24386. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  24387. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  24388. /**
  24389. Used by AudioSource::getNextAudioBlock().
  24390. */
  24391. struct JUCE_API AudioSourceChannelInfo
  24392. {
  24393. /** The destination buffer to fill with audio data.
  24394. When the AudioSource::getNextAudioBlock() method is called, the active section
  24395. of this buffer should be filled with whatever output the source produces.
  24396. Only the samples specified by the startSample and numSamples members of this structure
  24397. should be affected by the call.
  24398. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  24399. method can be treated as the input if the source is performing some kind of filter operation,
  24400. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  24401. a handy way of doing this.
  24402. The number of channels in the buffer could be anything, so the AudioSource
  24403. must cope with this in whatever way is appropriate for its function.
  24404. */
  24405. AudioSampleBuffer* buffer;
  24406. /** The first sample in the buffer from which the callback is expected
  24407. to write data. */
  24408. int startSample;
  24409. /** The number of samples in the buffer which the callback is expected to
  24410. fill with data. */
  24411. int numSamples;
  24412. /** Convenient method to clear the buffer if the source is not producing any data. */
  24413. void clearActiveBufferRegion() const
  24414. {
  24415. if (buffer != 0)
  24416. buffer->clear (startSample, numSamples);
  24417. }
  24418. };
  24419. /**
  24420. Base class for objects that can produce a continuous stream of audio.
  24421. @see AudioFormatReaderSource, ResamplingAudioSource
  24422. */
  24423. class JUCE_API AudioSource
  24424. {
  24425. protected:
  24426. /** Creates an AudioSource. */
  24427. AudioSource() throw() {}
  24428. public:
  24429. /** Destructor. */
  24430. virtual ~AudioSource() {}
  24431. /** Tells the source to prepare for playing.
  24432. The source can use this opportunity to initialise anything it needs to.
  24433. Note that this method could be called more than once in succession without
  24434. a matching call to releaseResources(), so make sure your code is robust and
  24435. can handle that kind of situation.
  24436. @param samplesPerBlockExpected the number of samples that the source
  24437. will be expected to supply each time its
  24438. getNextAudioBlock() method is called. This
  24439. number may vary slightly, because it will be dependent
  24440. on audio hardware callbacks, and these aren't
  24441. guaranteed to always use a constant block size, so
  24442. the source should be able to cope with small variations.
  24443. @param sampleRate the sample rate that the output will be used at - this
  24444. is needed by sources such as tone generators.
  24445. @see releaseResources, getNextAudioBlock
  24446. */
  24447. virtual void prepareToPlay (int samplesPerBlockExpected,
  24448. double sampleRate) = 0;
  24449. /** Allows the source to release anything it no longer needs after playback has stopped.
  24450. This will be called when the source is no longer going to have its getNextAudioBlock()
  24451. method called, so it should release any spare memory, etc. that it might have
  24452. allocated during the prepareToPlay() call.
  24453. Note that there's no guarantee that prepareToPlay() will actually have been called before
  24454. releaseResources(), and it may be called more than once in succession, so make sure your
  24455. code is robust and doesn't make any assumptions about when it will be called.
  24456. @see prepareToPlay, getNextAudioBlock
  24457. */
  24458. virtual void releaseResources() = 0;
  24459. /** Called repeatedly to fetch subsequent blocks of audio data.
  24460. After calling the prepareToPlay() method, this callback will be made each
  24461. time the audio playback hardware (or whatever other destination the audio
  24462. data is going to) needs another block of data.
  24463. It will generally be called on a high-priority system thread, or possibly even
  24464. an interrupt, so be careful not to do too much work here, as that will cause
  24465. audio glitches!
  24466. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  24467. */
  24468. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  24469. };
  24470. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  24471. /********* End of inlined file: juce_AudioSource.h *********/
  24472. /**
  24473. A type of AudioSource which can be repositioned.
  24474. The basic AudioSource just streams continuously with no idea of a current
  24475. time or length, so the PositionableAudioSource is used for a finite stream
  24476. that has a current read position.
  24477. @see AudioSource, AudioTransportSource
  24478. */
  24479. class JUCE_API PositionableAudioSource : public AudioSource
  24480. {
  24481. protected:
  24482. /** Creates the PositionableAudioSource. */
  24483. PositionableAudioSource() throw() {}
  24484. public:
  24485. /** Destructor */
  24486. ~PositionableAudioSource() {}
  24487. /** Tells the stream to move to a new position.
  24488. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  24489. should return samples from this position.
  24490. Note that this may be called on a different thread to getNextAudioBlock(),
  24491. so the subclass should make sure it's synchronised.
  24492. */
  24493. virtual void setNextReadPosition (int newPosition) = 0;
  24494. /** Returns the position from which the next block will be returned.
  24495. @see setNextReadPosition
  24496. */
  24497. virtual int getNextReadPosition() const = 0;
  24498. /** Returns the total length of the stream (in samples). */
  24499. virtual int getTotalLength() const = 0;
  24500. /** Returns true if this source is actually playing in a loop. */
  24501. virtual bool isLooping() const = 0;
  24502. };
  24503. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24504. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  24505. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  24506. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  24507. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  24508. class AudioFormat;
  24509. /**
  24510. Reads samples from an audio file stream.
  24511. A subclass that reads a specific type of audio format will be created by
  24512. an AudioFormat object.
  24513. @see AudioFormat, AudioFormatWriter
  24514. */
  24515. class JUCE_API AudioFormatReader
  24516. {
  24517. protected:
  24518. /** Creates an AudioFormatReader object.
  24519. @param sourceStream the stream to read from - this will be deleted
  24520. by this object when it is no longer needed. (Some
  24521. specialised readers might not use this parameter and
  24522. can leave it as 0).
  24523. @param formatName the description that will be returned by the getFormatName()
  24524. method
  24525. */
  24526. AudioFormatReader (InputStream* const sourceStream,
  24527. const String& formatName);
  24528. public:
  24529. /** Destructor. */
  24530. virtual ~AudioFormatReader();
  24531. /** Returns a description of what type of format this is.
  24532. E.g. "AIFF"
  24533. */
  24534. const String getFormatName() const throw() { return formatName; }
  24535. /** Reads samples from the stream.
  24536. @param destSamples an array of buffers into which the sample data for each
  24537. channel will be written.
  24538. If the format is fixed-point, each channel will be written
  24539. as an array of 32-bit signed integers using the full
  24540. range -0x80000000 to 0x7fffffff, regardless of the source's
  24541. bit-depth. If it is a floating-point format, you should cast
  24542. the resulting array to a (float**) to get the values (in the
  24543. range -1.0 to 1.0 or beyond)
  24544. If the format is stereo, then destSamples[0] is the left channel
  24545. data, and destSamples[1] is the right channel.
  24546. The numDestChannels parameter indicates how many pointers this array
  24547. contains, but some of these pointers can be null if you don't want to
  24548. read data for some of the channels
  24549. @param numDestChannels the number of array elements in the destChannels array
  24550. @param startSampleInSource the position in the audio file or stream at which the samples
  24551. should be read, as a number of samples from the start of the
  24552. stream. It's ok for this to be beyond the start or end of the
  24553. available data - any samples that are out-of-range will be returned
  24554. as zeros.
  24555. @param numSamplesToRead the number of samples to read. If this is greater than the number
  24556. of samples that the file or stream contains. the result will be padded
  24557. with zeros
  24558. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  24559. for some of the channels that you pass in, then they should be filled with
  24560. copies of valid source channels.
  24561. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  24562. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  24563. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  24564. was false, then only the first channel would be filled with the file's contents, and
  24565. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  24566. from a stereo file, then the last 3 would all end up with copies of the same data.
  24567. @returns true if the operation succeeded, false if there was an error. Note
  24568. that reading sections of data beyond the extent of the stream isn't an
  24569. error - the reader should just return zeros for these regions
  24570. @see readMaxLevels
  24571. */
  24572. bool read (int** destSamples,
  24573. int numDestChannels,
  24574. int64 startSampleInSource,
  24575. int numSamplesToRead,
  24576. const bool fillLeftoverChannelsWithCopies);
  24577. /** Finds the highest and lowest sample levels from a section of the audio stream.
  24578. This will read a block of samples from the stream, and measure the
  24579. highest and lowest sample levels from the channels in that section, returning
  24580. these as normalised floating-point levels.
  24581. @param startSample the offset into the audio stream to start reading from. It's
  24582. ok for this to be beyond the start or end of the stream.
  24583. @param numSamples how many samples to read
  24584. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  24585. @param highestLeft on return, this is the highest absolute sample from the left channel
  24586. @param lowestRight on return, this is the lowest absolute sample from the right
  24587. channel (if there is one)
  24588. @param highestRight on return, this is the highest absolute sample from the right
  24589. channel (if there is one)
  24590. @see read
  24591. */
  24592. virtual void readMaxLevels (int64 startSample,
  24593. int64 numSamples,
  24594. float& lowestLeft,
  24595. float& highestLeft,
  24596. float& lowestRight,
  24597. float& highestRight);
  24598. /** Scans the source looking for a sample whose magnitude is in a specified range.
  24599. This will read from the source, either forwards or backwards between two sample
  24600. positions, until it finds a sample whose magnitude lies between two specified levels.
  24601. If it finds a suitable sample, it returns its position; if not, it will return -1.
  24602. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  24603. points when you're searching for a continuous range of samples
  24604. @param startSample the first sample to look at
  24605. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  24606. the search will go backwards
  24607. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  24608. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  24609. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  24610. of this many consecutive samples, all of which lie
  24611. within the target range. When it finds such a sequence,
  24612. it returns the position of the first in-range sample
  24613. it found (i.e. the earliest one if scanning forwards, the
  24614. latest one if scanning backwards)
  24615. */
  24616. int64 searchForLevel (int64 startSample,
  24617. int64 numSamplesToSearch,
  24618. const double magnitudeRangeMinimum,
  24619. const double magnitudeRangeMaximum,
  24620. const int minimumConsecutiveSamples);
  24621. /** The sample-rate of the stream. */
  24622. double sampleRate;
  24623. /** The number of bits per sample, e.g. 16, 24, 32. */
  24624. unsigned int bitsPerSample;
  24625. /** The total number of samples in the audio stream. */
  24626. int64 lengthInSamples;
  24627. /** The total number of channels in the audio stream. */
  24628. unsigned int numChannels;
  24629. /** Indicates whether the data is floating-point or fixed. */
  24630. bool usesFloatingPointData;
  24631. /** A set of metadata values that the reader has pulled out of the stream.
  24632. Exactly what these values are depends on the format, so you can
  24633. check out the format implementation code to see what kind of stuff
  24634. they understand.
  24635. */
  24636. StringPairArray metadataValues;
  24637. /** The input stream, for use by subclasses. */
  24638. InputStream* input;
  24639. /** Subclasses must implement this method to perform the low-level read operation.
  24640. Callers should use read() instead of calling this directly.
  24641. @param destSamples the array of destination buffers to fill. Some of these
  24642. pointers may be null
  24643. @param numDestChannels the number of items in the destSamples array. This
  24644. value is guaranteed not to be greater than the number of
  24645. channels that this reader object contains
  24646. @param startOffsetInDestBuffer the number of samples from the start of the
  24647. dest data at which to begin writing
  24648. @param startSampleInFile the number of samples into the source data at which
  24649. to begin reading. This value is guaranteed to be >= 0.
  24650. @param numSamples the number of samples to read
  24651. */
  24652. virtual bool readSamples (int** destSamples,
  24653. int numDestChannels,
  24654. int startOffsetInDestBuffer,
  24655. int64 startSampleInFile,
  24656. int numSamples) = 0;
  24657. juce_UseDebuggingNewOperator
  24658. private:
  24659. String formatName;
  24660. AudioFormatReader (const AudioFormatReader&);
  24661. const AudioFormatReader& operator= (const AudioFormatReader&);
  24662. };
  24663. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  24664. /********* End of inlined file: juce_AudioFormatReader.h *********/
  24665. /**
  24666. A type of AudioSource that will read from an AudioFormatReader.
  24667. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  24668. */
  24669. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  24670. {
  24671. public:
  24672. /** Creates an AudioFormatReaderSource for a given reader.
  24673. @param sourceReader the reader to use as the data source
  24674. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  24675. when this object is deleted; if false it will be
  24676. left up to the caller to manage its lifetime
  24677. */
  24678. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  24679. const bool deleteReaderWhenThisIsDeleted);
  24680. /** Destructor. */
  24681. ~AudioFormatReaderSource();
  24682. /** Toggles loop-mode.
  24683. If set to true, it will continuously loop the input source. If false,
  24684. it will just emit silence after the source has finished.
  24685. @see isLooping
  24686. */
  24687. void setLooping (const bool shouldLoop) throw();
  24688. /** Returns whether loop-mode is turned on or not. */
  24689. bool isLooping() const { return looping; }
  24690. /** Returns the reader that's being used. */
  24691. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  24692. /** Implementation of the AudioSource method. */
  24693. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24694. /** Implementation of the AudioSource method. */
  24695. void releaseResources();
  24696. /** Implementation of the AudioSource method. */
  24697. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24698. /** Implements the PositionableAudioSource method. */
  24699. void setNextReadPosition (int newPosition);
  24700. /** Implements the PositionableAudioSource method. */
  24701. int getNextReadPosition() const;
  24702. /** Implements the PositionableAudioSource method. */
  24703. int getTotalLength() const;
  24704. juce_UseDebuggingNewOperator
  24705. private:
  24706. AudioFormatReader* reader;
  24707. bool deleteReader;
  24708. int volatile nextPlayPos;
  24709. bool volatile looping;
  24710. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  24711. AudioFormatReaderSource (const AudioFormatReaderSource&);
  24712. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  24713. };
  24714. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  24715. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  24716. #endif
  24717. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  24718. #endif
  24719. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24720. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  24721. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24722. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24723. /**
  24724. Wrapper class to continuously stream audio from an audio source to an
  24725. AudioIODevice.
  24726. This object acts as an AudioIODeviceCallback, so can be attached to an
  24727. output device, and will stream audio from an AudioSource.
  24728. */
  24729. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  24730. {
  24731. public:
  24732. /** Creates an empty AudioSourcePlayer. */
  24733. AudioSourcePlayer();
  24734. /** Destructor.
  24735. Make sure this object isn't still being used by an AudioIODevice before
  24736. deleting it!
  24737. */
  24738. virtual ~AudioSourcePlayer();
  24739. /** Changes the current audio source to play from.
  24740. If the source passed in is already being used, this method will do nothing.
  24741. If the source is not null, its prepareToPlay() method will be called
  24742. before it starts being used for playback.
  24743. If there's another source currently playing, its releaseResources() method
  24744. will be called after it has been swapped for the new one.
  24745. @param newSource the new source to use - this will NOT be deleted
  24746. by this object when no longer needed, so it's the
  24747. caller's responsibility to manage it.
  24748. */
  24749. void setSource (AudioSource* newSource);
  24750. /** Returns the source that's playing.
  24751. May return 0 if there's no source.
  24752. */
  24753. AudioSource* getCurrentSource() const throw() { return source; }
  24754. /** Sets a gain to apply to the audio data. */
  24755. void setGain (const float newGain) throw();
  24756. /** Implementation of the AudioIODeviceCallback method. */
  24757. void audioDeviceIOCallback (const float** inputChannelData,
  24758. int totalNumInputChannels,
  24759. float** outputChannelData,
  24760. int totalNumOutputChannels,
  24761. int numSamples);
  24762. /** Implementation of the AudioIODeviceCallback method. */
  24763. void audioDeviceAboutToStart (AudioIODevice* device);
  24764. /** Implementation of the AudioIODeviceCallback method. */
  24765. void audioDeviceStopped();
  24766. juce_UseDebuggingNewOperator
  24767. private:
  24768. CriticalSection readLock;
  24769. AudioSource* source;
  24770. double sampleRate;
  24771. int bufferSize;
  24772. float* channels [128];
  24773. float* outputChans [128];
  24774. const float* inputChans [128];
  24775. AudioSampleBuffer tempBuffer;
  24776. float lastGain, gain;
  24777. AudioSourcePlayer (const AudioSourcePlayer&);
  24778. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  24779. };
  24780. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  24781. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  24782. #endif
  24783. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24784. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  24785. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24786. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24787. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  24788. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24789. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24790. /**
  24791. An AudioSource which takes another source as input, and buffers it using a thread.
  24792. Create this as a wrapper around another thread, and it will read-ahead with
  24793. a background thread to smooth out playback. You can either create one of these
  24794. directly, or use it indirectly using an AudioTransportSource.
  24795. @see PositionableAudioSource, AudioTransportSource
  24796. */
  24797. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  24798. {
  24799. public:
  24800. /** Creates a BufferingAudioSource.
  24801. @param source the input source to read from
  24802. @param deleteSourceWhenDeleted if true, then the input source object will
  24803. be deleted when this object is deleted
  24804. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  24805. */
  24806. BufferingAudioSource (PositionableAudioSource* source,
  24807. const bool deleteSourceWhenDeleted,
  24808. int numberOfSamplesToBuffer);
  24809. /** Destructor.
  24810. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  24811. flag was set in the constructor.
  24812. */
  24813. ~BufferingAudioSource();
  24814. /** Implementation of the AudioSource method. */
  24815. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24816. /** Implementation of the AudioSource method. */
  24817. void releaseResources();
  24818. /** Implementation of the AudioSource method. */
  24819. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24820. /** Implements the PositionableAudioSource method. */
  24821. void setNextReadPosition (int newPosition);
  24822. /** Implements the PositionableAudioSource method. */
  24823. int getNextReadPosition() const;
  24824. /** Implements the PositionableAudioSource method. */
  24825. int getTotalLength() const { return source->getTotalLength(); }
  24826. /** Implements the PositionableAudioSource method. */
  24827. bool isLooping() const { return source->isLooping(); }
  24828. juce_UseDebuggingNewOperator
  24829. private:
  24830. PositionableAudioSource* source;
  24831. bool deleteSourceWhenDeleted;
  24832. int numberOfSamplesToBuffer;
  24833. AudioSampleBuffer buffer;
  24834. CriticalSection bufferStartPosLock;
  24835. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  24836. bool wasSourceLooping;
  24837. double volatile sampleRate;
  24838. friend class SharedBufferingAudioSourceThread;
  24839. bool readNextBufferChunk();
  24840. void readBufferSection (int start, int length, int bufferOffset);
  24841. BufferingAudioSource (const BufferingAudioSource&);
  24842. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  24843. };
  24844. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24845. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  24846. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  24847. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24848. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24849. /**
  24850. A type of AudioSource that takes an input source and changes its sample rate.
  24851. @see AudioSource
  24852. */
  24853. class JUCE_API ResamplingAudioSource : public AudioSource
  24854. {
  24855. public:
  24856. /** Creates a ResamplingAudioSource for a given input source.
  24857. @param inputSource the input source to read from
  24858. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24859. this object is deleted
  24860. */
  24861. ResamplingAudioSource (AudioSource* const inputSource,
  24862. const bool deleteInputWhenDeleted);
  24863. /** Destructor. */
  24864. ~ResamplingAudioSource();
  24865. /** Changes the resampling ratio.
  24866. (This value can be changed at any time, even while the source is running).
  24867. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  24868. values will speed it up; lower values will slow it
  24869. down. The ratio must be greater than 0
  24870. */
  24871. void setResamplingRatio (const double samplesInPerOutputSample);
  24872. /** Returns the current resampling ratio.
  24873. This is the value that was set by setResamplingRatio().
  24874. */
  24875. double getResamplingRatio() const throw() { return ratio; }
  24876. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24877. void releaseResources();
  24878. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24879. juce_UseDebuggingNewOperator
  24880. private:
  24881. AudioSource* const input;
  24882. const bool deleteInputWhenDeleted;
  24883. double ratio, lastRatio;
  24884. AudioSampleBuffer buffer;
  24885. int bufferPos, sampsInBuffer;
  24886. double subSampleOffset;
  24887. double coefficients[6];
  24888. CriticalSection ratioLock;
  24889. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  24890. void createLowPass (const double proportionalRate);
  24891. struct FilterState
  24892. {
  24893. double x1, x2, y1, y2;
  24894. };
  24895. FilterState filterStates[2];
  24896. void resetFilters();
  24897. void applyFilter (float* samples, int num, FilterState& fs);
  24898. ResamplingAudioSource (const ResamplingAudioSource&);
  24899. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  24900. };
  24901. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24902. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  24903. /**
  24904. An AudioSource that takes a PositionableAudioSource and allows it to be
  24905. played, stopped, started, etc.
  24906. This can also be told use a buffer and background thread to read ahead, and
  24907. if can correct for different sample-rates.
  24908. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  24909. to control playback of an audio file.
  24910. @see AudioSource, AudioSourcePlayer
  24911. */
  24912. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  24913. public ChangeBroadcaster
  24914. {
  24915. public:
  24916. /** Creates an AudioTransportSource.
  24917. After creating one of these, use the setSource() method to select an input source.
  24918. */
  24919. AudioTransportSource();
  24920. /** Destructor. */
  24921. ~AudioTransportSource();
  24922. /** Sets the reader that is being used as the input source.
  24923. This will stop playback, reset the position to 0 and change to the new reader.
  24924. The source passed in will not be deleted by this object, so must be managed by
  24925. the caller.
  24926. @param newSource the new input source to use. This may be zero
  24927. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  24928. is zero, no reading ahead will be done; if it's
  24929. greater than zero, a BufferingAudioSource will be used
  24930. to do the reading-ahead
  24931. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  24932. rate of the source, and playback will be sample-rate
  24933. adjusted to maintain playback at the correct pitch. If
  24934. this is 0, no sample-rate adjustment will be performed
  24935. */
  24936. void setSource (PositionableAudioSource* const newSource,
  24937. int readAheadBufferSize = 0,
  24938. double sourceSampleRateToCorrectFor = 0.0);
  24939. /** Changes the current playback position in the source stream.
  24940. The next time the getNextAudioBlock() method is called, this
  24941. is the time from which it'll read data.
  24942. @see getPosition
  24943. */
  24944. void setPosition (double newPosition);
  24945. /** Returns the position that the next data block will be read from
  24946. This is a time in seconds.
  24947. */
  24948. double getCurrentPosition() const;
  24949. /** Returns true if the player has stopped because its input stream ran out of data.
  24950. */
  24951. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24952. /** Starts playing (if a source has been selected).
  24953. If it starts playing, this will send a message to any ChangeListeners
  24954. that are registered with this object.
  24955. */
  24956. void start();
  24957. /** Stops playing.
  24958. If it's actually playing, this will send a message to any ChangeListeners
  24959. that are registered with this object.
  24960. */
  24961. void stop();
  24962. /** Returns true if it's currently playing. */
  24963. bool isPlaying() const throw() { return playing; }
  24964. /** Changes the gain to apply to the output.
  24965. @param newGain a factor by which to multiply the outgoing samples,
  24966. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24967. */
  24968. void setGain (const float newGain) throw();
  24969. /** Returns the current gain setting.
  24970. @see setGain
  24971. */
  24972. float getGain() const throw() { return gain; }
  24973. /** Implementation of the AudioSource method. */
  24974. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24975. /** Implementation of the AudioSource method. */
  24976. void releaseResources();
  24977. /** Implementation of the AudioSource method. */
  24978. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24979. /** Implements the PositionableAudioSource method. */
  24980. void setNextReadPosition (int newPosition);
  24981. /** Implements the PositionableAudioSource method. */
  24982. int getNextReadPosition() const;
  24983. /** Implements the PositionableAudioSource method. */
  24984. int getTotalLength() const;
  24985. /** Implements the PositionableAudioSource method. */
  24986. bool isLooping() const;
  24987. juce_UseDebuggingNewOperator
  24988. private:
  24989. PositionableAudioSource* source;
  24990. ResamplingAudioSource* resamplerSource;
  24991. BufferingAudioSource* bufferingSource;
  24992. PositionableAudioSource* positionableSource;
  24993. AudioSource* masterSource;
  24994. CriticalSection callbackLock;
  24995. float volatile gain, lastGain;
  24996. bool volatile playing, stopped;
  24997. double sampleRate, sourceSampleRate;
  24998. int blockSize, readAheadBufferSize;
  24999. bool isPrepared, inputStreamEOF;
  25000. AudioTransportSource (const AudioTransportSource&);
  25001. const AudioTransportSource& operator= (const AudioTransportSource&);
  25002. };
  25003. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  25004. /********* End of inlined file: juce_AudioTransportSource.h *********/
  25005. #endif
  25006. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  25007. #endif
  25008. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  25009. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  25010. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  25011. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  25012. /**
  25013. An AudioSource that takes the audio from another source, and re-maps its
  25014. input and output channels to a different arrangement.
  25015. You can use this to increase or decrease the number of channels that an
  25016. audio source uses, or to re-order those channels.
  25017. Call the reset() method before using it to set up a default mapping, and then
  25018. the setInputChannelMapping() and setOutputChannelMapping() methods to
  25019. create an appropriate mapping, otherwise no channels will be connected and
  25020. it'll produce silence.
  25021. @see AudioSource
  25022. */
  25023. class ChannelRemappingAudioSource : public AudioSource
  25024. {
  25025. public:
  25026. /** Creates a remapping source that will pass on audio from the given input.
  25027. @param source the input source to use. Make sure that this doesn't
  25028. get deleted before the ChannelRemappingAudioSource object
  25029. @param deleteSourceWhenDeleted if true, the input source will be deleted
  25030. when this object is deleted, if false, the caller is
  25031. responsible for its deletion
  25032. */
  25033. ChannelRemappingAudioSource (AudioSource* const source,
  25034. const bool deleteSourceWhenDeleted);
  25035. /** Destructor. */
  25036. ~ChannelRemappingAudioSource();
  25037. /** Specifies a number of channels that this audio source must produce from its
  25038. getNextAudioBlock() callback.
  25039. */
  25040. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  25041. /** Clears any mapped channels.
  25042. After this, no channels are mapped, so this object will produce silence. Create
  25043. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  25044. */
  25045. void clearAllMappings() throw();
  25046. /** Creates an input channel mapping.
  25047. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  25048. data will be sent to destChannelIndex of our input source.
  25049. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  25050. source specified when this object was created).
  25051. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  25052. during our getNextAudioBlock() callback
  25053. */
  25054. void setInputChannelMapping (const int destChannelIndex,
  25055. const int sourceChannelIndex) throw();
  25056. /** Creates an output channel mapping.
  25057. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  25058. our input audio source will be copied to channel destChannelIndex of the final buffer.
  25059. @param sourceChannelIndex the index of an output channel coming from our input audio source
  25060. (i.e. the source specified when this object was created).
  25061. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  25062. during our getNextAudioBlock() callback
  25063. */
  25064. void setOutputChannelMapping (const int sourceChannelIndex,
  25065. const int destChannelIndex) throw();
  25066. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  25067. our input audio source.
  25068. */
  25069. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  25070. /** Returns the output channel to which channel outputChannelIndex of our input audio
  25071. source will be sent to.
  25072. */
  25073. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  25074. /** Returns an XML object to encapsulate the state of the mappings.
  25075. @see restoreFromXml
  25076. */
  25077. XmlElement* createXml() const throw();
  25078. /** Restores the mappings from an XML object created by createXML().
  25079. @see createXml
  25080. */
  25081. void restoreFromXml (const XmlElement& e) throw();
  25082. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  25083. void releaseResources();
  25084. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  25085. juce_UseDebuggingNewOperator
  25086. private:
  25087. int requiredNumberOfChannels;
  25088. Array <int> remappedInputs, remappedOutputs;
  25089. AudioSource* const source;
  25090. const bool deleteSourceWhenDeleted;
  25091. AudioSampleBuffer buffer;
  25092. AudioSourceChannelInfo remappedInfo;
  25093. CriticalSection lock;
  25094. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  25095. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  25096. };
  25097. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  25098. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  25099. #endif
  25100. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  25101. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  25102. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  25103. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  25104. /**
  25105. An AudioSource that performs an IIR filter on another source.
  25106. */
  25107. class JUCE_API IIRFilterAudioSource : public AudioSource
  25108. {
  25109. public:
  25110. /** Creates a IIRFilterAudioSource for a given input source.
  25111. @param inputSource the input source to read from
  25112. @param deleteInputWhenDeleted if true, the input source will be deleted when
  25113. this object is deleted
  25114. */
  25115. IIRFilterAudioSource (AudioSource* const inputSource,
  25116. const bool deleteInputWhenDeleted);
  25117. /** Destructor. */
  25118. ~IIRFilterAudioSource();
  25119. /** Changes the filter to use the same parameters as the one being passed in.
  25120. */
  25121. void setFilterParameters (const IIRFilter& newSettings);
  25122. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  25123. void releaseResources();
  25124. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  25125. juce_UseDebuggingNewOperator
  25126. private:
  25127. AudioSource* const input;
  25128. const bool deleteInputWhenDeleted;
  25129. OwnedArray <IIRFilter> iirFilters;
  25130. IIRFilterAudioSource (const IIRFilterAudioSource&);
  25131. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  25132. };
  25133. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  25134. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  25135. #endif
  25136. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  25137. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  25138. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  25139. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  25140. /**
  25141. An AudioSource that mixes together the output of a set of other AudioSources.
  25142. Input sources can be added and removed while the mixer is running as long as their
  25143. prepareToPlay() and releaseResources() methods are called before and after adding
  25144. them to the mixer.
  25145. */
  25146. class JUCE_API MixerAudioSource : public AudioSource
  25147. {
  25148. public:
  25149. /** Creates a MixerAudioSource.
  25150. */
  25151. MixerAudioSource();
  25152. /** Destructor. */
  25153. ~MixerAudioSource();
  25154. /** Adds an input source to the mixer.
  25155. If the mixer is running you'll need to make sure that the input source
  25156. is ready to play by calling its prepareToPlay() method before adding it.
  25157. If the mixer is stopped, then its input sources will be automatically
  25158. prepared when the mixer's prepareToPlay() method is called.
  25159. @param newInput the source to add to the mixer
  25160. @param deleteWhenRemoved if true, then this source will be deleted when
  25161. the mixer is deleted or when removeAllInputs() is
  25162. called (unless the source is previously removed
  25163. with the removeInputSource method)
  25164. */
  25165. void addInputSource (AudioSource* newInput,
  25166. const bool deleteWhenRemoved);
  25167. /** Removes an input source.
  25168. If the mixer is running, this will remove the source but not call its
  25169. releaseResources() method, so the caller might want to do this manually.
  25170. @param input the source to remove
  25171. @param deleteSource whether to delete this source after it's been removed
  25172. */
  25173. void removeInputSource (AudioSource* input,
  25174. const bool deleteSource);
  25175. /** Removes all the input sources.
  25176. If the mixer is running, this will remove the sources but not call their
  25177. releaseResources() method, so the caller might want to do this manually.
  25178. Any sources which were added with the deleteWhenRemoved flag set will be
  25179. deleted by this method.
  25180. */
  25181. void removeAllInputs();
  25182. /** Implementation of the AudioSource method.
  25183. This will call prepareToPlay() on all its input sources.
  25184. */
  25185. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  25186. /** Implementation of the AudioSource method.
  25187. This will call releaseResources() on all its input sources.
  25188. */
  25189. void releaseResources();
  25190. /** Implementation of the AudioSource method. */
  25191. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  25192. juce_UseDebuggingNewOperator
  25193. private:
  25194. VoidArray inputs;
  25195. BitArray inputsToDelete;
  25196. CriticalSection lock;
  25197. AudioSampleBuffer tempBuffer;
  25198. double currentSampleRate;
  25199. int bufferSizeExpected;
  25200. MixerAudioSource (const MixerAudioSource&);
  25201. const MixerAudioSource& operator= (const MixerAudioSource&);
  25202. };
  25203. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  25204. /********* End of inlined file: juce_MixerAudioSource.h *********/
  25205. #endif
  25206. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  25207. #endif
  25208. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  25209. #endif
  25210. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  25211. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  25212. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  25213. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  25214. /**
  25215. A simple AudioSource that generates a sine wave.
  25216. */
  25217. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  25218. {
  25219. public:
  25220. /** Creates a ToneGeneratorAudioSource. */
  25221. ToneGeneratorAudioSource();
  25222. /** Destructor. */
  25223. ~ToneGeneratorAudioSource();
  25224. /** Sets the signal's amplitude. */
  25225. void setAmplitude (const float newAmplitude);
  25226. /** Sets the signal's frequency. */
  25227. void setFrequency (const double newFrequencyHz);
  25228. /** Implementation of the AudioSource method. */
  25229. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  25230. /** Implementation of the AudioSource method. */
  25231. void releaseResources();
  25232. /** Implementation of the AudioSource method. */
  25233. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  25234. juce_UseDebuggingNewOperator
  25235. private:
  25236. double frequency, sampleRate;
  25237. double currentPhase, phasePerSample;
  25238. float amplitude;
  25239. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  25240. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  25241. };
  25242. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  25243. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  25244. #endif
  25245. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25246. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  25247. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25248. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25249. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  25250. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25251. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25252. class AudioDeviceManager;
  25253. class Component;
  25254. /**
  25255. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  25256. To get a list of available audio driver types, use the createDeviceTypes()
  25257. method. Each of the objects returned can then be used to list the available
  25258. devices of that type. E.g.
  25259. @code
  25260. OwnedArray <AudioIODeviceType> types;
  25261. AudioIODeviceType::createDeviceTypes (types);
  25262. for (int i = 0; i < types.size(); ++i)
  25263. {
  25264. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  25265. types[i]->scanForDevices(); // This must be called before getting the list of devices
  25266. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  25267. for (int j = 0; j < deviceNames.size(); ++j)
  25268. {
  25269. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  25270. ...
  25271. }
  25272. }
  25273. @endcode
  25274. For an easier way of managing audio devices and their settings, have a look at the
  25275. AudioDeviceManager class.
  25276. @see AudioIODevice, AudioDeviceManager
  25277. */
  25278. class JUCE_API AudioIODeviceType
  25279. {
  25280. public:
  25281. /** Returns the name of this type of driver that this object manages.
  25282. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  25283. */
  25284. const String& getTypeName() const throw() { return typeName; }
  25285. /** Refreshes the object's cached list of known devices.
  25286. This must be called at least once before calling getDeviceNames() or any of
  25287. the other device creation methods.
  25288. */
  25289. virtual void scanForDevices() = 0;
  25290. /** Returns the list of available devices of this type.
  25291. The scanForDevices() method must have been called to create this list.
  25292. @param wantInputNames only really used by DirectSound where devices are split up
  25293. into inputs and outputs, this indicates whether to use
  25294. the input or output name to refer to a pair of devices.
  25295. */
  25296. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  25297. /** Returns the name of the default device.
  25298. This will be one of the names from the getDeviceNames() list.
  25299. @param forInput if true, this means that a default input device should be
  25300. returned; if false, it should return the default output
  25301. */
  25302. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  25303. /** Returns the index of a given device in the list of device names.
  25304. If asInput is true, it shows the index in the inputs list, otherwise it
  25305. looks for it in the outputs list.
  25306. */
  25307. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  25308. /** Returns true if two different devices can be used for the input and output.
  25309. */
  25310. virtual bool hasSeparateInputsAndOutputs() const = 0;
  25311. /** Creates one of the devices of this type.
  25312. The deviceName must be one of the strings returned by getDeviceNames(), and
  25313. scanForDevices() must have been called before this method is used.
  25314. */
  25315. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  25316. const String& inputDeviceName) = 0;
  25317. struct DeviceSetupDetails
  25318. {
  25319. AudioDeviceManager* manager;
  25320. int minNumInputChannels, maxNumInputChannels;
  25321. int minNumOutputChannels, maxNumOutputChannels;
  25322. bool useStereoPairs;
  25323. };
  25324. /** Destructor. */
  25325. virtual ~AudioIODeviceType();
  25326. protected:
  25327. AudioIODeviceType (const tchar* const typeName);
  25328. private:
  25329. String typeName;
  25330. AudioIODeviceType (const AudioIODeviceType&);
  25331. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  25332. };
  25333. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25334. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  25335. /********* Start of inlined file: juce_MidiOutput.h *********/
  25336. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25337. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  25338. /**
  25339. Represents a midi output device.
  25340. To create one of these, use the static getDevices() method to find out what
  25341. outputs are available, then use the openDevice() method to try to open one.
  25342. @see MidiInput
  25343. */
  25344. class JUCE_API MidiOutput : private Thread
  25345. {
  25346. public:
  25347. /** Returns a list of the available midi output devices.
  25348. You can open one of the devices by passing its index into the
  25349. openDevice() method.
  25350. @see getDefaultDeviceIndex, openDevice
  25351. */
  25352. static const StringArray getDevices();
  25353. /** Returns the index of the default midi output device to use.
  25354. This refers to the index in the list returned by getDevices().
  25355. */
  25356. static int getDefaultDeviceIndex();
  25357. /** Tries to open one of the midi output devices.
  25358. This will return a MidiOutput object if it manages to open it. You can then
  25359. send messages to this device, and delete it when no longer needed.
  25360. If the device can't be opened, this will return a null pointer.
  25361. @param deviceIndex the index of a device from the list returned by getDevices()
  25362. @see getDevices
  25363. */
  25364. static MidiOutput* openDevice (int deviceIndex);
  25365. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25366. /** This will try to create a new midi output device (Not available on Windows).
  25367. This will attempt to create a new midi output device that other apps can connect
  25368. to and use as their midi input.
  25369. Returns 0 if a device can't be created.
  25370. @param deviceName the name to use for the new device
  25371. */
  25372. static MidiOutput* createNewDevice (const String& deviceName);
  25373. #endif
  25374. /** Destructor. */
  25375. virtual ~MidiOutput();
  25376. /** Makes this device output a midi message.
  25377. @see MidiMessage
  25378. */
  25379. virtual void sendMessageNow (const MidiMessage& message);
  25380. /** Sends a midi reset to the device. */
  25381. virtual void reset();
  25382. /** Returns the current volume setting for this device. */
  25383. virtual bool getVolume (float& leftVol,
  25384. float& rightVol);
  25385. /** Changes the overall volume for this device. */
  25386. virtual void setVolume (float leftVol,
  25387. float rightVol);
  25388. /** This lets you supply a block of messages that will be sent out at some point
  25389. in the future.
  25390. The MidiOutput class has an internal thread that can send out timestamped
  25391. messages - this appends a set of messages to its internal buffer, ready for
  25392. sending.
  25393. This will only work if you've already started the thread with startBackgroundThread().
  25394. A time is supplied, at which the block of messages should be sent. This time uses
  25395. the same time base as Time::getMillisecondCounter(), and must be in the future.
  25396. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  25397. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  25398. samplesPerSecondForBuffer value is needed to convert this sample position to a
  25399. real time.
  25400. */
  25401. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  25402. const double millisecondCounterToStartAt,
  25403. double samplesPerSecondForBuffer) throw();
  25404. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  25405. */
  25406. virtual void clearAllPendingMessages() throw();
  25407. /** Starts up a background thread so that the device can send blocks of data.
  25408. Call this to get the device ready, before using sendBlockOfMessages().
  25409. */
  25410. virtual void startBackgroundThread() throw();
  25411. /** Stops the background thread, and clears any pending midi events.
  25412. @see startBackgroundThread
  25413. */
  25414. virtual void stopBackgroundThread() throw();
  25415. juce_UseDebuggingNewOperator
  25416. protected:
  25417. void* internal;
  25418. struct PendingMessage
  25419. {
  25420. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  25421. MidiMessage message;
  25422. PendingMessage* next;
  25423. juce_UseDebuggingNewOperator
  25424. };
  25425. CriticalSection lock;
  25426. PendingMessage* firstMessage;
  25427. MidiOutput() throw();
  25428. MidiOutput (const MidiOutput&);
  25429. void run();
  25430. };
  25431. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  25432. /********* End of inlined file: juce_MidiOutput.h *********/
  25433. /********* Start of inlined file: juce_ComboBox.h *********/
  25434. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  25435. #define __JUCE_COMBOBOX_JUCEHEADER__
  25436. /********* Start of inlined file: juce_Label.h *********/
  25437. #ifndef __JUCE_LABEL_JUCEHEADER__
  25438. #define __JUCE_LABEL_JUCEHEADER__
  25439. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  25440. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  25441. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  25442. /**
  25443. Object for monitoring a component, and later testing whether it's still valid.
  25444. Slightly obscure, this one, but it's used internally for making sure that
  25445. after some callbacks, a component hasn't been deleted. It's more reliable than
  25446. just using isValidComponent(), which can provide false-positives if a new
  25447. component is created at the same memory location as an old one.
  25448. */
  25449. class JUCE_API ComponentDeletionWatcher
  25450. {
  25451. public:
  25452. /** Creates a watcher for a given component.
  25453. The component must be valid at the time it's passed in.
  25454. */
  25455. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  25456. /** Destructor. */
  25457. ~ComponentDeletionWatcher() throw();
  25458. /** Returns true if the component has been deleted since the time that this
  25459. object was created.
  25460. */
  25461. bool hasBeenDeleted() const throw();
  25462. /** Returns the component that's being watched, or null if it has been deleted. */
  25463. const Component* getComponent() const throw();
  25464. juce_UseDebuggingNewOperator
  25465. private:
  25466. const Component* const componentToWatch;
  25467. const uint32 componentUID;
  25468. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  25469. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  25470. };
  25471. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  25472. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  25473. /********* Start of inlined file: juce_TextEditor.h *********/
  25474. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  25475. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  25476. class TextEditor;
  25477. class TextHolderComponent;
  25478. /**
  25479. Receives callbacks from a TextEditor component when it changes.
  25480. @see TextEditor::addListener
  25481. */
  25482. class JUCE_API TextEditorListener
  25483. {
  25484. public:
  25485. /** Destructor. */
  25486. virtual ~TextEditorListener() {}
  25487. /** Called when the user changes the text in some way. */
  25488. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  25489. /** Called when the user presses the return key. */
  25490. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  25491. /** Called when the user presses the escape key. */
  25492. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  25493. /** Called when the text editor loses focus. */
  25494. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  25495. };
  25496. /**
  25497. A component containing text that can be edited.
  25498. A TextEditor can either be in single- or multi-line mode, and supports mixed
  25499. fonts and colours.
  25500. @see TextEditorListener, Label
  25501. */
  25502. class JUCE_API TextEditor : public Component,
  25503. public SettableTooltipClient
  25504. {
  25505. public:
  25506. /** Creates a new, empty text editor.
  25507. @param componentName the name to pass to the component for it to use as its name
  25508. @param passwordCharacter if this is not zero, this character will be used as a replacement
  25509. for all characters that are drawn on screen - e.g. to create
  25510. a password-style textbox containing circular blobs instead of text,
  25511. you could set this value to 0x25cf, which is the unicode character
  25512. for a black splodge (not all fonts include this, though), or 0x2022,
  25513. which is a bullet (probably the best choice for linux).
  25514. */
  25515. TextEditor (const String& componentName = String::empty,
  25516. const tchar passwordCharacter = 0);
  25517. /** Destructor. */
  25518. virtual ~TextEditor();
  25519. /** Puts the editor into either multi- or single-line mode.
  25520. By default, the editor will be in single-line mode, so use this if you need a multi-line
  25521. editor.
  25522. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  25523. on if you want a multi-line editor with line-breaks.
  25524. @see isMultiLine, setReturnKeyStartsNewLine
  25525. */
  25526. void setMultiLine (const bool shouldBeMultiLine,
  25527. const bool shouldWordWrap = true);
  25528. /** Returns true if the editor is in multi-line mode.
  25529. */
  25530. bool isMultiLine() const throw();
  25531. /** Changes the behaviour of the return key.
  25532. If set to true, the return key will insert a new-line into the text; if false
  25533. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  25534. method. By default this is set to false, and when true it will only insert
  25535. new-lines when in multi-line mode (see setMultiLine()).
  25536. */
  25537. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  25538. /** Returns the value set by setReturnKeyStartsNewLine().
  25539. See setReturnKeyStartsNewLine() for more info.
  25540. */
  25541. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  25542. /** Indicates whether the tab key should be accepted and used to input a tab character,
  25543. or whether it gets ignored.
  25544. By default the tab key is ignored, so that it can be used to switch keyboard focus
  25545. between components.
  25546. */
  25547. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  25548. /** Returns true if the tab key is being used for input.
  25549. @see setTabKeyUsedAsCharacter
  25550. */
  25551. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  25552. /** Changes the editor to read-only mode.
  25553. By default, the text editor is not read-only. If you're making it read-only, you
  25554. might also want to call setCaretVisible (false) to get rid of the caret.
  25555. The text can still be highlighted and copied when in read-only mode.
  25556. @see isReadOnly, setCaretVisible
  25557. */
  25558. void setReadOnly (const bool shouldBeReadOnly);
  25559. /** Returns true if the editor is in read-only mode.
  25560. */
  25561. bool isReadOnly() const throw();
  25562. /** Makes the caret visible or invisible.
  25563. By default the caret is visible.
  25564. @see setCaretColour, setCaretPosition
  25565. */
  25566. void setCaretVisible (const bool shouldBeVisible) throw();
  25567. /** Returns true if the caret is enabled.
  25568. @see setCaretVisible
  25569. */
  25570. bool isCaretVisible() const throw() { return caretVisible; }
  25571. /** Enables/disables a vertical scrollbar.
  25572. (This only applies when in multi-line mode). When the text gets too long to fit
  25573. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  25574. this is enabled, the scrollbar will be hidden unless it's needed.
  25575. By default the scrollbar is enabled.
  25576. */
  25577. void setScrollbarsShown (bool shouldBeEnabled) throw();
  25578. /** Returns true if scrollbars are enabled.
  25579. @see setScrollbarsShown
  25580. */
  25581. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  25582. /** Changes the password character used to disguise the text.
  25583. @param passwordCharacter if this is not zero, this character will be used as a replacement
  25584. for all characters that are drawn on screen - e.g. to create
  25585. a password-style textbox containing circular blobs instead of text,
  25586. you could set this value to 0x25cf, which is the unicode character
  25587. for a black splodge (not all fonts include this, though), or 0x2022,
  25588. which is a bullet (probably the best choice for linux).
  25589. */
  25590. void setPasswordCharacter (const tchar passwordCharacter) throw();
  25591. /** Returns the current password character.
  25592. @see setPasswordCharacter
  25593. l */
  25594. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  25595. /** Allows a right-click menu to appear for the editor.
  25596. (This defaults to being enabled).
  25597. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  25598. of options such as cut/copy/paste, undo/redo, etc.
  25599. */
  25600. void setPopupMenuEnabled (const bool menuEnabled) throw();
  25601. /** Returns true if the right-click menu is enabled.
  25602. @see setPopupMenuEnabled
  25603. */
  25604. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  25605. /** Returns true if a popup-menu is currently being displayed.
  25606. */
  25607. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  25608. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  25609. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25610. methods.
  25611. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25612. */
  25613. enum ColourIds
  25614. {
  25615. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  25616. transparent if necessary. */
  25617. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  25618. that because the editor can contain multiple colours, calling this
  25619. method won't change the colour of existing text - to do that, call
  25620. applyFontToAllText() after calling this method.*/
  25621. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  25622. the text - this can be transparent if you don't want to show any
  25623. highlighting.*/
  25624. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  25625. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  25626. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  25627. the edge of the component. */
  25628. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  25629. the edge of the component when it has focus. */
  25630. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  25631. around the edge of the editor. */
  25632. };
  25633. /** Sets the font to use for newly added text.
  25634. This will change the font that will be used next time any text is added or entered
  25635. into the editor. It won't change the font of any existing text - to do that, use
  25636. applyFontToAllText() instead.
  25637. @see applyFontToAllText
  25638. */
  25639. void setFont (const Font& newFont) throw();
  25640. /** Applies a font to all the text in the editor.
  25641. This will also set the current font to use for any new text that's added.
  25642. @see setFont
  25643. */
  25644. void applyFontToAllText (const Font& newFont);
  25645. /** Returns the font that's currently being used for new text.
  25646. @see setFont
  25647. */
  25648. const Font getFont() const throw();
  25649. /** If set to true, focusing on the editor will highlight all its text.
  25650. (Set to false by default).
  25651. This is useful for boxes where you expect the user to re-enter all the
  25652. text when they focus on the component, rather than editing what's already there.
  25653. */
  25654. void setSelectAllWhenFocused (const bool b) throw();
  25655. /** Sets limits on the characters that can be entered.
  25656. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  25657. limit is set
  25658. @param allowedCharacters if this is non-empty, then only characters that occur in
  25659. this string are allowed to be entered into the editor.
  25660. */
  25661. void setInputRestrictions (const int maxTextLength,
  25662. const String& allowedCharacters = String::empty) throw();
  25663. /** When the text editor is empty, it can be set to display a message.
  25664. This is handy for things like telling the user what to type in the box - the
  25665. string is only displayed, it's not taken to actually be the contents of
  25666. the editor.
  25667. */
  25668. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  25669. /** Changes the size of the scrollbars that are used.
  25670. Handy if you need smaller scrollbars for a small text box.
  25671. */
  25672. void setScrollBarThickness (const int newThicknessPixels);
  25673. /** Shows or hides the buttons on any scrollbars that are used.
  25674. @see ScrollBar::setButtonVisibility
  25675. */
  25676. void setScrollBarButtonVisibility (const bool buttonsVisible);
  25677. /** Registers a listener to be told when things happen to the text.
  25678. @see removeListener
  25679. */
  25680. void addListener (TextEditorListener* const newListener) throw();
  25681. /** Deregisters a listener.
  25682. @see addListener
  25683. */
  25684. void removeListener (TextEditorListener* const listenerToRemove) throw();
  25685. /** Returns the entire contents of the editor. */
  25686. const String getText() const throw();
  25687. /** Returns a section of the contents of the editor. */
  25688. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  25689. /** Returns true if there are no characters in the editor.
  25690. This is more efficient than calling getText().isEmpty().
  25691. */
  25692. bool isEmpty() const throw();
  25693. /** Sets the entire content of the editor.
  25694. This will clear the editor and insert the given text (using the current text colour
  25695. and font). You can set the current text colour using
  25696. @code setColour (TextEditor::textColourId, ...);
  25697. @endcode
  25698. @param newText the text to add
  25699. @param sendTextChangeMessage if true, this will cause a change message to
  25700. be sent to all the listeners.
  25701. @see insertText
  25702. */
  25703. void setText (const String& newText,
  25704. const bool sendTextChangeMessage = true);
  25705. /** Inserts some text at the current cursor position.
  25706. If a section of the text is highlighted, it will be replaced by
  25707. this string, otherwise it will be inserted.
  25708. To delete a section of text, you can use setHighlightedRegion() to
  25709. highlight it, and call insertTextAtCursor (String::empty).
  25710. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  25711. */
  25712. void insertTextAtCursor (String textToInsert);
  25713. /** Deletes all the text from the editor. */
  25714. void clear();
  25715. /** Deletes the currently selected region, and puts it on the clipboard.
  25716. @see copy, paste, SystemClipboard
  25717. */
  25718. void cut();
  25719. /** Copies any currently selected region to the clipboard.
  25720. @see cut, paste, SystemClipboard
  25721. */
  25722. void copy();
  25723. /** Pastes the contents of the clipboard into the editor at the cursor position.
  25724. @see cut, copy, SystemClipboard
  25725. */
  25726. void paste();
  25727. /** Moves the caret to be in front of a given character.
  25728. @see getCaretPosition
  25729. */
  25730. void setCaretPosition (const int newIndex) throw();
  25731. /** Returns the current index of the caret.
  25732. @see setCaretPosition
  25733. */
  25734. int getCaretPosition() const throw();
  25735. /** Attempts to scroll the text editor so that the caret ends up at
  25736. a specified position.
  25737. This won't affect the caret's position within the text, it tries to scroll
  25738. the entire editor vertically and horizontally so that the caret is sitting
  25739. at the given position (relative to the top-left of this component).
  25740. Depending on the amount of text available, it might not be possible to
  25741. scroll far enough for the caret to reach this exact position, but it
  25742. will go as far as it can in that direction.
  25743. */
  25744. void scrollEditorToPositionCaret (const int desiredCaretX,
  25745. const int desiredCaretY) throw();
  25746. /** Get the graphical position of the caret.
  25747. The rectangle returned is relative to the component's top-left corner.
  25748. @see scrollEditorToPositionCaret
  25749. */
  25750. const Rectangle getCaretRectangle() throw();
  25751. /** Selects a section of the text.
  25752. */
  25753. void setHighlightedRegion (int startIndex,
  25754. int numberOfCharactersToHighlight) throw();
  25755. /** Returns the first character that is selected.
  25756. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  25757. will return 0.
  25758. @see setHighlightedRegion, getHighlightedRegionLength
  25759. */
  25760. int getHighlightedRegionStart() const throw() { return selectionStart; }
  25761. /** Returns the number of characters that are selected.
  25762. @see setHighlightedRegion, getHighlightedRegionStart
  25763. */
  25764. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  25765. /** Returns the section of text that is currently selected. */
  25766. const String getHighlightedText() const throw();
  25767. /** Finds the index of the character at a given position.
  25768. The co-ordinates are relative to the component's top-left.
  25769. */
  25770. int getTextIndexAt (const int x, const int y) throw();
  25771. /** Counts the number of characters in the text.
  25772. This is quicker than getting the text as a string if you just need to know
  25773. the length.
  25774. */
  25775. int getTotalNumChars() throw();
  25776. /** Returns the total width of the text, as it is currently laid-out.
  25777. This may be larger than the size of the TextEditor, and can change when
  25778. the TextEditor is resized or the text changes.
  25779. */
  25780. int getTextWidth() const throw();
  25781. /** Returns the maximum height of the text, as it is currently laid-out.
  25782. This may be larger than the size of the TextEditor, and can change when
  25783. the TextEditor is resized or the text changes.
  25784. */
  25785. int getTextHeight() const throw();
  25786. /** Changes the size of the gap at the top and left-edge of the editor.
  25787. By default there's a gap of 4 pixels.
  25788. */
  25789. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  25790. /** Changes the size of border left around the edge of the component.
  25791. @see getBorder
  25792. */
  25793. void setBorder (const BorderSize& border) throw();
  25794. /** Returns the size of border around the edge of the component.
  25795. @see setBorder
  25796. */
  25797. const BorderSize getBorder() const throw();
  25798. /** Used to disable the auto-scrolling which keeps the cursor visible.
  25799. If true (the default), the editor will scroll when the cursor moves offscreen. If
  25800. set to false, it won't.
  25801. */
  25802. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  25803. /** @internal */
  25804. void paint (Graphics& g);
  25805. /** @internal */
  25806. void paintOverChildren (Graphics& g);
  25807. /** @internal */
  25808. void mouseDown (const MouseEvent& e);
  25809. /** @internal */
  25810. void mouseUp (const MouseEvent& e);
  25811. /** @internal */
  25812. void mouseDrag (const MouseEvent& e);
  25813. /** @internal */
  25814. void mouseDoubleClick (const MouseEvent& e);
  25815. /** @internal */
  25816. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25817. /** @internal */
  25818. bool keyPressed (const KeyPress& key);
  25819. /** @internal */
  25820. bool keyStateChanged (const bool isKeyDown);
  25821. /** @internal */
  25822. void focusGained (FocusChangeType cause);
  25823. /** @internal */
  25824. void focusLost (FocusChangeType cause);
  25825. /** @internal */
  25826. void resized();
  25827. /** @internal */
  25828. void enablementChanged();
  25829. /** @internal */
  25830. void colourChanged();
  25831. juce_UseDebuggingNewOperator
  25832. protected:
  25833. /** This adds the items to the popup menu.
  25834. By default it adds the cut/copy/paste items, but you can override this if
  25835. you need to replace these with your own items.
  25836. If you want to add your own items to the existing ones, you can override this,
  25837. call the base class's addPopupMenuItems() method, then append your own items.
  25838. When the menu has been shown, performPopupMenuAction() will be called to
  25839. perform the item that the user has chosen.
  25840. The default menu items will be added using item IDs in the range
  25841. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  25842. menu IDs.
  25843. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  25844. a pointer to the info about it, or may be null if the menu is being triggered
  25845. by some other means.
  25846. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  25847. */
  25848. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  25849. const MouseEvent* mouseClickEvent);
  25850. /** This is called to perform one of the items that was shown on the popup menu.
  25851. If you've overridden addPopupMenuItems(), you should also override this
  25852. to perform the actions that you've added.
  25853. If you've overridden addPopupMenuItems() but have still left the default items
  25854. on the menu, remember to call the superclass's performPopupMenuAction()
  25855. so that it can perform the default actions if that's what the user clicked on.
  25856. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  25857. */
  25858. virtual void performPopupMenuAction (const int menuItemID);
  25859. /** Scrolls the minimum distance needed to get the caret into view. */
  25860. void scrollToMakeSureCursorIsVisible() throw();
  25861. /** @internal */
  25862. void moveCaret (int newCaretPos) throw();
  25863. /** @internal */
  25864. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  25865. /** Used internally to dispatch a text-change message. */
  25866. void textChanged() throw();
  25867. /** Begins a new transaction in the UndoManager.
  25868. */
  25869. void newTransaction() throw();
  25870. /** Used internally to trigger an undo or redo. */
  25871. void doUndoRedo (const bool isRedo);
  25872. /** Can be overridden to intercept return key presses directly */
  25873. virtual void returnPressed();
  25874. /** Can be overridden to intercept escape key presses directly */
  25875. virtual void escapePressed();
  25876. /** @internal */
  25877. void handleCommandMessage (int commandId);
  25878. private:
  25879. Viewport* viewport;
  25880. TextHolderComponent* textHolder;
  25881. BorderSize borderSize;
  25882. bool readOnly : 1;
  25883. bool multiline : 1;
  25884. bool wordWrap : 1;
  25885. bool returnKeyStartsNewLine : 1;
  25886. bool caretVisible : 1;
  25887. bool popupMenuEnabled : 1;
  25888. bool selectAllTextWhenFocused : 1;
  25889. bool scrollbarVisible : 1;
  25890. bool wasFocused : 1;
  25891. bool caretFlashState : 1;
  25892. bool keepCursorOnScreen : 1;
  25893. bool tabKeyUsed : 1;
  25894. bool menuActive : 1;
  25895. UndoManager undoManager;
  25896. float cursorX, cursorY, cursorHeight;
  25897. int maxTextLength;
  25898. int selectionStart, selectionEnd;
  25899. int leftIndent, topIndent;
  25900. unsigned int lastTransactionTime;
  25901. Font currentFont;
  25902. int totalNumChars, caretPosition;
  25903. VoidArray sections;
  25904. String textToShowWhenEmpty;
  25905. Colour colourForTextWhenEmpty;
  25906. tchar passwordCharacter;
  25907. enum
  25908. {
  25909. notDragging,
  25910. draggingSelectionStart,
  25911. draggingSelectionEnd
  25912. } dragType;
  25913. String allowedCharacters;
  25914. SortedSet <void*> listeners;
  25915. friend class TextEditorInsertAction;
  25916. friend class TextEditorRemoveAction;
  25917. void coalesceSimilarSections() throw();
  25918. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  25919. void clearInternal (UndoManager* const um) throw();
  25920. void insert (const String& text,
  25921. const int insertIndex,
  25922. const Font& font,
  25923. const Colour& colour,
  25924. UndoManager* const um,
  25925. const int caretPositionToMoveTo) throw();
  25926. void reinsert (const int insertIndex,
  25927. const VoidArray& sections) throw();
  25928. void remove (const int startIndex,
  25929. int endIndex,
  25930. UndoManager* const um,
  25931. const int caretPositionToMoveTo) throw();
  25932. void getCharPosition (const int index,
  25933. float& x, float& y,
  25934. float& lineHeight) const throw();
  25935. void updateCaretPosition() throw();
  25936. int indexAtPosition (const float x,
  25937. const float y) throw();
  25938. int findWordBreakAfter (const int position) const throw();
  25939. int findWordBreakBefore (const int position) const throw();
  25940. friend class TextHolderComponent;
  25941. friend class TextEditorViewport;
  25942. void drawContent (Graphics& g);
  25943. void updateTextHolderSize() throw();
  25944. float getWordWrapWidth() const throw();
  25945. void timerCallbackInt();
  25946. void repaintCaret();
  25947. void repaintText (int textStartIndex, int textEndIndex);
  25948. TextEditor (const TextEditor&);
  25949. const TextEditor& operator= (const TextEditor&);
  25950. };
  25951. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  25952. /********* End of inlined file: juce_TextEditor.h *********/
  25953. class Label;
  25954. /**
  25955. A class for receiving events from a Label.
  25956. You can register a LabelListener with a Label using the Label::addListener()
  25957. method, and it will be called when the text of the label changes, either because
  25958. of a call to Label::setText() or by the user editing the text (if the label is
  25959. editable).
  25960. @see Label::addListener, Label::removeListener
  25961. */
  25962. class JUCE_API LabelListener
  25963. {
  25964. public:
  25965. /** Destructor. */
  25966. virtual ~LabelListener() {}
  25967. /** Called when a Label's text has changed.
  25968. */
  25969. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  25970. };
  25971. /**
  25972. A component that displays a text string, and can optionally become a text
  25973. editor when clicked.
  25974. */
  25975. class JUCE_API Label : public Component,
  25976. public SettableTooltipClient,
  25977. protected TextEditorListener,
  25978. private ComponentListener
  25979. {
  25980. public:
  25981. /** Creates a Label.
  25982. @param componentName the name to give the component
  25983. @param labelText the text to show in the label
  25984. */
  25985. Label (const String& componentName,
  25986. const String& labelText);
  25987. /** Destructor. */
  25988. ~Label();
  25989. /** Changes the label text.
  25990. If broadcastChangeMessage is true and the new text is different to the current
  25991. text, then the class will broadcast a change message to any LabelListeners that
  25992. are registered.
  25993. */
  25994. void setText (const String& newText,
  25995. const bool broadcastChangeMessage);
  25996. /** Returns the label's current text.
  25997. @param returnActiveEditorContents if this is true and the label is currently
  25998. being edited, then this method will return the
  25999. text as it's being shown in the editor. If false,
  26000. then the value returned here won't be updated until
  26001. the user has finished typing and pressed the return
  26002. key.
  26003. */
  26004. const String getText (const bool returnActiveEditorContents = false) const throw();
  26005. /** Changes the font to use to draw the text.
  26006. @see getFont
  26007. */
  26008. void setFont (const Font& newFont) throw();
  26009. /** Returns the font currently being used.
  26010. @see setFont
  26011. */
  26012. const Font& getFont() const throw();
  26013. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26014. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26015. methods.
  26016. Note that you can also use the constants from TextEditor::ColourIds to change the
  26017. colour of the text editor that is opened when a label is editable.
  26018. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26019. */
  26020. enum ColourIds
  26021. {
  26022. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  26023. textColourId = 0x1000281, /**< The colour for the text. */
  26024. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  26025. Leave this transparent to not have an outline. */
  26026. };
  26027. /** Sets the style of justification to be used for positioning the text.
  26028. (The default is Justification::centredLeft)
  26029. */
  26030. void setJustificationType (const Justification& justification) throw();
  26031. /** Returns the type of justification, as set in setJustificationType(). */
  26032. const Justification getJustificationType() const throw() { return justification; }
  26033. /** Changes the gap that is left between the edge of the component and the text.
  26034. By default there's a small gap left at the sides of the component to allow for
  26035. the drawing of the border, but you can change this if necessary.
  26036. */
  26037. void setBorderSize (int horizontalBorder, int verticalBorder);
  26038. /** Returns the size of the horizontal gap being left around the text.
  26039. */
  26040. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  26041. /** Returns the size of the vertical gap being left around the text.
  26042. */
  26043. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  26044. /** Makes this label "stick to" another component.
  26045. This will cause the label to follow another component around, staying
  26046. either to its left or above it.
  26047. @param owner the component to follow
  26048. @param onLeft if true, the label will stay on the left of its component; if
  26049. false, it will stay above it.
  26050. */
  26051. void attachToComponent (Component* owner,
  26052. const bool onLeft);
  26053. /** If this label has been attached to another component using attachToComponent, this
  26054. returns the other component.
  26055. Returns 0 if the label is not attached.
  26056. */
  26057. Component* getAttachedComponent() const throw() { return ownerComponent; }
  26058. /** If the label is attached to the left of another component, this returns true.
  26059. Returns false if the label is above the other component. This is only relevent if
  26060. attachToComponent() has been called.
  26061. */
  26062. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  26063. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  26064. using ellipsis.
  26065. @see Graphics::drawFittedText
  26066. */
  26067. void setMinimumHorizontalScale (const float newScale);
  26068. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  26069. /** Registers a listener that will be called when the label's text changes. */
  26070. void addListener (LabelListener* const listener) throw();
  26071. /** Deregisters a previously-registered listener. */
  26072. void removeListener (LabelListener* const listener) throw();
  26073. /** Makes the label turn into a TextEditor when clicked.
  26074. By default this is turned off.
  26075. If turned on, then single- or double-clicking will turn the label into
  26076. an editor. If the user then changes the text, then the ChangeBroadcaster
  26077. base class will be used to send change messages to any listeners that
  26078. have registered.
  26079. If the user changes the text, the textWasEdited() method will be called
  26080. afterwards, and subclasses can override this if they need to do anything
  26081. special.
  26082. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  26083. @param editOnDoubleClick if true, a double-click is needed to start editing
  26084. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  26085. edited will discard any changes; if false, then this will
  26086. commit the changes.
  26087. @see showEditor, setEditorColours, TextEditor
  26088. */
  26089. void setEditable (const bool editOnSingleClick,
  26090. const bool editOnDoubleClick = false,
  26091. const bool lossOfFocusDiscardsChanges = false) throw();
  26092. /** Returns true if this option was set using setEditable(). */
  26093. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  26094. /** Returns true if this option was set using setEditable(). */
  26095. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  26096. /** Returns true if this option has been set in a call to setEditable(). */
  26097. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  26098. /** Returns true if the user can edit this label's text. */
  26099. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  26100. /** Makes the editor appear as if the label had been clicked by the user.
  26101. @see textWasEdited, setEditable
  26102. */
  26103. void showEditor();
  26104. /** Hides the editor if it was being shown.
  26105. @param discardCurrentEditorContents if true, the label's text will be
  26106. reset to whatever it was before the editor
  26107. was shown; if false, the current contents of the
  26108. editor will be used to set the label's text
  26109. before it is hidden.
  26110. */
  26111. void hideEditor (const bool discardCurrentEditorContents);
  26112. /** Returns true if the editor is currently focused and active. */
  26113. bool isBeingEdited() const throw();
  26114. juce_UseDebuggingNewOperator
  26115. protected:
  26116. /** @internal */
  26117. void paint (Graphics& g);
  26118. /** @internal */
  26119. void resized();
  26120. /** @internal */
  26121. void mouseUp (const MouseEvent& e);
  26122. /** @internal */
  26123. void mouseDoubleClick (const MouseEvent& e);
  26124. /** @internal */
  26125. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26126. /** @internal */
  26127. void componentParentHierarchyChanged (Component& component);
  26128. /** @internal */
  26129. void componentVisibilityChanged (Component& component);
  26130. /** @internal */
  26131. void inputAttemptWhenModal();
  26132. /** @internal */
  26133. void focusGained (FocusChangeType);
  26134. /** @internal */
  26135. void enablementChanged();
  26136. /** @internal */
  26137. KeyboardFocusTraverser* createFocusTraverser();
  26138. /** @internal */
  26139. void textEditorTextChanged (TextEditor& editor);
  26140. /** @internal */
  26141. void textEditorReturnKeyPressed (TextEditor& editor);
  26142. /** @internal */
  26143. void textEditorEscapeKeyPressed (TextEditor& editor);
  26144. /** @internal */
  26145. void textEditorFocusLost (TextEditor& editor);
  26146. /** @internal */
  26147. void colourChanged();
  26148. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  26149. Subclasses can override this if they need to customise this component in some way.
  26150. */
  26151. virtual TextEditor* createEditorComponent();
  26152. /** Called after the user changes the text.
  26153. */
  26154. virtual void textWasEdited();
  26155. /** Called when the text has been altered.
  26156. */
  26157. virtual void textWasChanged();
  26158. /** Called when the text editor has just appeared, due to a user click or other
  26159. focus change.
  26160. */
  26161. virtual void editorShown (TextEditor* editorComponent);
  26162. /** Called when the text editor is going to be deleted, after editing has finished.
  26163. */
  26164. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  26165. private:
  26166. String text;
  26167. Font font;
  26168. Justification justification;
  26169. TextEditor* editor;
  26170. SortedSet <void*> listeners;
  26171. Component* ownerComponent;
  26172. ComponentDeletionWatcher* deletionWatcher;
  26173. int horizontalBorderSize, verticalBorderSize;
  26174. float minimumHorizontalScale;
  26175. bool editSingleClick : 1;
  26176. bool editDoubleClick : 1;
  26177. bool lossOfFocusDiscardsChanges : 1;
  26178. bool leftOfOwnerComp : 1;
  26179. bool updateFromTextEditorContents();
  26180. void callChangeListeners();
  26181. Label (const Label&);
  26182. const Label& operator= (const Label&);
  26183. };
  26184. #endif // __JUCE_LABEL_JUCEHEADER__
  26185. /********* End of inlined file: juce_Label.h *********/
  26186. class ComboBox;
  26187. /**
  26188. A class for receiving events from a ComboBox.
  26189. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  26190. method, and it will be called when the selected item in the box changes.
  26191. @see ComboBox::addListener, ComboBox::removeListener
  26192. */
  26193. class JUCE_API ComboBoxListener
  26194. {
  26195. public:
  26196. /** Destructor. */
  26197. virtual ~ComboBoxListener() {}
  26198. /** Called when a ComboBox has its selected item changed.
  26199. */
  26200. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  26201. };
  26202. /**
  26203. A component that lets the user choose from a drop-down list of choices.
  26204. The combo-box has a list of text strings, each with an associated id number,
  26205. that will be shown in the drop-down list when the user clicks on the component.
  26206. The currently selected choice is displayed in the combo-box, and this can
  26207. either be read-only text, or editable.
  26208. To find out when the user selects a different item or edits the text, you
  26209. can register a ComboBoxListener to receive callbacks.
  26210. @see ComboBoxListener
  26211. */
  26212. class JUCE_API ComboBox : public Component,
  26213. public SettableTooltipClient,
  26214. private LabelListener,
  26215. private AsyncUpdater
  26216. {
  26217. public:
  26218. /** Creates a combo-box.
  26219. On construction, the text field will be empty, so you should call the
  26220. setSelectedId() or setText() method to choose the initial value before
  26221. displaying it.
  26222. @param componentName the name to set for the component (see Component::setName())
  26223. */
  26224. ComboBox (const String& componentName);
  26225. /** Destructor. */
  26226. ~ComboBox();
  26227. /** Sets whether the test in the combo-box is editable.
  26228. The default state for a new ComboBox is non-editable, and can only be changed
  26229. by choosing from the drop-down list.
  26230. */
  26231. void setEditableText (const bool isEditable);
  26232. /** Returns true if the text is directly editable.
  26233. @see setEditableText
  26234. */
  26235. bool isTextEditable() const throw();
  26236. /** Sets the style of justification to be used for positioning the text.
  26237. The default is Justification::centredLeft. The text is displayed using a
  26238. Label component inside the ComboBox.
  26239. */
  26240. void setJustificationType (const Justification& justification) throw();
  26241. /** Returns the current justification for the text box.
  26242. @see setJustificationType
  26243. */
  26244. const Justification getJustificationType() const throw();
  26245. /** Adds an item to be shown in the drop-down list.
  26246. @param newItemText the text of the item to show in the list
  26247. @param newItemId an associated ID number that can be set or retrieved - see
  26248. getSelectedId() and setSelectedId()
  26249. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  26250. */
  26251. void addItem (const String& newItemText,
  26252. const int newItemId) throw();
  26253. /** Adds a separator line to the drop-down list.
  26254. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  26255. */
  26256. void addSeparator() throw();
  26257. /** Adds a heading to the drop-down list, so that you can group the items into
  26258. different sections.
  26259. The headings are indented slightly differently to set them apart from the
  26260. items on the list, and obviously can't be selected. You might want to add
  26261. separators between your sections too.
  26262. @see addItem, addSeparator
  26263. */
  26264. void addSectionHeading (const String& headingName) throw();
  26265. /** This allows items in the drop-down list to be selectively disabled.
  26266. When you add an item, it's enabled by default, but you can call this
  26267. method to change its status.
  26268. If you disable an item which is already selected, this won't change the
  26269. current selection - it just stops the user choosing that item from the list.
  26270. */
  26271. void setItemEnabled (const int itemId,
  26272. const bool shouldBeEnabled) throw();
  26273. /** Changes the text for an existing item.
  26274. */
  26275. void changeItemText (const int itemId,
  26276. const String& newText) throw();
  26277. /** Removes all the items from the drop-down list.
  26278. If this call causes the content to be cleared, then a change-message
  26279. will be broadcast unless dontSendChangeMessage is true.
  26280. @see addItem, removeItem, getNumItems
  26281. */
  26282. void clear (const bool dontSendChangeMessage = false);
  26283. /** Returns the number of items that have been added to the list.
  26284. Note that this doesn't include headers or separators.
  26285. */
  26286. int getNumItems() const throw();
  26287. /** Returns the text for one of the items in the list.
  26288. Note that this doesn't include headers or separators.
  26289. @param index the item's index from 0 to (getNumItems() - 1)
  26290. */
  26291. const String getItemText (const int index) const throw();
  26292. /** Returns the ID for one of the items in the list.
  26293. Note that this doesn't include headers or separators.
  26294. @param index the item's index from 0 to (getNumItems() - 1)
  26295. */
  26296. int getItemId (const int index) const throw();
  26297. /** Returns the ID of the item that's currently shown in the box.
  26298. If no item is selected, or if the text is editable and the user
  26299. has entered something which isn't one of the items in the list, then
  26300. this will return 0.
  26301. @see setSelectedId, getSelectedItemIndex, getText
  26302. */
  26303. int getSelectedId() const throw();
  26304. /** Sets one of the items to be the current selection.
  26305. This will set the ComboBox's text to that of the item that matches
  26306. this ID.
  26307. @param newItemId the new item to select
  26308. @param dontSendChangeMessage if set to true, this method won't trigger a
  26309. change notification
  26310. @see getSelectedId, setSelectedItemIndex, setText
  26311. */
  26312. void setSelectedId (const int newItemId,
  26313. const bool dontSendChangeMessage = false) throw();
  26314. /** Returns the index of the item that's currently shown in the box.
  26315. If no item is selected, or if the text is editable and the user
  26316. has entered something which isn't one of the items in the list, then
  26317. this will return -1.
  26318. @see setSelectedItemIndex, getSelectedId, getText
  26319. */
  26320. int getSelectedItemIndex() const throw();
  26321. /** Sets one of the items to be the current selection.
  26322. This will set the ComboBox's text to that of the item at the given
  26323. index in the list.
  26324. @param newItemIndex the new item to select
  26325. @param dontSendChangeMessage if set to true, this method won't trigger a
  26326. change notification
  26327. @see getSelectedItemIndex, setSelectedId, setText
  26328. */
  26329. void setSelectedItemIndex (const int newItemIndex,
  26330. const bool dontSendChangeMessage = false) throw();
  26331. /** Returns the text that is currently shown in the combo-box's text field.
  26332. If the ComboBox has editable text, then this text may have been edited
  26333. by the user; otherwise it will be one of the items from the list, or
  26334. possibly an empty string if nothing was selected.
  26335. @see setText, getSelectedId, getSelectedItemIndex
  26336. */
  26337. const String getText() const throw();
  26338. /** Sets the contents of the combo-box's text field.
  26339. The text passed-in will be set as the current text regardless of whether
  26340. it is one of the items in the list. If the current text isn't one of the
  26341. items, then getSelectedId() will return -1, otherwise it wil return
  26342. the approriate ID.
  26343. @param newText the text to select
  26344. @param dontSendChangeMessage if set to true, this method won't trigger a
  26345. change notification
  26346. @see getText
  26347. */
  26348. void setText (const String& newText,
  26349. const bool dontSendChangeMessage = false) throw();
  26350. /** Programmatically opens the text editor to allow the user to edit the current item.
  26351. This is the same effect as when the box is clicked-on.
  26352. @see Label::showEditor();
  26353. */
  26354. void showEditor();
  26355. /** Registers a listener that will be called when the box's content changes. */
  26356. void addListener (ComboBoxListener* const listener) throw();
  26357. /** Deregisters a previously-registered listener. */
  26358. void removeListener (ComboBoxListener* const listener) throw();
  26359. /** Sets a message to display when there is no item currently selected.
  26360. @see getTextWhenNothingSelected
  26361. */
  26362. void setTextWhenNothingSelected (const String& newMessage) throw();
  26363. /** Returns the text that is shown when no item is selected.
  26364. @see setTextWhenNothingSelected
  26365. */
  26366. const String getTextWhenNothingSelected() const throw();
  26367. /** Sets the message to show when there are no items in the list, and the user clicks
  26368. on the drop-down box.
  26369. By default it just says "no choices", but this lets you change it to something more
  26370. meaningful.
  26371. */
  26372. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  26373. /** Returns the text shown when no items have been added to the list.
  26374. @see setTextWhenNoChoicesAvailable
  26375. */
  26376. const String getTextWhenNoChoicesAvailable() const throw();
  26377. /** Gives the ComboBox a tooltip. */
  26378. void setTooltip (const String& newTooltip);
  26379. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  26380. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26381. methods.
  26382. To change the colours of the menu that pops up
  26383. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26384. */
  26385. enum ColourIds
  26386. {
  26387. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  26388. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  26389. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  26390. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  26391. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  26392. };
  26393. /** @internal */
  26394. void labelTextChanged (Label*);
  26395. /** @internal */
  26396. void enablementChanged();
  26397. /** @internal */
  26398. void colourChanged();
  26399. /** @internal */
  26400. void focusGained (Component::FocusChangeType cause);
  26401. /** @internal */
  26402. void focusLost (Component::FocusChangeType cause);
  26403. /** @internal */
  26404. void handleAsyncUpdate();
  26405. /** @internal */
  26406. const String getTooltip() { return label->getTooltip(); }
  26407. /** @internal */
  26408. void mouseDown (const MouseEvent&);
  26409. /** @internal */
  26410. void mouseDrag (const MouseEvent&);
  26411. /** @internal */
  26412. void mouseUp (const MouseEvent&);
  26413. /** @internal */
  26414. void lookAndFeelChanged();
  26415. /** @internal */
  26416. void paint (Graphics&);
  26417. /** @internal */
  26418. void resized();
  26419. /** @internal */
  26420. bool keyStateChanged (const bool isKeyDown);
  26421. /** @internal */
  26422. bool keyPressed (const KeyPress&);
  26423. juce_UseDebuggingNewOperator
  26424. private:
  26425. struct ItemInfo
  26426. {
  26427. String name;
  26428. int itemId;
  26429. bool isEnabled : 1, isHeading : 1;
  26430. bool isSeparator() const throw();
  26431. bool isRealItem() const throw();
  26432. };
  26433. OwnedArray <ItemInfo> items;
  26434. int currentIndex;
  26435. bool isButtonDown;
  26436. bool separatorPending;
  26437. bool menuActive;
  26438. SortedSet <void*> listeners;
  26439. Label* label;
  26440. String textWhenNothingSelected, noChoicesMessage;
  26441. void showPopup();
  26442. ItemInfo* getItemForId (const int itemId) const throw();
  26443. ItemInfo* getItemForIndex (const int index) const throw();
  26444. ComboBox (const ComboBox&);
  26445. const ComboBox& operator= (const ComboBox&);
  26446. };
  26447. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  26448. /********* End of inlined file: juce_ComboBox.h *********/
  26449. /**
  26450. Manages the state of some audio and midi i/o devices.
  26451. This class keeps tracks of a currently-selected audio device, through
  26452. with which it continuously streams data from an audio callback, as well as
  26453. one or more midi inputs.
  26454. The idea is that your application will create one global instance of this object,
  26455. and let it take care of creating and deleting specific types of audio devices
  26456. internally. So when the device is changed, your callbacks will just keep running
  26457. without having to worry about this.
  26458. The manager can save and reload all of its device settings as XML, which
  26459. makes it very easy for you to save and reload the audio setup of your
  26460. application.
  26461. And to make it easy to let the user change its settings, there's a component
  26462. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  26463. device selection/sample-rate/latency controls.
  26464. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  26465. call addAudioCallback() to register your audio callback with it, and use that to process
  26466. your audio data.
  26467. The manager also acts as a handy hub for incoming midi messages, allowing a
  26468. listener to register for messages from either a specific midi device, or from whatever
  26469. the current default midi input device is. The listener then doesn't have to worry about
  26470. re-registering with different midi devices if they are changed or deleted.
  26471. And yet another neat trick is that amount of CPU time being used is measured and
  26472. available with the getCpuUsage() method.
  26473. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  26474. listeners whenever one of its settings is changed.
  26475. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  26476. */
  26477. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  26478. {
  26479. public:
  26480. /** Creates a default AudioDeviceManager.
  26481. Initially no audio device will be selected. You should call the initialise() method
  26482. and register an audio callback with setAudioCallback() before it'll be able to
  26483. actually make any noise.
  26484. */
  26485. AudioDeviceManager();
  26486. /** Destructor. */
  26487. ~AudioDeviceManager();
  26488. /**
  26489. This structure holds a set of properties describing the current audio setup.
  26490. @see AudioDeviceManager::setAudioDeviceSetup()
  26491. */
  26492. struct JUCE_API AudioDeviceSetup
  26493. {
  26494. AudioDeviceSetup();
  26495. bool operator== (const AudioDeviceSetup& other) const;
  26496. /** The name of the audio device used for output.
  26497. The name has to be one of the ones listed by the AudioDeviceManager's currently
  26498. selected device type.
  26499. This may be the same as the input device.
  26500. */
  26501. String outputDeviceName;
  26502. /** The name of the audio device used for input.
  26503. This may be the same as the output device.
  26504. */
  26505. String inputDeviceName;
  26506. /** The current sample rate.
  26507. This rate is used for both the input and output devices.
  26508. */
  26509. double sampleRate;
  26510. /** The buffer size, in samples.
  26511. This buffer size is used for both the input and output devices.
  26512. */
  26513. int bufferSize;
  26514. /** The set of active input channels.
  26515. The bits that are set in this array indicate the channels of the
  26516. input device that are active.
  26517. */
  26518. BitArray inputChannels;
  26519. /** If this is true, it indicates that the inputChannels array
  26520. should be ignored, and instead, the device's default channels
  26521. should be used.
  26522. */
  26523. bool useDefaultInputChannels;
  26524. /** The set of active output channels.
  26525. The bits that are set in this array indicate the channels of the
  26526. input device that are active.
  26527. */
  26528. BitArray outputChannels;
  26529. /** If this is true, it indicates that the outputChannels array
  26530. should be ignored, and instead, the device's default channels
  26531. should be used.
  26532. */
  26533. bool useDefaultOutputChannels;
  26534. };
  26535. /** Opens a set of audio devices ready for use.
  26536. This will attempt to open either a default audio device, or one that was
  26537. previously saved as XML.
  26538. @param numInputChannelsNeeded a minimum number of input channels needed
  26539. by your app.
  26540. @param numOutputChannelsNeeded a minimum number of output channels to open
  26541. @param savedState either a previously-saved state that was produced
  26542. by createStateXml(), or 0 if you want the manager
  26543. to choose the best device to open.
  26544. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  26545. fails to open, then a default device will be used
  26546. instead. If false, then on failure, no device is
  26547. opened.
  26548. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  26549. name, then that will be used as the default device
  26550. (assuming that there wasn't one specified in the XML).
  26551. The string can actually be a simple wildcard, containing "*"
  26552. and "?" characters
  26553. @param preferredSetupOptions if this is non-null, the structure will be used as the
  26554. set of preferred settings when opening the device. If you
  26555. use this parameter, the preferredDefaultDeviceName
  26556. field will be ignored
  26557. @returns an error message if anything went wrong, or an empty string if it worked ok.
  26558. */
  26559. const String initialise (const int numInputChannelsNeeded,
  26560. const int numOutputChannelsNeeded,
  26561. const XmlElement* const savedState,
  26562. const bool selectDefaultDeviceOnFailure,
  26563. const String& preferredDefaultDeviceName = String::empty,
  26564. const AudioDeviceSetup* preferredSetupOptions = 0);
  26565. /** Returns some XML representing the current state of the manager.
  26566. This stores the current device, its samplerate, block size, etc, and
  26567. can be restored later with initialise().
  26568. */
  26569. XmlElement* createStateXml() const;
  26570. /** Returns the current device properties that are in use.
  26571. @see setAudioDeviceSetup
  26572. */
  26573. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  26574. /** Changes the current device or its settings.
  26575. If you want to change a device property, like the current sample rate or
  26576. block size, you can call getAudioDeviceSetup() to retrieve the current
  26577. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  26578. and pass it back into this method to apply the new settings.
  26579. @param newSetup the settings that you'd like to use
  26580. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  26581. settings will be taken as having been explicitly chosen by the
  26582. user, and the next time createStateXml() is called, these settings
  26583. will be returned. If it's false, then the device is treated as a
  26584. temporary or default device, and a call to createStateXml() will
  26585. return either the last settings that were made with treatAsChosenDevice
  26586. as true, or the last XML settings that were passed into initialise().
  26587. @returns an error message if anything went wrong, or an empty string if it worked ok.
  26588. @see getAudioDeviceSetup
  26589. */
  26590. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  26591. const bool treatAsChosenDevice);
  26592. /** Returns the currently-active audio device. */
  26593. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  26594. /** Returns the type of audio device currently in use.
  26595. @see setCurrentAudioDeviceType
  26596. */
  26597. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  26598. /** Returns the currently active audio device type object.
  26599. Don't keep a copy of this pointer - it's owned by the device manager and could
  26600. change at any time.
  26601. */
  26602. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  26603. /** Changes the class of audio device being used.
  26604. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  26605. this because there's only one type: CoreAudio.
  26606. For a list of types, see getAvailableDeviceTypes().
  26607. */
  26608. void setCurrentAudioDeviceType (const String& type,
  26609. const bool treatAsChosenDevice);
  26610. /** Closes the currently-open device.
  26611. You can call restartLastAudioDevice() later to reopen it in the same state
  26612. that it was just in.
  26613. */
  26614. void closeAudioDevice();
  26615. /** Tries to reload the last audio device that was running.
  26616. Note that this only reloads the last device that was running before
  26617. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  26618. and can only be called after a device has been opened with SetAudioDevice().
  26619. If a device is already open, this call will do nothing.
  26620. */
  26621. void restartLastAudioDevice();
  26622. /** Registers an audio callback to be used.
  26623. The manager will redirect callbacks from whatever audio device is currently
  26624. in use to all registered callback objects. If more than one callback is
  26625. active, they will all be given the same input data, and their outputs will
  26626. be summed.
  26627. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  26628. object before returning.
  26629. To remove a callback, use removeAudioCallback().
  26630. */
  26631. void addAudioCallback (AudioIODeviceCallback* newCallback);
  26632. /** Deregisters a previously added callback.
  26633. If necessary, this method will invoke audioDeviceStopped() on the callback
  26634. object before returning.
  26635. @see addAudioCallback
  26636. */
  26637. void removeAudioCallback (AudioIODeviceCallback* callback);
  26638. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  26639. Returns a value between 0 and 1.0
  26640. */
  26641. double getCpuUsage() const;
  26642. /** Enables or disables a midi input device.
  26643. The list of devices can be obtained with the MidiInput::getDevices() method.
  26644. Any incoming messages from enabled input devices will be forwarded on to all the
  26645. listeners that have been registered with the addMidiInputCallback() method. They
  26646. can either register for messages from a particular device, or from just the
  26647. "default" midi input.
  26648. Routing the midi input via an AudioDeviceManager means that when a listener
  26649. registers for the default midi input, this default device can be changed by the
  26650. manager without the listeners having to know about it or re-register.
  26651. It also means that a listener can stay registered for a midi input that is disabled
  26652. or not present, so that when the input is re-enabled, the listener will start
  26653. receiving messages again.
  26654. @see addMidiInputCallback, isMidiInputEnabled
  26655. */
  26656. void setMidiInputEnabled (const String& midiInputDeviceName,
  26657. const bool enabled);
  26658. /** Returns true if a given midi input device is being used.
  26659. @see setMidiInputEnabled
  26660. */
  26661. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  26662. /** Registers a listener for callbacks when midi events arrive from a midi input.
  26663. The device name can be empty to indicate that it wants events from whatever the
  26664. current "default" device is. Or it can be the name of one of the midi input devices
  26665. (see MidiInput::getDevices() for the names).
  26666. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  26667. events forwarded on to listeners.
  26668. */
  26669. void addMidiInputCallback (const String& midiInputDeviceName,
  26670. MidiInputCallback* callback);
  26671. /** Removes a listener that was previously registered with addMidiInputCallback().
  26672. */
  26673. void removeMidiInputCallback (const String& midiInputDeviceName,
  26674. MidiInputCallback* callback);
  26675. /** Sets a midi output device to use as the default.
  26676. The list of devices can be obtained with the MidiOutput::getDevices() method.
  26677. The specified device will be opened automatically and can be retrieved with the
  26678. getDefaultMidiOutput() method.
  26679. Pass in an empty string to deselect all devices. For the default device, you
  26680. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  26681. @see getDefaultMidiOutput, getDefaultMidiOutputName
  26682. */
  26683. void setDefaultMidiOutput (const String& deviceName);
  26684. /** Returns the name of the default midi output.
  26685. @see setDefaultMidiOutput, getDefaultMidiOutput
  26686. */
  26687. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  26688. /** Returns the current default midi output device.
  26689. If no device has been selected, or the device can't be opened, this will
  26690. return 0.
  26691. @see getDefaultMidiOutputName
  26692. */
  26693. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  26694. /** Returns a list of the types of device supported.
  26695. */
  26696. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  26697. /** Creates a list of available types.
  26698. This will add a set of new AudioIODeviceType objects to the specified list, to
  26699. represent each available types of device.
  26700. You can override this if your app needs to do something specific, like avoid
  26701. using DirectSound devices, etc.
  26702. */
  26703. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  26704. /** Plays a beep through the current audio device.
  26705. This is here to allow the audio setup UI panels to easily include a "test"
  26706. button so that the user can check where the audio is coming from.
  26707. */
  26708. void playTestSound();
  26709. /** Turns on level-measuring.
  26710. When enabled, the device manager will measure the peak input level
  26711. across all channels, and you can get this level by calling getCurrentInputLevel().
  26712. This is mainly intended for audio setup UI panels to use to create a mic
  26713. level display, so that the user can check that they've selected the right
  26714. device.
  26715. A simple filter is used to make the level decay smoothly, but this is
  26716. only intended for giving rough feedback, and not for any kind of accurate
  26717. measurement.
  26718. */
  26719. void enableInputLevelMeasurement (const bool enableMeasurement);
  26720. /** Returns the current input level.
  26721. To use this, you must first enable it by calling enableInputLevelMeasurement().
  26722. See enableInputLevelMeasurement() for more info.
  26723. */
  26724. double getCurrentInputLevel() const;
  26725. juce_UseDebuggingNewOperator
  26726. private:
  26727. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  26728. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  26729. AudioDeviceSetup currentSetup;
  26730. AudioIODevice* currentAudioDevice;
  26731. SortedSet <AudioIODeviceCallback*> callbacks;
  26732. int numInputChansNeeded, numOutputChansNeeded;
  26733. String currentDeviceType;
  26734. BitArray inputChannels, outputChannels;
  26735. XmlElement* lastExplicitSettings;
  26736. mutable bool listNeedsScanning;
  26737. bool useInputNames;
  26738. int inputLevelMeasurementEnabledCount;
  26739. double inputLevel;
  26740. AudioSampleBuffer* testSound;
  26741. int testSoundPosition;
  26742. AudioSampleBuffer tempBuffer;
  26743. StringArray midiInsFromXml;
  26744. OwnedArray <MidiInput> enabledMidiInputs;
  26745. Array <MidiInputCallback*> midiCallbacks;
  26746. Array <MidiInput*> midiCallbackDevices;
  26747. String defaultMidiOutputName;
  26748. MidiOutput* defaultMidiOutput;
  26749. CriticalSection audioCallbackLock, midiCallbackLock;
  26750. double cpuUsageMs, timeToCpuScale;
  26751. class CallbackHandler : public AudioIODeviceCallback,
  26752. public MidiInputCallback
  26753. {
  26754. public:
  26755. AudioDeviceManager* owner;
  26756. void audioDeviceIOCallback (const float** inputChannelData,
  26757. int totalNumInputChannels,
  26758. float** outputChannelData,
  26759. int totalNumOutputChannels,
  26760. int numSamples);
  26761. void audioDeviceAboutToStart (AudioIODevice*);
  26762. void audioDeviceStopped();
  26763. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26764. };
  26765. CallbackHandler callbackHandler;
  26766. friend class CallbackHandler;
  26767. void audioDeviceIOCallbackInt (const float** inputChannelData,
  26768. int totalNumInputChannels,
  26769. float** outputChannelData,
  26770. int totalNumOutputChannels,
  26771. int numSamples);
  26772. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  26773. void audioDeviceStoppedInt();
  26774. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  26775. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  26776. const BitArray& ins, const BitArray& outs);
  26777. void stopDevice();
  26778. void updateXml();
  26779. void createDeviceTypesIfNeeded();
  26780. void scanDevicesIfNeeded();
  26781. void deleteCurrentDevice();
  26782. double chooseBestSampleRate (double preferred) const;
  26783. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  26784. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  26785. AudioDeviceManager (const AudioDeviceManager&);
  26786. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  26787. };
  26788. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26789. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  26790. #endif
  26791. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26792. #endif
  26793. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26794. #endif
  26795. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26796. #endif
  26797. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  26798. #endif
  26799. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26800. /********* Start of inlined file: juce_Sampler.h *********/
  26801. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26802. #define __JUCE_SAMPLER_JUCEHEADER__
  26803. /********* Start of inlined file: juce_Synthesiser.h *********/
  26804. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26805. #define __JUCE_SYNTHESISER_JUCEHEADER__
  26806. /**
  26807. Describes one of the sounds that a Synthesiser can play.
  26808. A synthesiser can contain one or more sounds, and a sound can choose which
  26809. midi notes and channels can trigger it.
  26810. The SynthesiserSound is a passive class that just describes what the sound is -
  26811. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  26812. more than one SynthesiserVoice to play the same sound at the same time.
  26813. @see Synthesiser, SynthesiserVoice
  26814. */
  26815. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  26816. {
  26817. protected:
  26818. SynthesiserSound();
  26819. public:
  26820. /** Destructor. */
  26821. virtual ~SynthesiserSound();
  26822. /** Returns true if this sound should be played when a given midi note is pressed.
  26823. The Synthesiser will use this information when deciding which sounds to trigger
  26824. for a given note.
  26825. */
  26826. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  26827. /** Returns true if the sound should be triggered by midi events on a given channel.
  26828. The Synthesiser will use this information when deciding which sounds to trigger
  26829. for a given note.
  26830. */
  26831. virtual bool appliesToChannel (const int midiChannel) = 0;
  26832. /**
  26833. */
  26834. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  26835. juce_UseDebuggingNewOperator
  26836. };
  26837. /**
  26838. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  26839. A voice plays a single sound at a time, and a synthesiser holds an array of
  26840. voices so that it can play polyphonically.
  26841. @see Synthesiser, SynthesiserSound
  26842. */
  26843. class JUCE_API SynthesiserVoice
  26844. {
  26845. public:
  26846. /** Creates a voice. */
  26847. SynthesiserVoice();
  26848. /** Destructor. */
  26849. virtual ~SynthesiserVoice();
  26850. /** Returns the midi note that this voice is currently playing.
  26851. Returns a value less than 0 if no note is playing.
  26852. */
  26853. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  26854. /** Returns the sound that this voice is currently playing.
  26855. Returns 0 if it's not playing.
  26856. */
  26857. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  26858. /** Must return true if this voice object is capable of playing the given sound.
  26859. If there are different classes of sound, and different classes of voice, a voice can
  26860. choose which ones it wants to take on.
  26861. A typical implementation of this method may just return true if there's only one type
  26862. of voice and sound, or it might check the type of the sound object passed-in and
  26863. see if it's one that it understands.
  26864. */
  26865. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  26866. /** Called to start a new note.
  26867. This will be called during the rendering callback, so must be fast and thread-safe.
  26868. */
  26869. virtual void startNote (const int midiNoteNumber,
  26870. const float velocity,
  26871. SynthesiserSound* sound,
  26872. const int currentPitchWheelPosition) = 0;
  26873. /** Called to stop a note.
  26874. This will be called during the rendering callback, so must be fast and thread-safe.
  26875. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  26876. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  26877. and allow the synth to reassign it another sound.
  26878. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  26879. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  26880. finishes playing (during the rendering callback), it must make sure that it calls
  26881. clearCurrentNote().
  26882. */
  26883. virtual void stopNote (const bool allowTailOff) = 0;
  26884. /** Called to let the voice know that the pitch wheel has been moved.
  26885. This will be called during the rendering callback, so must be fast and thread-safe.
  26886. */
  26887. virtual void pitchWheelMoved (const int newValue) = 0;
  26888. /** Called to let the voice know that a midi controller has been moved.
  26889. This will be called during the rendering callback, so must be fast and thread-safe.
  26890. */
  26891. virtual void controllerMoved (const int controllerNumber,
  26892. const int newValue) = 0;
  26893. /** Renders the next block of data for this voice.
  26894. The output audio data must be added to the current contents of the buffer provided.
  26895. Only the region of the buffer between startSample and (startSample + numSamples)
  26896. should be altered by this method.
  26897. If the voice is currently silent, it should just return without doing anything.
  26898. If the sound that the voice is playing finishes during the course of this rendered
  26899. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  26900. The size of the blocks that are rendered can change each time it is called, and may
  26901. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  26902. the voice's methods will be called to tell it about note and controller events.
  26903. */
  26904. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  26905. int startSample,
  26906. int numSamples) = 0;
  26907. /** Returns true if the voice is currently playing a sound which is mapped to the given
  26908. midi channel.
  26909. If it's not currently playing, this will return false.
  26910. */
  26911. bool isPlayingChannel (const int midiChannel) const;
  26912. /** Changes the voice's reference sample rate.
  26913. The rate is set so that subclasses know the output rate and can set their pitch
  26914. accordingly.
  26915. This method is called by the synth, and subclasses can access the current rate with
  26916. the currentSampleRate member.
  26917. */
  26918. void setCurrentPlaybackSampleRate (const double newRate);
  26919. juce_UseDebuggingNewOperator
  26920. protected:
  26921. /** Returns the current target sample rate at which rendering is being done.
  26922. This is available for subclasses so they can pitch things correctly.
  26923. */
  26924. double getSampleRate() const throw() { return currentSampleRate; }
  26925. /** Resets the state of this voice after a sound has finished playing.
  26926. The subclass must call this when it finishes playing a note and becomes available
  26927. to play new ones.
  26928. It must either call it in the stopNote() method, or if the voice is tailing off,
  26929. then it should call it later during the renderNextBlock method, as soon as it
  26930. finishes its tail-off.
  26931. It can also be called at any time during the render callback if the sound happens
  26932. to have finished, e.g. if it's playing a sample and the sample finishes.
  26933. */
  26934. void clearCurrentNote();
  26935. private:
  26936. friend class Synthesiser;
  26937. double currentSampleRate;
  26938. int currentlyPlayingNote;
  26939. uint32 noteOnTime;
  26940. SynthesiserSound::Ptr currentlyPlayingSound;
  26941. };
  26942. /**
  26943. Base class for a musical device that can play sounds.
  26944. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  26945. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  26946. which can play back one of these sounds.
  26947. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  26948. set of sounds, and a set of voices it can use to play them. If you only give it
  26949. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  26950. have available.
  26951. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  26952. events that go in will be scanned for note on/off messages, and these are used to
  26953. start and stop the voices playing the appropriate sounds.
  26954. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  26955. noteOff() and other controller methods.
  26956. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  26957. what the target playback rate is. This value is passed on to the voices so that
  26958. they can pitch their output correctly.
  26959. */
  26960. class JUCE_API Synthesiser
  26961. {
  26962. public:
  26963. /** Creates a new synthesiser.
  26964. You'll need to add some sounds and voices before it'll make any sound..
  26965. */
  26966. Synthesiser();
  26967. /** Destructor. */
  26968. virtual ~Synthesiser();
  26969. /** Deletes all voices. */
  26970. void clearVoices();
  26971. /** Returns the number of voices that have been added. */
  26972. int getNumVoices() const throw() { return voices.size(); }
  26973. /** Returns one of the voices that have been added. */
  26974. SynthesiserVoice* getVoice (const int index) const throw();
  26975. /** Adds a new voice to the synth.
  26976. All the voices should be the same class of object and are treated equally.
  26977. The object passed in will be managed by the synthesiser, which will delete
  26978. it later on when no longer needed. The caller should not retain a pointer to the
  26979. voice.
  26980. */
  26981. void addVoice (SynthesiserVoice* const newVoice);
  26982. /** Deletes one of the voices. */
  26983. void removeVoice (const int index);
  26984. /** Deletes all sounds. */
  26985. void clearSounds();
  26986. /** Returns the number of sounds that have been added to the synth. */
  26987. int getNumSounds() const throw() { return sounds.size(); }
  26988. /** Returns one of the sounds. */
  26989. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  26990. /** Adds a new sound to the synthesiser.
  26991. The object passed in is reference counted, so will be deleted when it is removed
  26992. from the synthesiser, and when no voices are still using it.
  26993. */
  26994. void addSound (const SynthesiserSound::Ptr& newSound);
  26995. /** Removes and deletes one of the sounds. */
  26996. void removeSound (const int index);
  26997. /** If set to true, then the synth will try to take over an existing voice if
  26998. it runs out and needs to play another note.
  26999. The value of this boolean is passed into findFreeVoice(), so the result will
  27000. depend on the implementation of this method.
  27001. */
  27002. void setNoteStealingEnabled (const bool shouldStealNotes);
  27003. /** Returns true if note-stealing is enabled.
  27004. @see setNoteStealingEnabled
  27005. */
  27006. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  27007. /** Triggers a note-on event.
  27008. The default method here will find all the sounds that want to be triggered by
  27009. this note/channel. For each sound, it'll try to find a free voice, and use the
  27010. voice to start playing the sound.
  27011. Subclasses might want to override this if they need a more complex algorithm.
  27012. This method will be called automatically according to the midi data passed into
  27013. renderNextBlock(), but may be called explicitly too.
  27014. */
  27015. virtual void noteOn (const int midiChannel,
  27016. const int midiNoteNumber,
  27017. const float velocity);
  27018. /** Triggers a note-off event.
  27019. This will turn off any voices that are playing a sound for the given note/channel.
  27020. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  27021. (if they can do). If this is false, the notes will all be cut off immediately.
  27022. This method will be called automatically according to the midi data passed into
  27023. renderNextBlock(), but may be called explicitly too.
  27024. */
  27025. virtual void noteOff (const int midiChannel,
  27026. const int midiNoteNumber,
  27027. const bool allowTailOff);
  27028. /** Turns off all notes.
  27029. This will turn off any voices that are playing a sound on the given midi channel.
  27030. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  27031. which channel they're playing.
  27032. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  27033. (if they can do). If this is false, the notes will all be cut off immediately.
  27034. This method will be called automatically according to the midi data passed into
  27035. renderNextBlock(), but may be called explicitly too.
  27036. */
  27037. virtual void allNotesOff (const int midiChannel,
  27038. const bool allowTailOff);
  27039. /** Sends a pitch-wheel message.
  27040. This will send a pitch-wheel message to any voices that are playing sounds on
  27041. the given midi channel.
  27042. This method will be called automatically according to the midi data passed into
  27043. renderNextBlock(), but may be called explicitly too.
  27044. @param midiChannel the midi channel for the event
  27045. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  27046. */
  27047. virtual void handlePitchWheel (const int midiChannel,
  27048. const int wheelValue);
  27049. /** Sends a midi controller message.
  27050. This will send a midi controller message to any voices that are playing sounds on
  27051. the given midi channel.
  27052. This method will be called automatically according to the midi data passed into
  27053. renderNextBlock(), but may be called explicitly too.
  27054. @param midiChannel the midi channel for the event
  27055. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  27056. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  27057. */
  27058. virtual void handleController (const int midiChannel,
  27059. const int controllerNumber,
  27060. const int controllerValue);
  27061. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  27062. render.
  27063. This value is propagated to the voices so that they can use it to render the correct
  27064. pitches.
  27065. */
  27066. void setCurrentPlaybackSampleRate (const double sampleRate);
  27067. /** Creates the next block of audio output.
  27068. This will process the next numSamples of data from all the voices, and add that output
  27069. to the audio block supplied, starting from the offset specified. Note that the
  27070. data will be added to the current contents of the buffer, so you should clear it
  27071. before calling this method if necessary.
  27072. The midi events in the inputMidi buffer are parsed for note and controller events,
  27073. and these are used to trigger the voices. Note that the startSample offset applies
  27074. both to the audio output buffer and the midi input buffer, so any midi events
  27075. with timestamps outside the specified region will be ignored.
  27076. */
  27077. void renderNextBlock (AudioSampleBuffer& outputAudio,
  27078. const MidiBuffer& inputMidi,
  27079. int startSample,
  27080. int numSamples);
  27081. juce_UseDebuggingNewOperator
  27082. protected:
  27083. /** This is used to control access to the rendering callback and the note trigger methods. */
  27084. CriticalSection lock;
  27085. OwnedArray <SynthesiserVoice> voices;
  27086. ReferenceCountedArray <SynthesiserSound> sounds;
  27087. /** The last pitch-wheel values for each midi channel. */
  27088. int lastPitchWheelValues [16];
  27089. /** Searches through the voices to find one that's not currently playing, and which
  27090. can play the given sound.
  27091. Returns 0 if all voices are busy and stealing isn't enabled.
  27092. This can be overridden to implement custom voice-stealing algorithms.
  27093. */
  27094. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  27095. const bool stealIfNoneAvailable) const;
  27096. /** Starts a specified voice playing a particular sound.
  27097. You'll probably never need to call this, it's used internally by noteOn(), but
  27098. may be needed by subclasses for custom behaviours.
  27099. */
  27100. void startVoice (SynthesiserVoice* const voice,
  27101. SynthesiserSound* const sound,
  27102. const int midiChannel,
  27103. const int midiNoteNumber,
  27104. const float velocity);
  27105. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  27106. int findFreeVoice (const bool) const { return 0; }
  27107. private:
  27108. double sampleRate;
  27109. uint32 lastNoteOnCounter;
  27110. bool shouldStealNotes;
  27111. Synthesiser (const Synthesiser&);
  27112. const Synthesiser& operator= (const Synthesiser&);
  27113. };
  27114. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  27115. /********* End of inlined file: juce_Synthesiser.h *********/
  27116. /**
  27117. A subclass of SynthesiserSound that represents a sampled audio clip.
  27118. This is a pretty basic sampler, and just attempts to load the whole audio stream
  27119. into memory.
  27120. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  27121. give it some SampledSound objects to play.
  27122. @see SamplerVoice, Synthesiser, SynthesiserSound
  27123. */
  27124. class JUCE_API SamplerSound : public SynthesiserSound
  27125. {
  27126. public:
  27127. /** Creates a sampled sound from an audio reader.
  27128. This will attempt to load the audio from the source into memory and store
  27129. it in this object.
  27130. @param name a name for the sample
  27131. @param source the audio to load. This object can be safely deleted by the
  27132. caller after this constructor returns
  27133. @param midiNotes the set of midi keys that this sound should be played on. This
  27134. is used by the SynthesiserSound::appliesToNote() method
  27135. @param midiNoteForNormalPitch the midi note at which the sample should be played
  27136. with its natural rate. All other notes will be pitched
  27137. up or down relative to this one
  27138. @param attackTimeSecs the attack (fade-in) time, in seconds
  27139. @param releaseTimeSecs the decay (fade-out) time, in seconds
  27140. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  27141. source, in seconds
  27142. */
  27143. SamplerSound (const String& name,
  27144. AudioFormatReader& source,
  27145. const BitArray& midiNotes,
  27146. const int midiNoteForNormalPitch,
  27147. const double attackTimeSecs,
  27148. const double releaseTimeSecs,
  27149. const double maxSampleLengthSeconds);
  27150. /** Destructor. */
  27151. ~SamplerSound();
  27152. /** Returns the sample's name */
  27153. const String& getName() const throw() { return name; }
  27154. /** Returns the audio sample data.
  27155. This could be 0 if there was a problem loading it.
  27156. */
  27157. AudioSampleBuffer* getAudioData() const throw() { return data; }
  27158. bool appliesToNote (const int midiNoteNumber);
  27159. bool appliesToChannel (const int midiChannel);
  27160. juce_UseDebuggingNewOperator
  27161. private:
  27162. friend class SamplerVoice;
  27163. String name;
  27164. AudioSampleBuffer* data;
  27165. double sourceSampleRate;
  27166. BitArray midiNotes;
  27167. int length, attackSamples, releaseSamples;
  27168. int midiRootNote;
  27169. };
  27170. /**
  27171. A subclass of SynthesiserVoice that can play a SamplerSound.
  27172. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  27173. give it some SampledSound objects to play.
  27174. @see SamplerSound, Synthesiser, SynthesiserVoice
  27175. */
  27176. class JUCE_API SamplerVoice : public SynthesiserVoice
  27177. {
  27178. public:
  27179. /** Creates a SamplerVoice.
  27180. */
  27181. SamplerVoice();
  27182. /** Destructor. */
  27183. ~SamplerVoice();
  27184. bool canPlaySound (SynthesiserSound* sound);
  27185. void startNote (const int midiNoteNumber,
  27186. const float velocity,
  27187. SynthesiserSound* sound,
  27188. const int currentPitchWheelPosition);
  27189. void stopNote (const bool allowTailOff);
  27190. void pitchWheelMoved (const int newValue);
  27191. void controllerMoved (const int controllerNumber,
  27192. const int newValue);
  27193. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  27194. juce_UseDebuggingNewOperator
  27195. private:
  27196. double pitchRatio;
  27197. double sourceSamplePosition;
  27198. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  27199. bool isInAttack, isInRelease;
  27200. };
  27201. #endif // __JUCE_SAMPLER_JUCEHEADER__
  27202. /********* End of inlined file: juce_Sampler.h *********/
  27203. #endif
  27204. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  27205. #endif
  27206. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27207. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  27208. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27209. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27210. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  27211. /**
  27212. Implements a plugin format manager for AudioUnits.
  27213. */
  27214. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  27215. {
  27216. public:
  27217. AudioUnitPluginFormat();
  27218. ~AudioUnitPluginFormat();
  27219. const String getName() const { return "AudioUnit"; }
  27220. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27221. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27222. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27223. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27224. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27225. bool doesPluginStillExist (const PluginDescription& desc);
  27226. const FileSearchPath getDefaultLocationsToSearch();
  27227. juce_UseDebuggingNewOperator
  27228. private:
  27229. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  27230. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  27231. };
  27232. #endif
  27233. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27234. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  27235. #endif
  27236. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27237. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  27238. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27239. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27240. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  27241. // Sorry, this file is just a placeholder at the moment!...
  27242. /**
  27243. Implements a plugin format manager for DirectX plugins.
  27244. */
  27245. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  27246. {
  27247. public:
  27248. DirectXPluginFormat();
  27249. ~DirectXPluginFormat();
  27250. const String getName() const { return "DirectX"; }
  27251. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27252. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27253. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27254. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  27255. const FileSearchPath getDefaultLocationsToSearch();
  27256. juce_UseDebuggingNewOperator
  27257. private:
  27258. DirectXPluginFormat (const DirectXPluginFormat&);
  27259. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  27260. };
  27261. #endif
  27262. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27263. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  27264. #endif
  27265. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27266. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  27267. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27268. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27269. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  27270. // Sorry, this file is just a placeholder at the moment!...
  27271. /**
  27272. Implements a plugin format manager for DirectX plugins.
  27273. */
  27274. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  27275. {
  27276. public:
  27277. LADSPAPluginFormat();
  27278. ~LADSPAPluginFormat();
  27279. const String getName() const { return "LADSPA"; }
  27280. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27281. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27282. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27283. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  27284. const FileSearchPath getDefaultLocationsToSearch();
  27285. juce_UseDebuggingNewOperator
  27286. private:
  27287. LADSPAPluginFormat (const LADSPAPluginFormat&);
  27288. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  27289. };
  27290. #endif
  27291. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27292. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  27293. #endif
  27294. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27295. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  27296. #ifdef __aeffect__
  27297. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27298. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27299. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  27300. events to the list.
  27301. This is used by both the VST hosting code and the plugin wrapper.
  27302. */
  27303. class VSTMidiEventList
  27304. {
  27305. public:
  27306. VSTMidiEventList()
  27307. : events (0), numEventsUsed (0), numEventsAllocated (0)
  27308. {
  27309. }
  27310. ~VSTMidiEventList()
  27311. {
  27312. freeEvents();
  27313. }
  27314. void clear()
  27315. {
  27316. numEventsUsed = 0;
  27317. if (events != 0)
  27318. events->numEvents = 0;
  27319. }
  27320. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  27321. {
  27322. ensureSize (numEventsUsed + 1);
  27323. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  27324. events->numEvents = ++numEventsUsed;
  27325. if (numBytes <= 4)
  27326. {
  27327. if (e->type == kVstSysExType)
  27328. {
  27329. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27330. e->type = kVstMidiType;
  27331. e->byteSize = sizeof (VstMidiEvent);
  27332. e->noteLength = 0;
  27333. e->noteOffset = 0;
  27334. e->detune = 0;
  27335. e->noteOffVelocity = 0;
  27336. }
  27337. e->deltaFrames = frameOffset;
  27338. memcpy (e->midiData, midiData, numBytes);
  27339. }
  27340. else
  27341. {
  27342. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  27343. if (se->type == kVstSysExType)
  27344. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  27345. else
  27346. se->sysexDump = (char*) juce_malloc (numBytes);
  27347. memcpy (se->sysexDump, midiData, numBytes);
  27348. se->type = kVstSysExType;
  27349. se->byteSize = sizeof (VstMidiSysexEvent);
  27350. se->deltaFrames = frameOffset;
  27351. se->flags = 0;
  27352. se->dumpBytes = numBytes;
  27353. se->resvd1 = 0;
  27354. se->resvd2 = 0;
  27355. }
  27356. }
  27357. // Handy method to pull the events out of an event buffer supplied by the host
  27358. // or plugin.
  27359. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  27360. {
  27361. for (int i = 0; i < events->numEvents; ++i)
  27362. {
  27363. const VstEvent* const e = events->events[i];
  27364. if (e != 0)
  27365. {
  27366. if (e->type == kVstMidiType)
  27367. {
  27368. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  27369. 4, e->deltaFrames);
  27370. }
  27371. else if (e->type == kVstSysExType)
  27372. {
  27373. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  27374. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  27375. e->deltaFrames);
  27376. }
  27377. }
  27378. }
  27379. }
  27380. void ensureSize (int numEventsNeeded)
  27381. {
  27382. if (numEventsNeeded > numEventsAllocated)
  27383. {
  27384. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  27385. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  27386. if (events == 0)
  27387. events = (VstEvents*) juce_calloc (size);
  27388. else
  27389. events = (VstEvents*) juce_realloc (events, size);
  27390. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  27391. {
  27392. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  27393. (int) sizeof (VstMidiSysexEvent)));
  27394. e->type = kVstMidiType;
  27395. e->byteSize = sizeof (VstMidiEvent);
  27396. events->events[i] = (VstEvent*) e;
  27397. }
  27398. numEventsAllocated = numEventsNeeded;
  27399. }
  27400. }
  27401. void freeEvents()
  27402. {
  27403. if (events != 0)
  27404. {
  27405. for (int i = numEventsAllocated; --i >= 0;)
  27406. {
  27407. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  27408. if (e->type == kVstSysExType)
  27409. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27410. juce_free (e);
  27411. }
  27412. juce_free (events);
  27413. events = 0;
  27414. numEventsUsed = 0;
  27415. numEventsAllocated = 0;
  27416. }
  27417. }
  27418. VstEvents* events;
  27419. private:
  27420. int numEventsUsed, numEventsAllocated;
  27421. };
  27422. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27423. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27424. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  27425. #endif
  27426. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27427. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  27428. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27429. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27430. #if JUCE_PLUGINHOST_VST
  27431. /**
  27432. Implements a plugin format manager for VSTs.
  27433. */
  27434. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  27435. {
  27436. public:
  27437. VSTPluginFormat();
  27438. ~VSTPluginFormat();
  27439. const String getName() const { return "VST"; }
  27440. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27441. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27442. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27443. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27444. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27445. bool doesPluginStillExist (const PluginDescription& desc);
  27446. const FileSearchPath getDefaultLocationsToSearch();
  27447. juce_UseDebuggingNewOperator
  27448. private:
  27449. VSTPluginFormat (const VSTPluginFormat&);
  27450. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  27451. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  27452. };
  27453. #endif
  27454. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27455. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  27456. #endif
  27457. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27458. #endif
  27459. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27460. #endif
  27461. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27462. #endif
  27463. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27464. #endif
  27465. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27466. #endif
  27467. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27468. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  27469. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27470. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27471. /**
  27472. Scans a directory for plugins, and adds them to a KnownPluginList.
  27473. To use one of these, create it and call scanNextFile() repeatedly, until
  27474. it returns false.
  27475. */
  27476. class JUCE_API PluginDirectoryScanner
  27477. {
  27478. public:
  27479. /**
  27480. Creates a scanner.
  27481. @param listToAddResultsTo this will get the new types added to it.
  27482. @param formatToLookFor this is the type of format that you want to look for
  27483. @param directoriesToSearch the path to search
  27484. @param searchRecursively true to search recursively
  27485. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  27486. be used as a file to store the names of any plugins
  27487. that crash during initialisation. If there are
  27488. any plugins listed in it, then these will always
  27489. be scanned after all other possible files have
  27490. been tried - in this way, even if there's a few
  27491. dodgy plugins in your path, then a couple of rescans
  27492. will still manage to find all the proper plugins.
  27493. It's probably best to choose a file in the user's
  27494. application data directory (alongside your app's
  27495. settings file) for this. The file format it uses
  27496. is just a list of filenames of the modules that
  27497. failed.
  27498. */
  27499. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  27500. AudioPluginFormat& formatToLookFor,
  27501. FileSearchPath directoriesToSearch,
  27502. const bool searchRecursively,
  27503. const File& deadMansPedalFile);
  27504. /** Destructor. */
  27505. ~PluginDirectoryScanner();
  27506. /** Tries the next likely-looking file.
  27507. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  27508. re-tested if it's not already in the list, or if the file's modification
  27509. time has changed since the list was created. If dontRescanIfAlreadyInList is
  27510. false, the file will always be reloaded and tested.
  27511. Returns false when there are no more files to try.
  27512. */
  27513. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  27514. /** Returns the description of the plugin that will be scanned during the next
  27515. call to scanNextFile().
  27516. This is handy if you want to show the user which file is currently getting
  27517. scanned.
  27518. */
  27519. const String getNextPluginFileThatWillBeScanned() const throw();
  27520. /** Returns the estimated progress, between 0 and 1.
  27521. */
  27522. float getProgress() const { return progress; }
  27523. /** This returns a list of all the filenames of things that looked like being
  27524. a plugin file, but which failed to open for some reason.
  27525. */
  27526. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  27527. juce_UseDebuggingNewOperator
  27528. private:
  27529. KnownPluginList& list;
  27530. AudioPluginFormat& format;
  27531. StringArray filesOrIdentifiersToScan;
  27532. File deadMansPedalFile;
  27533. StringArray failedFiles;
  27534. int nextIndex;
  27535. float progress;
  27536. const StringArray getDeadMansPedalFile() throw();
  27537. void setDeadMansPedalFile (const StringArray& newContents) throw();
  27538. PluginDirectoryScanner (const PluginDirectoryScanner&);
  27539. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  27540. };
  27541. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27542. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  27543. #endif
  27544. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27545. /********* Start of inlined file: juce_PluginListComponent.h *********/
  27546. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27547. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27548. /********* Start of inlined file: juce_ListBox.h *********/
  27549. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  27550. #define __JUCE_LISTBOX_JUCEHEADER__
  27551. class ListViewport;
  27552. /**
  27553. A subclass of this is used to drive a ListBox.
  27554. @see ListBox
  27555. */
  27556. class JUCE_API ListBoxModel
  27557. {
  27558. public:
  27559. /** Destructor. */
  27560. virtual ~ListBoxModel() {}
  27561. /** This has to return the number of items in the list.
  27562. @see ListBox::getNumRows()
  27563. */
  27564. virtual int getNumRows() = 0;
  27565. /** This method must be implemented to draw a row of the list.
  27566. */
  27567. virtual void paintListBoxItem (int rowNumber,
  27568. Graphics& g,
  27569. int width, int height,
  27570. bool rowIsSelected) = 0;
  27571. /** This is used to create or update a custom component to go in a row of the list.
  27572. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  27573. and handle mouse clicks with listBoxItemClicked().
  27574. This method will be called whenever a custom component might need to be updated - e.g.
  27575. when the table is changed, or TableListBox::updateContent() is called.
  27576. If you don't need a custom component for the specified row, then return 0.
  27577. If you do want a custom component, and the existingComponentToUpdate is null, then
  27578. this method must create a suitable new component and return it.
  27579. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  27580. by this method. In this case, the method must either update it to make sure it's correctly representing
  27581. the given row (which may be different from the one that the component was created for), or it can
  27582. delete this component and return a new one.
  27583. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  27584. */
  27585. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  27586. Component* existingComponentToUpdate);
  27587. /** This can be overridden to react to the user clicking on a row.
  27588. @see listBoxItemDoubleClicked
  27589. */
  27590. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  27591. /** This can be overridden to react to the user double-clicking on a row.
  27592. @see listBoxItemClicked
  27593. */
  27594. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  27595. /** This can be overridden to react to the user double-clicking on a part of the list where
  27596. there are no rows.
  27597. @see listBoxItemClicked
  27598. */
  27599. virtual void backgroundClicked();
  27600. /** Override this to be informed when rows are selected or deselected.
  27601. This will be called whenever a row is selected or deselected. If a range of
  27602. rows is selected all at once, this will just be called once for that event.
  27603. @param lastRowSelected the last row that the user selected. If no
  27604. rows are currently selected, this may be -1.
  27605. */
  27606. virtual void selectedRowsChanged (int lastRowSelected);
  27607. /** Override this to be informed when the delete key is pressed.
  27608. If no rows are selected when they press the key, this won't be called.
  27609. @param lastRowSelected the last row that had been selected when they pressed the
  27610. key - if there are multiple selections, this might not be
  27611. very useful
  27612. */
  27613. virtual void deleteKeyPressed (int lastRowSelected);
  27614. /** Override this to be informed when the return key is pressed.
  27615. If no rows are selected when they press the key, this won't be called.
  27616. @param lastRowSelected the last row that had been selected when they pressed the
  27617. key - if there are multiple selections, this might not be
  27618. very useful
  27619. */
  27620. virtual void returnKeyPressed (int lastRowSelected);
  27621. /** Override this to be informed when the list is scrolled.
  27622. This might be caused by the user moving the scrollbar, or by programmatic changes
  27623. to the list position.
  27624. */
  27625. virtual void listWasScrolled();
  27626. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  27627. If this returns a non-empty name then when the user drags a row, the listbox will
  27628. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  27629. a drag-and-drop operation, using this string as the source description, with the listbox
  27630. itself as the source component.
  27631. @see DragAndDropContainer::startDragging
  27632. */
  27633. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  27634. /** You can override this to provide tool tips for specific rows.
  27635. @see TooltipClient
  27636. */
  27637. virtual const String getTooltipForRow (int row);
  27638. };
  27639. /**
  27640. A list of items that can be scrolled vertically.
  27641. To create a list, you'll need to create a subclass of ListBoxModel. This can
  27642. either paint each row of the list and respond to events via callbacks, or for
  27643. more specialised tasks, it can supply a custom component to fill each row.
  27644. @see ComboBox, TableListBox
  27645. */
  27646. class JUCE_API ListBox : public Component,
  27647. public SettableTooltipClient
  27648. {
  27649. public:
  27650. /** Creates a ListBox.
  27651. The model pointer passed-in can be null, in which case you can set it later
  27652. with setModel().
  27653. */
  27654. ListBox (const String& componentName,
  27655. ListBoxModel* const model);
  27656. /** Destructor. */
  27657. ~ListBox();
  27658. /** Changes the current data model to display. */
  27659. void setModel (ListBoxModel* const newModel);
  27660. /** Returns the current list model. */
  27661. ListBoxModel* getModel() const throw() { return model; }
  27662. /** Causes the list to refresh its content.
  27663. Call this when the number of rows in the list changes, or if you want it
  27664. to call refreshComponentForRow() on all the row components.
  27665. Be careful not to call it from a different thread, though, as it's not
  27666. thread-safe.
  27667. */
  27668. void updateContent();
  27669. /** Turns on multiple-selection of rows.
  27670. By default this is disabled.
  27671. When your row component gets clicked you'll need to call the
  27672. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  27673. clicked and to get it to do the appropriate selection based on whether
  27674. the ctrl/shift keys are held down.
  27675. */
  27676. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  27677. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  27678. This function is here primarily for the ComboBox class to use, but might be
  27679. useful for some other purpose too.
  27680. */
  27681. void setMouseMoveSelectsRows (bool shouldSelect);
  27682. /** Selects a row.
  27683. If the row is already selected, this won't do anything.
  27684. @param rowNumber the row to select
  27685. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  27686. the selected row is off-screen, it'll scroll to make
  27687. sure that row is on-screen
  27688. @param deselectOthersFirst if true and there are multiple selections, these will
  27689. first be deselected before this item is selected
  27690. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  27691. deselectAllRows, selectRangeOfRows
  27692. */
  27693. void selectRow (const int rowNumber,
  27694. bool dontScrollToShowThisRow = false,
  27695. bool deselectOthersFirst = true);
  27696. /** Selects a set of rows.
  27697. This will add these rows to the current selection, so you might need to
  27698. clear the current selection first with deselectAllRows()
  27699. @param firstRow the first row to select (inclusive)
  27700. @param lastRow the last row to select (inclusive)
  27701. */
  27702. void selectRangeOfRows (int firstRow,
  27703. int lastRow);
  27704. /** Deselects a row.
  27705. If it's not currently selected, this will do nothing.
  27706. @see selectRow, deselectAllRows
  27707. */
  27708. void deselectRow (const int rowNumber);
  27709. /** Deselects any currently selected rows.
  27710. @see deselectRow
  27711. */
  27712. void deselectAllRows();
  27713. /** Selects or deselects a row.
  27714. If the row's currently selected, this deselects it, and vice-versa.
  27715. */
  27716. void flipRowSelection (const int rowNumber);
  27717. /** Returns a sparse set indicating the rows that are currently selected.
  27718. @see setSelectedRows
  27719. */
  27720. const SparseSet<int> getSelectedRows() const;
  27721. /** Sets the rows that should be selected, based on an explicit set of ranges.
  27722. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  27723. method will be called. If it's false, no notification will be sent to the model.
  27724. @see getSelectedRows
  27725. */
  27726. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  27727. const bool sendNotificationEventToModel = true);
  27728. /** Checks whether a row is selected.
  27729. */
  27730. bool isRowSelected (const int rowNumber) const;
  27731. /** Returns the number of rows that are currently selected.
  27732. @see getSelectedRow, isRowSelected, getLastRowSelected
  27733. */
  27734. int getNumSelectedRows() const;
  27735. /** Returns the row number of a selected row.
  27736. This will return the row number of the Nth selected row. The row numbers returned will
  27737. be sorted in order from low to high.
  27738. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  27739. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  27740. selected
  27741. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  27742. */
  27743. int getSelectedRow (const int index = 0) const;
  27744. /** Returns the last row that the user selected.
  27745. This isn't the same as the highest row number that is currently selected - if the user
  27746. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  27747. If nothing is selected, it will return -1.
  27748. */
  27749. int getLastRowSelected() const;
  27750. /** Multiply-selects rows based on the modifier keys.
  27751. If no modifier keys are down, this will select the given row and
  27752. deselect any others.
  27753. If the ctrl (or command on the Mac) key is down, it'll flip the
  27754. state of the selected row.
  27755. If the shift key is down, it'll select up to the given row from the
  27756. last row selected.
  27757. @see selectRow
  27758. */
  27759. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  27760. const ModifierKeys& modifiers);
  27761. /** Scrolls the list to a particular position.
  27762. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  27763. 1.0 scrolls to the bottom.
  27764. If the total number of rows all fit onto the screen at once, then this
  27765. method won't do anything.
  27766. @see getVerticalPosition
  27767. */
  27768. void setVerticalPosition (const double newProportion);
  27769. /** Returns the current vertical position as a proportion of the total.
  27770. This can be used in conjunction with setVerticalPosition() to save and restore
  27771. the list's position. It returns a value in the range 0 to 1.
  27772. @see setVerticalPosition
  27773. */
  27774. double getVerticalPosition() const;
  27775. /** Scrolls if necessary to make sure that a particular row is visible.
  27776. */
  27777. void scrollToEnsureRowIsOnscreen (const int row);
  27778. /** Returns a pointer to the scrollbar.
  27779. (Unlikely to be useful for most people).
  27780. */
  27781. ScrollBar* getVerticalScrollBar() const throw();
  27782. /** Returns a pointer to the scrollbar.
  27783. (Unlikely to be useful for most people).
  27784. */
  27785. ScrollBar* getHorizontalScrollBar() const throw();
  27786. /** Finds the row index that contains a given x,y position.
  27787. The position is relative to the ListBox's top-left.
  27788. If no row exists at this position, the method will return -1.
  27789. @see getComponentForRowNumber
  27790. */
  27791. int getRowContainingPosition (const int x, const int y) const throw();
  27792. /** Finds a row index that would be the most suitable place to insert a new
  27793. item for a given position.
  27794. This is useful when the user is e.g. dragging and dropping onto the listbox,
  27795. because it lets you easily choose the best position to insert the item that
  27796. they drop, based on where they drop it.
  27797. If the position is out of range, this will return -1. If the position is
  27798. beyond the end of the list, it will return getNumRows() to indicate the end
  27799. of the list.
  27800. @see getComponentForRowNumber
  27801. */
  27802. int getInsertionIndexForPosition (const int x, const int y) const throw();
  27803. /** Returns the position of one of the rows, relative to the top-left of
  27804. the listbox.
  27805. This may be off-screen, and the range of the row number that is passed-in is
  27806. not checked to see if it's a valid row.
  27807. */
  27808. const Rectangle getRowPosition (const int rowNumber,
  27809. const bool relativeToComponentTopLeft) const throw();
  27810. /** Finds the row component for a given row in the list.
  27811. The component returned will have been created using createRowComponent().
  27812. If the component for this row is off-screen or if the row is out-of-range,
  27813. this will return 0.
  27814. @see getRowContainingPosition
  27815. */
  27816. Component* getComponentForRowNumber (const int rowNumber) const throw();
  27817. /** Returns the row number that the given component represents.
  27818. If the component isn't one of the list's rows, this will return -1.
  27819. */
  27820. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  27821. /** Returns the width of a row (which may be less than the width of this component
  27822. if there's a scrollbar).
  27823. */
  27824. int getVisibleRowWidth() const throw();
  27825. /** Sets the height of each row in the list.
  27826. The default height is 22 pixels.
  27827. @see getRowHeight
  27828. */
  27829. void setRowHeight (const int newHeight);
  27830. /** Returns the height of a row in the list.
  27831. @see setRowHeight
  27832. */
  27833. int getRowHeight() const throw() { return rowHeight; }
  27834. /** Returns the number of rows actually visible.
  27835. This is the number of whole rows which will fit on-screen, so the value might
  27836. be more than the actual number of rows in the list.
  27837. */
  27838. int getNumRowsOnScreen() const throw();
  27839. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27840. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27841. methods.
  27842. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27843. */
  27844. enum ColourIds
  27845. {
  27846. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  27847. Make this transparent if you don't want the background to be filled. */
  27848. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  27849. Make this transparent to not have an outline. */
  27850. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  27851. };
  27852. /** Sets the thickness of a border that will be drawn around the box.
  27853. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  27854. @see outlineColourId
  27855. */
  27856. void setOutlineThickness (const int outlineThickness);
  27857. /** Returns the thickness of outline that will be drawn around the listbox.
  27858. @see setOutlineColour
  27859. */
  27860. int getOutlineThickness() const throw() { return outlineThickness; }
  27861. /** Sets a component that the list should use as a header.
  27862. This will position the given component at the top of the list, maintaining the
  27863. height of the component passed-in, but rescaling it horizontally to match the
  27864. width of the items in the listbox.
  27865. The component will be deleted when setHeaderComponent() is called with a
  27866. different component, or when the listbox is deleted.
  27867. */
  27868. void setHeaderComponent (Component* const newHeaderComponent);
  27869. /** Changes the width of the rows in the list.
  27870. This can be used to make the list's row components wider than the list itself - the
  27871. width of the rows will be either the width of the list or this value, whichever is
  27872. greater, and if the rows become wider than the list, a horizontal scrollbar will
  27873. appear.
  27874. The default value for this is 0, which means that the rows will always
  27875. be the same width as the list.
  27876. */
  27877. void setMinimumContentWidth (const int newMinimumWidth);
  27878. /** Returns the space currently available for the row items, taking into account
  27879. borders, scrollbars, etc.
  27880. */
  27881. int getVisibleContentWidth() const throw();
  27882. /** Repaints one of the rows.
  27883. This is a lightweight alternative to calling updateContent, and just causes a
  27884. repaint of the row's area.
  27885. */
  27886. void repaintRow (const int rowNumber) throw();
  27887. /** This fairly obscure method creates an image that just shows the currently
  27888. selected row components.
  27889. It's a handy method for doing drag-and-drop, as it can be passed to the
  27890. DragAndDropContainer for use as the drag image.
  27891. Note that it will make the row components temporarily invisible, so if you're
  27892. using custom components this could affect them if they're sensitive to that
  27893. sort of thing.
  27894. @see Component::createComponentSnapshot
  27895. */
  27896. Image* createSnapshotOfSelectedRows();
  27897. /** Returns the viewport that this ListBox uses.
  27898. You may need to use this to change parameters such as whether scrollbars
  27899. are shown, etc.
  27900. */
  27901. Viewport* getViewport() const throw();
  27902. /** @internal */
  27903. bool keyPressed (const KeyPress& key);
  27904. /** @internal */
  27905. bool keyStateChanged (const bool isKeyDown);
  27906. /** @internal */
  27907. void paint (Graphics& g);
  27908. /** @internal */
  27909. void paintOverChildren (Graphics& g);
  27910. /** @internal */
  27911. void resized();
  27912. /** @internal */
  27913. void visibilityChanged();
  27914. /** @internal */
  27915. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27916. /** @internal */
  27917. void mouseMove (const MouseEvent&);
  27918. /** @internal */
  27919. void mouseExit (const MouseEvent&);
  27920. /** @internal */
  27921. void mouseUp (const MouseEvent&);
  27922. /** @internal */
  27923. void colourChanged();
  27924. juce_UseDebuggingNewOperator
  27925. private:
  27926. friend class ListViewport;
  27927. friend class TableListBox;
  27928. ListBoxModel* model;
  27929. ListViewport* viewport;
  27930. Component* headerComponent;
  27931. int totalItems, rowHeight, minimumRowWidth;
  27932. int outlineThickness;
  27933. int lastMouseX, lastMouseY, lastRowSelected;
  27934. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  27935. SparseSet <int> selected;
  27936. void selectRowInternal (const int rowNumber,
  27937. bool dontScrollToShowThisRow,
  27938. bool deselectOthersFirst,
  27939. bool isMouseClick);
  27940. ListBox (const ListBox&);
  27941. const ListBox& operator= (const ListBox&);
  27942. };
  27943. #endif // __JUCE_LISTBOX_JUCEHEADER__
  27944. /********* End of inlined file: juce_ListBox.h *********/
  27945. /********* Start of inlined file: juce_TextButton.h *********/
  27946. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  27947. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  27948. /**
  27949. A button that uses the standard lozenge-shaped background with a line of
  27950. text on it.
  27951. @see Button, DrawableButton
  27952. */
  27953. class JUCE_API TextButton : public Button
  27954. {
  27955. public:
  27956. /** Creates a TextButton.
  27957. @param buttonName the text to put in the button (the component's name is also
  27958. initially set to this string, but these can be changed later
  27959. using the setName() and setButtonText() methods)
  27960. @param toolTip an optional string to use as a toolip
  27961. @see Button
  27962. */
  27963. TextButton (const String& buttonName,
  27964. const String& toolTip = String::empty);
  27965. /** Destructor. */
  27966. ~TextButton();
  27967. /** A set of colour IDs to use to change the colour of various aspects of the button.
  27968. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27969. methods.
  27970. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27971. */
  27972. enum ColourIds
  27973. {
  27974. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  27975. 'off'). The look-and-feel class might re-interpret this to add
  27976. effects, etc. */
  27977. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  27978. 'on'). The look-and-feel class might re-interpret this to add
  27979. effects, etc. */
  27980. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  27981. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  27982. };
  27983. /** Resizes the button to fit neatly around its current text.
  27984. If newHeight is >= 0, the button's height will be changed to this
  27985. value. If it's less than zero, its height will be unaffected.
  27986. */
  27987. void changeWidthToFitText (const int newHeight = -1);
  27988. /** This can be overridden to use different fonts than the default one.
  27989. Note that you'll need to set the font's size appropriately, too.
  27990. */
  27991. virtual const Font getFont();
  27992. juce_UseDebuggingNewOperator
  27993. protected:
  27994. /** @internal */
  27995. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  27996. /** @internal */
  27997. void colourChanged();
  27998. private:
  27999. TextButton (const TextButton&);
  28000. const TextButton& operator= (const TextButton&);
  28001. };
  28002. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  28003. /********* End of inlined file: juce_TextButton.h *********/
  28004. /**
  28005. A component displaying a list of plugins, with options to scan for them,
  28006. add, remove and sort them.
  28007. */
  28008. class JUCE_API PluginListComponent : public Component,
  28009. public ListBoxModel,
  28010. public ChangeListener,
  28011. public ButtonListener,
  28012. public Timer
  28013. {
  28014. public:
  28015. /**
  28016. Creates the list component.
  28017. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  28018. The properties file, if supplied, is used to store the user's last search paths.
  28019. */
  28020. PluginListComponent (KnownPluginList& listToRepresent,
  28021. const File& deadMansPedalFile,
  28022. PropertiesFile* const propertiesToUse);
  28023. /** Destructor. */
  28024. ~PluginListComponent();
  28025. /** @internal */
  28026. void resized();
  28027. /** @internal */
  28028. bool isInterestedInFileDrag (const StringArray& files);
  28029. /** @internal */
  28030. void filesDropped (const StringArray& files, int, int);
  28031. /** @internal */
  28032. int getNumRows();
  28033. /** @internal */
  28034. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  28035. /** @internal */
  28036. void deleteKeyPressed (int lastRowSelected);
  28037. /** @internal */
  28038. void buttonClicked (Button* b);
  28039. /** @internal */
  28040. void changeListenerCallback (void*);
  28041. /** @internal */
  28042. void timerCallback();
  28043. juce_UseDebuggingNewOperator
  28044. private:
  28045. KnownPluginList& list;
  28046. File deadMansPedalFile;
  28047. ListBox* listBox;
  28048. TextButton* optionsButton;
  28049. PropertiesFile* propertiesToUse;
  28050. int typeToScan;
  28051. void scanFor (AudioPluginFormat* format);
  28052. PluginListComponent (const PluginListComponent&);
  28053. const PluginListComponent& operator= (const PluginListComponent&);
  28054. };
  28055. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  28056. /********* End of inlined file: juce_PluginListComponent.h *********/
  28057. #endif
  28058. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28059. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  28060. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28061. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28062. /********* Start of inlined file: juce_AudioFormat.h *********/
  28063. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28064. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  28065. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  28066. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28067. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28068. /**
  28069. Writes samples to an audio file stream.
  28070. A subclass that writes a specific type of audio format will be created by
  28071. an AudioFormat object.
  28072. After creating one of these with the AudioFormat::createWriterFor() method
  28073. you can call its write() method to store the samples, and then delete it.
  28074. @see AudioFormat, AudioFormatReader
  28075. */
  28076. class JUCE_API AudioFormatWriter
  28077. {
  28078. protected:
  28079. /** Creates an AudioFormatWriter object.
  28080. @param destStream the stream to write to - this will be deleted
  28081. by this object when it is no longer needed
  28082. @param formatName the description that will be returned by the getFormatName()
  28083. method
  28084. @param sampleRate the sample rate to use - the base class just stores
  28085. this value, it doesn't do anything with it
  28086. @param numberOfChannels the number of channels to write - the base class just stores
  28087. this value, it doesn't do anything with it
  28088. @param bitsPerSample the bit depth of the stream - the base class just stores
  28089. this value, it doesn't do anything with it
  28090. */
  28091. AudioFormatWriter (OutputStream* const destStream,
  28092. const String& formatName,
  28093. const double sampleRate,
  28094. const unsigned int numberOfChannels,
  28095. const unsigned int bitsPerSample);
  28096. public:
  28097. /** Destructor. */
  28098. virtual ~AudioFormatWriter();
  28099. /** Returns a description of what type of format this is.
  28100. E.g. "AIFF file"
  28101. */
  28102. const String getFormatName() const throw() { return formatName; }
  28103. /** Writes a set of samples to the audio stream.
  28104. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  28105. can use AudioSampleBuffer::writeToAudioWriter().
  28106. @param samplesToWrite an array of arrays containing the sample data for
  28107. each channel to write. This is a zero-terminated
  28108. array of arrays, and can contain a different number
  28109. of channels than the actual stream uses, and the
  28110. writer should do its best to cope with this.
  28111. If the format is fixed-point, each channel will be formatted
  28112. as an array of signed integers using the full 32-bit
  28113. range -0x80000000 to 0x7fffffff, regardless of the source's
  28114. bit-depth. If it is a floating-point format, you should treat
  28115. the arrays as arrays of floats, and just cast it to an (int**)
  28116. to pass it into the method.
  28117. @param numSamples the number of samples to write
  28118. */
  28119. virtual bool write (const int** samplesToWrite,
  28120. int numSamples) = 0;
  28121. /** Reads a section of samples from an AudioFormatReader, and writes these to
  28122. the output.
  28123. This will take care of any floating-point conversion that's required to convert
  28124. between the two formats. It won't deal with sample-rate conversion, though.
  28125. If numSamplesToRead < 0, it will write the entire length of the reader.
  28126. @returns false if it can't read or write properly during the operation
  28127. */
  28128. bool writeFromAudioReader (AudioFormatReader& reader,
  28129. int64 startSample,
  28130. int64 numSamplesToRead);
  28131. /** Reads some samples from an AudioSource, and writes these to the output.
  28132. The source must already have been initialised with the AudioSource::prepareToPlay() method
  28133. @param source the source to read from
  28134. @param numSamplesToRead total number of samples to read and write
  28135. @param samplesPerBlock the maximum number of samples to fetch from the source
  28136. @returns false if it can't read or write properly during the operation
  28137. */
  28138. bool writeFromAudioSource (AudioSource& source,
  28139. int numSamplesToRead,
  28140. const int samplesPerBlock = 2048);
  28141. /** Returns the sample rate being used. */
  28142. double getSampleRate() const throw() { return sampleRate; }
  28143. /** Returns the number of channels being written. */
  28144. int getNumChannels() const throw() { return numChannels; }
  28145. /** Returns the bit-depth of the data being written. */
  28146. int getBitsPerSample() const throw() { return bitsPerSample; }
  28147. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  28148. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  28149. juce_UseDebuggingNewOperator
  28150. protected:
  28151. /** The sample rate of the stream. */
  28152. double sampleRate;
  28153. /** The number of channels being written to the stream. */
  28154. unsigned int numChannels;
  28155. /** The bit depth of the file. */
  28156. unsigned int bitsPerSample;
  28157. /** True if it's a floating-point format, false if it's fixed-point. */
  28158. bool usesFloatingPointData;
  28159. /** The output stream for Use by subclasses. */
  28160. OutputStream* output;
  28161. private:
  28162. String formatName;
  28163. };
  28164. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28165. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  28166. /**
  28167. Subclasses of AudioFormat are used to read and write different audio
  28168. file formats.
  28169. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  28170. */
  28171. class JUCE_API AudioFormat
  28172. {
  28173. public:
  28174. /** Destructor. */
  28175. virtual ~AudioFormat();
  28176. /** Returns the name of this format.
  28177. e.g. "WAV file" or "AIFF file"
  28178. */
  28179. const String& getFormatName() const;
  28180. /** Returns all the file extensions that might apply to a file of this format.
  28181. The first item will be the one that's preferred when creating a new file.
  28182. So for a wav file this might just return ".wav"; for an AIFF file it might
  28183. return two items, ".aif" and ".aiff"
  28184. */
  28185. const StringArray& getFileExtensions() const;
  28186. /** Returns true if this the given file can be read by this format.
  28187. Subclasses shouldn't do too much work here, just check the extension or
  28188. file type. The base class implementation just checks the file's extension
  28189. against one of the ones that was registered in the constructor.
  28190. */
  28191. virtual bool canHandleFile (const File& fileToTest);
  28192. /** Returns a set of sample rates that the format can read and write. */
  28193. virtual const Array <int> getPossibleSampleRates() = 0;
  28194. /** Returns a set of bit depths that the format can read and write. */
  28195. virtual const Array <int> getPossibleBitDepths() = 0;
  28196. /** Returns true if the format can do 2-channel audio. */
  28197. virtual bool canDoStereo() = 0;
  28198. /** Returns true if the format can do 1-channel audio. */
  28199. virtual bool canDoMono() = 0;
  28200. /** Returns true if the format uses compressed data. */
  28201. virtual bool isCompressed();
  28202. /** Returns a list of different qualities that can be used when writing.
  28203. Non-compressed formats will just return an empty array, but for something
  28204. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  28205. When calling createWriterFor(), an index from this array is passed in to
  28206. tell the format which option is required.
  28207. */
  28208. virtual const StringArray getQualityOptions();
  28209. /** Tries to create an object that can read from a stream containing audio
  28210. data in this format.
  28211. The reader object that is returned can be used to read from the stream, and
  28212. should then be deleted by the caller.
  28213. @param sourceStream the stream to read from - the AudioFormatReader object
  28214. that is returned will delete this stream when it no longer
  28215. needs it.
  28216. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  28217. should delete the stream object that was passed-in. (If a valid
  28218. reader is returned, it will always be in charge of deleting the
  28219. stream, so this parameter is ignored)
  28220. @see AudioFormatReader
  28221. */
  28222. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28223. const bool deleteStreamIfOpeningFails) = 0;
  28224. /** Tries to create an object that can write to a stream with this audio format.
  28225. The writer object that is returned can be used to write to the stream, and
  28226. should then be deleted by the caller.
  28227. If the stream can't be created for some reason (e.g. the parameters passed in
  28228. here aren't suitable), this will return 0.
  28229. @param streamToWriteTo the stream that the data will go to - this will be
  28230. deleted by the AudioFormatWriter object when it's no longer
  28231. needed. If no AudioFormatWriter can be created by this method,
  28232. the stream will NOT be deleted, so that the caller can re-use it
  28233. to try to open a different format, etc
  28234. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  28235. returned by getPossibleSampleRates()
  28236. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  28237. the choice will depend on the results of canDoMono() and
  28238. canDoStereo()
  28239. @param bitsPerSample the bits per sample to use - this must be one of the values
  28240. returned by getPossibleBitDepths()
  28241. @param metadataValues a set of metadata values that the writer should try to write
  28242. to the stream. Exactly what these are depends on the format,
  28243. and the subclass doesn't actually have to do anything with
  28244. them if it doesn't want to. Have a look at the specific format
  28245. implementation classes to see possible values that can be
  28246. used
  28247. @param qualityOptionIndex the index of one of compression qualities returned by the
  28248. getQualityOptions() method. If there aren't any quality options
  28249. for this format, just pass 0 in this parameter, as it'll be
  28250. ignored
  28251. @see AudioFormatWriter
  28252. */
  28253. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28254. double sampleRateToUse,
  28255. unsigned int numberOfChannels,
  28256. int bitsPerSample,
  28257. const StringPairArray& metadataValues,
  28258. int qualityOptionIndex) = 0;
  28259. protected:
  28260. /** Creates an AudioFormat object.
  28261. @param formatName this sets the value that will be returned by getFormatName()
  28262. @param fileExtensions a zero-terminated list of file extensions - this is what will
  28263. be returned by getFileExtension()
  28264. */
  28265. AudioFormat (const String& formatName,
  28266. const tchar** const fileExtensions);
  28267. private:
  28268. String formatName;
  28269. StringArray fileExtensions;
  28270. };
  28271. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  28272. /********* End of inlined file: juce_AudioFormat.h *********/
  28273. /**
  28274. Reads and Writes AIFF format audio files.
  28275. @see AudioFormat
  28276. */
  28277. class JUCE_API AiffAudioFormat : public AudioFormat
  28278. {
  28279. public:
  28280. /** Creates an format object. */
  28281. AiffAudioFormat();
  28282. /** Destructor. */
  28283. ~AiffAudioFormat();
  28284. const Array <int> getPossibleSampleRates();
  28285. const Array <int> getPossibleBitDepths();
  28286. bool canDoStereo();
  28287. bool canDoMono();
  28288. #if JUCE_MAC
  28289. bool canHandleFile (const File& fileToTest);
  28290. #endif
  28291. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28292. const bool deleteStreamIfOpeningFails);
  28293. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28294. double sampleRateToUse,
  28295. unsigned int numberOfChannels,
  28296. int bitsPerSample,
  28297. const StringPairArray& metadataValues,
  28298. int qualityOptionIndex);
  28299. juce_UseDebuggingNewOperator
  28300. };
  28301. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28302. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  28303. #endif
  28304. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28305. #endif
  28306. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28307. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  28308. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28309. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28310. /**
  28311. A class for keeping a list of available audio formats, and for deciding which
  28312. one to use to open a given file.
  28313. You can either use this class as a singleton object, or create instances of it
  28314. yourself. Once created, use its registerFormat() method to tell it which
  28315. formats it should use.
  28316. @see AudioFormat
  28317. */
  28318. class JUCE_API AudioFormatManager
  28319. {
  28320. public:
  28321. /** Creates an empty format manager.
  28322. Before it'll be any use, you'll need to call registerFormat() with all the
  28323. formats you want it to be able to recognise.
  28324. */
  28325. AudioFormatManager();
  28326. /** Destructor. */
  28327. ~AudioFormatManager();
  28328. juce_DeclareSingleton (AudioFormatManager, false);
  28329. /** Adds a format to the manager's list of available file types.
  28330. The object passed-in will be deleted by this object, so don't keep a pointer
  28331. to it!
  28332. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28333. return this one when called.
  28334. */
  28335. void registerFormat (AudioFormat* newFormat,
  28336. const bool makeThisTheDefaultFormat);
  28337. /** Handy method to make it easy to register the formats that come with Juce.
  28338. Currently, this will add WAV and AIFF to the list.
  28339. */
  28340. void registerBasicFormats();
  28341. /** Clears the list of known formats. */
  28342. void clearFormats();
  28343. /** Returns the number of currently registered file formats. */
  28344. int getNumKnownFormats() const;
  28345. /** Returns one of the registered file formats. */
  28346. AudioFormat* getKnownFormat (const int index) const;
  28347. /** Looks for which of the known formats is listed as being for a given file
  28348. extension.
  28349. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28350. */
  28351. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28352. /** Returns the format which has been set as the default one.
  28353. You can set a format as being the default when it is registered. It's useful
  28354. when you want to write to a file, because the best format may change between
  28355. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28356. If none has been set as the default, this method will just return the first
  28357. one in the list.
  28358. */
  28359. AudioFormat* getDefaultFormat() const;
  28360. /** Returns a set of wildcards for file-matching that contains the extensions for
  28361. all known formats.
  28362. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28363. */
  28364. const String getWildcardForAllFormats() const;
  28365. /** Searches through the known formats to try to create a suitable reader for
  28366. this file.
  28367. If none of the registered formats can open the file, it'll return 0. If it
  28368. returns a reader, it's the caller's responsibility to delete the reader.
  28369. */
  28370. AudioFormatReader* createReaderFor (const File& audioFile);
  28371. /** Searches through the known formats to try to create a suitable reader for
  28372. this stream.
  28373. The stream object that is passed-in will be deleted by this method or by the
  28374. reader that is returned, so the caller should not keep any references to it.
  28375. The stream that is passed-in must be capable of being repositioned so
  28376. that all the formats can have a go at opening it.
  28377. If none of the registered formats can open the stream, it'll return 0. If it
  28378. returns a reader, it's the caller's responsibility to delete the reader.
  28379. */
  28380. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28381. juce_UseDebuggingNewOperator
  28382. private:
  28383. VoidArray knownFormats;
  28384. int defaultFormatIndex;
  28385. };
  28386. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28387. /********* End of inlined file: juce_AudioFormatManager.h *********/
  28388. #endif
  28389. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28390. #endif
  28391. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28392. #endif
  28393. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28394. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  28395. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28396. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28397. /**
  28398. This class is used to wrap an AudioFormatReader and only read from a
  28399. subsection of the file.
  28400. So if you have a reader which can read a 1000 sample file, you could wrap it
  28401. in one of these to only access, e.g. samples 100 to 200, and any samples
  28402. outside that will come back as 0. Accessing sample 0 from this reader will
  28403. actually read the first sample from the other's subsection, which might
  28404. be at a non-zero position.
  28405. @see AudioFormatReader
  28406. */
  28407. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28408. {
  28409. public:
  28410. /** Creates a AudioSubsectionReader for a given data source.
  28411. @param sourceReader the source reader from which we'll be taking data
  28412. @param subsectionStartSample the sample within the source reader which will be
  28413. mapped onto sample 0 for this reader.
  28414. @param subsectionLength the number of samples from the source that will
  28415. make up the subsection. If this reader is asked for
  28416. any samples beyond this region, it will return zero.
  28417. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28418. this object is deleted.
  28419. */
  28420. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  28421. const int64 subsectionStartSample,
  28422. const int64 subsectionLength,
  28423. const bool deleteSourceWhenDeleted);
  28424. /** Destructor. */
  28425. ~AudioSubsectionReader();
  28426. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28427. int64 startSampleInFile, int numSamples);
  28428. void readMaxLevels (int64 startSample,
  28429. int64 numSamples,
  28430. float& lowestLeft,
  28431. float& highestLeft,
  28432. float& lowestRight,
  28433. float& highestRight);
  28434. juce_UseDebuggingNewOperator
  28435. private:
  28436. AudioFormatReader* const source;
  28437. int64 startSample, length;
  28438. const bool deleteSourceWhenDeleted;
  28439. AudioSubsectionReader (const AudioSubsectionReader&);
  28440. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  28441. };
  28442. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28443. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  28444. #endif
  28445. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28446. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  28447. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28448. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28449. class AudioThumbnailCache;
  28450. /**
  28451. Makes it easy to quickly draw scaled views of the waveform shape of an
  28452. audio file.
  28453. To use this class, just create an AudioThumbNail class for the file you want
  28454. to draw, call setSource to tell it which file or resource to use, then call
  28455. drawChannel() to draw it.
  28456. The class will asynchronously scan the wavefile to create its scaled-down view,
  28457. so you should make your UI repaint itself as this data comes in. To do this, the
  28458. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28459. listeners should repaint themselves.
  28460. The thumbnail stores an internal low-res version of the wave data, and this can
  28461. be loaded and saved to avoid having to scan the file again.
  28462. @see AudioThumbnailCache
  28463. */
  28464. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  28465. public TimeSliceClient,
  28466. private Timer
  28467. {
  28468. public:
  28469. /** Creates an audio thumbnail.
  28470. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28471. of the audio data, this is the scale at which it should be done. (This
  28472. number is the number of original samples that will be averaged for each
  28473. low-res sample)
  28474. @param formatManagerToUse the audio format manager that is used to open the file
  28475. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28476. thread and storage that is used to by the thumbnail, and the cache
  28477. object can be shared between multiple thumbnails
  28478. */
  28479. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  28480. AudioFormatManager& formatManagerToUse,
  28481. AudioThumbnailCache& cacheToUse);
  28482. /** Destructor. */
  28483. ~AudioThumbnail();
  28484. /** Specifies the file or stream that contains the audio file.
  28485. For a file, just call
  28486. @code
  28487. setSource (new FileInputSource (file))
  28488. @endcode
  28489. You can pass a zero in here to clear the thumbnail.
  28490. The source that is passed in will be deleted by this object when it is no
  28491. longer needed
  28492. */
  28493. void setSource (InputSource* const newSource);
  28494. /** Reloads the low res thumbnail data from an input stream.
  28495. The thumb will automatically attempt to reload itself from its
  28496. AudioThumbnailCache.
  28497. */
  28498. void loadFrom (InputStream& input);
  28499. /** Saves the low res thumbnail data to an output stream.
  28500. The thumb will automatically attempt to save itself to its
  28501. AudioThumbnailCache after it finishes scanning the wave file.
  28502. */
  28503. void saveTo (OutputStream& output) const;
  28504. /** Returns the number of channels in the file.
  28505. */
  28506. int getNumChannels() const throw();
  28507. /** Returns the length of the audio file, in seconds.
  28508. */
  28509. double getTotalLength() const throw();
  28510. /** Renders the waveform shape for a channel.
  28511. The waveform will be drawn within the specified rectangle, where startTime
  28512. and endTime specify the times within the audio file that should be positioned
  28513. at the left and right edges of the rectangle.
  28514. The waveform will be scaled vertically so that a full-volume sample will fill
  28515. the rectangle vertically, but you can also specify an extra vertical scale factor
  28516. with the verticalZoomFactor parameter.
  28517. */
  28518. void drawChannel (Graphics& g,
  28519. int x, int y, int w, int h,
  28520. double startTimeSeconds,
  28521. double endTimeSeconds,
  28522. int channelNum,
  28523. const float verticalZoomFactor);
  28524. /** Returns true if the low res preview is fully generated.
  28525. */
  28526. bool isFullyLoaded() const throw();
  28527. /** @internal */
  28528. bool useTimeSlice();
  28529. /** @internal */
  28530. void timerCallback();
  28531. juce_UseDebuggingNewOperator
  28532. private:
  28533. AudioFormatManager& formatManagerToUse;
  28534. AudioThumbnailCache& cache;
  28535. InputSource* source;
  28536. CriticalSection readerLock;
  28537. AudioFormatReader* reader;
  28538. MemoryBlock data, cachedLevels;
  28539. int orginalSamplesPerThumbnailSample;
  28540. int numChannelsCached, numSamplesCached;
  28541. double cachedStart, cachedTimePerPixel;
  28542. bool cacheNeedsRefilling;
  28543. void clear();
  28544. AudioFormatReader* createReader() const;
  28545. void generateSection (AudioFormatReader& reader,
  28546. int64 startSample,
  28547. int numSamples);
  28548. char* getChannelData (int channel) const;
  28549. void refillCache (const int numSamples,
  28550. double startTime,
  28551. const double timePerPixel);
  28552. friend class AudioThumbnailCache;
  28553. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  28554. bool initialiseFromAudioFile (AudioFormatReader& reader);
  28555. // returns true if more needs to be read
  28556. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  28557. };
  28558. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28559. /********* End of inlined file: juce_AudioThumbnail.h *********/
  28560. #endif
  28561. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28562. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  28563. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28564. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28565. struct ThumbnailCacheEntry;
  28566. /**
  28567. An instance of this class is used to manage multiple AudioThumbnail objects.
  28568. The cache runs a single background thread that is shared by all the thumbnails
  28569. that need it, and it maintains a set of low-res previews in memory, to avoid
  28570. having to re-scan audio files too often.
  28571. @see AudioThumbnail
  28572. */
  28573. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28574. {
  28575. public:
  28576. /** Creates a cache object.
  28577. The maxNumThumbsToStore parameter lets you specify how many previews should
  28578. be kept in memory at once.
  28579. */
  28580. AudioThumbnailCache (const int maxNumThumbsToStore);
  28581. /** Destructor. */
  28582. ~AudioThumbnailCache();
  28583. /** Clears out any stored thumbnails.
  28584. */
  28585. void clear();
  28586. /** Reloads the specified thumb if this cache contains the appropriate stored
  28587. data.
  28588. This is called automatically by the AudioThumbnail class, so you shouldn't
  28589. normally need to call it directly.
  28590. */
  28591. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  28592. /** Stores the cachable data from the specified thumb in this cache.
  28593. This is called automatically by the AudioThumbnail class, so you shouldn't
  28594. normally need to call it directly.
  28595. */
  28596. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  28597. juce_UseDebuggingNewOperator
  28598. private:
  28599. OwnedArray <ThumbnailCacheEntry> thumbs;
  28600. int maxNumThumbsToStore;
  28601. friend class AudioThumbnail;
  28602. void addThumbnail (AudioThumbnail* const thumb);
  28603. void removeThumbnail (AudioThumbnail* const thumb);
  28604. };
  28605. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28606. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  28607. #endif
  28608. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28609. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  28610. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28611. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28612. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28613. /**
  28614. Reads and writes the lossless-compression FLAC audio format.
  28615. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28616. and make sure your include search path and library search path are set up to find
  28617. the FLAC header files and static libraries.
  28618. @see AudioFormat
  28619. */
  28620. class JUCE_API FlacAudioFormat : public AudioFormat
  28621. {
  28622. public:
  28623. FlacAudioFormat();
  28624. ~FlacAudioFormat();
  28625. const Array <int> getPossibleSampleRates();
  28626. const Array <int> getPossibleBitDepths();
  28627. bool canDoStereo();
  28628. bool canDoMono();
  28629. bool isCompressed();
  28630. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28631. const bool deleteStreamIfOpeningFails);
  28632. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28633. double sampleRateToUse,
  28634. unsigned int numberOfChannels,
  28635. int bitsPerSample,
  28636. const StringPairArray& metadataValues,
  28637. int qualityOptionIndex);
  28638. juce_UseDebuggingNewOperator
  28639. };
  28640. #endif
  28641. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28642. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  28643. #endif
  28644. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28645. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  28646. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28647. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28648. /**
  28649. Reads and Writes WAV format audio files.
  28650. @see AudioFormat
  28651. */
  28652. class JUCE_API WavAudioFormat : public AudioFormat
  28653. {
  28654. public:
  28655. /** Creates a format object. */
  28656. WavAudioFormat();
  28657. /** Destructor. */
  28658. ~WavAudioFormat();
  28659. /** Metadata property name used by wav readers and writers for adding
  28660. a BWAV chunk to the file.
  28661. @see AudioFormatReader::metadataValues, createWriterFor
  28662. */
  28663. static const tchar* const bwavDescription;
  28664. /** Metadata property name used by wav readers and writers for adding
  28665. a BWAV chunk to the file.
  28666. @see AudioFormatReader::metadataValues, createWriterFor
  28667. */
  28668. static const tchar* const bwavOriginator;
  28669. /** Metadata property name used by wav readers and writers for adding
  28670. a BWAV chunk to the file.
  28671. @see AudioFormatReader::metadataValues, createWriterFor
  28672. */
  28673. static const tchar* const bwavOriginatorRef;
  28674. /** Metadata property name used by wav readers and writers for adding
  28675. a BWAV chunk to the file.
  28676. Date format is: yyyy-mm-dd
  28677. @see AudioFormatReader::metadataValues, createWriterFor
  28678. */
  28679. static const tchar* const bwavOriginationDate;
  28680. /** Metadata property name used by wav readers and writers for adding
  28681. a BWAV chunk to the file.
  28682. Time format is: hh-mm-ss
  28683. @see AudioFormatReader::metadataValues, createWriterFor
  28684. */
  28685. static const tchar* const bwavOriginationTime;
  28686. /** Metadata property name used by wav readers and writers for adding
  28687. a BWAV chunk to the file.
  28688. This is the number of samples from the start of an edit that the
  28689. file is supposed to begin at. Seems like an obvious mistake to
  28690. only allow a file to occur in an edit once, but that's the way
  28691. it is..
  28692. @see AudioFormatReader::metadataValues, createWriterFor
  28693. */
  28694. static const tchar* const bwavTimeReference;
  28695. /** Metadata property name used by wav readers and writers for adding
  28696. a BWAV chunk to the file.
  28697. This is a
  28698. @see AudioFormatReader::metadataValues, createWriterFor
  28699. */
  28700. static const tchar* const bwavCodingHistory;
  28701. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28702. This just makes it easier than using the property names directly, and it
  28703. fills out the time and date in the right format.
  28704. */
  28705. static const StringPairArray createBWAVMetadata (const String& description,
  28706. const String& originator,
  28707. const String& originatorRef,
  28708. const Time& dateAndTime,
  28709. const int64 timeReferenceSamples,
  28710. const String& codingHistory);
  28711. const Array <int> getPossibleSampleRates();
  28712. const Array <int> getPossibleBitDepths();
  28713. bool canDoStereo();
  28714. bool canDoMono();
  28715. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28716. const bool deleteStreamIfOpeningFails);
  28717. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28718. double sampleRateToUse,
  28719. unsigned int numberOfChannels,
  28720. int bitsPerSample,
  28721. const StringPairArray& metadataValues,
  28722. int qualityOptionIndex);
  28723. /** Utility function to replace the metadata in a wav file with a new set of values.
  28724. If possible, this cheats by overwriting just the metadata region of the file, rather
  28725. than by copying the whole file again.
  28726. */
  28727. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28728. juce_UseDebuggingNewOperator
  28729. };
  28730. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28731. /********* End of inlined file: juce_WavAudioFormat.h *********/
  28732. #endif
  28733. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28734. /********* Start of inlined file: juce_AudioCDReader.h *********/
  28735. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28736. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28737. #if JUCE_USE_CDREADER
  28738. #if JUCE_MAC
  28739. #endif
  28740. /**
  28741. A type of AudioFormatReader that reads from an audio CD.
  28742. One of these can be used to read a CD as if it's one big audio stream. Use the
  28743. getPositionOfTrackStart() method to find where the individual tracks are
  28744. within the stream.
  28745. @see AudioFormatReader
  28746. */
  28747. class JUCE_API AudioCDReader : public AudioFormatReader
  28748. {
  28749. public:
  28750. /** Returns a list of names of Audio CDs currently available for reading.
  28751. If there's a CD drive but no CD in it, this might return an empty list, or
  28752. possibly a device that can be opened but which has no tracks, depending
  28753. on the platform.
  28754. @see createReaderForCD
  28755. */
  28756. static const StringArray getAvailableCDNames();
  28757. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28758. @param index the index of one of the available CDs - use getAvailableCDNames()
  28759. to find out how many there are.
  28760. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28761. caller will be responsible for deleting the object returned.
  28762. */
  28763. static AudioCDReader* createReaderForCD (const int index);
  28764. /** Destructor. */
  28765. ~AudioCDReader();
  28766. /** Implementation of the AudioFormatReader method. */
  28767. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28768. int64 startSampleInFile, int numSamples);
  28769. /** Checks whether the CD has been removed from the drive.
  28770. */
  28771. bool isCDStillPresent() const;
  28772. /** Returns the total number of tracks (audio + data).
  28773. */
  28774. int getNumTracks() const;
  28775. /** Finds the sample offset of the start of a track.
  28776. @param trackNum the track number, where 0 is the first track.
  28777. */
  28778. int getPositionOfTrackStart (int trackNum) const;
  28779. /** Returns true if a given track is an audio track.
  28780. @param trackNum the track number, where 0 is the first track.
  28781. */
  28782. bool isTrackAudio (int trackNum) const;
  28783. /** Refreshes the object's table of contents.
  28784. If the disc has been ejected and a different one put in since this
  28785. object was created, this will cause it to update its idea of how many tracks
  28786. there are, etc.
  28787. */
  28788. void refreshTrackLengths();
  28789. /** Enables scanning for indexes within tracks.
  28790. @see getLastIndex
  28791. */
  28792. void enableIndexScanning (bool enabled);
  28793. /** Returns the index number found during the last read() call.
  28794. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28795. Then when the read() method is called, if it comes across an index within that
  28796. block, the index number is stored and returned by this method.
  28797. Some devices might not support indexes, of course.
  28798. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28799. @see enableIndexScanning
  28800. */
  28801. int getLastIndex() const;
  28802. /** Scans a track to find the position of any indexes within it.
  28803. @param trackNumber the track to look in, where 0 is the first track on the disc
  28804. @returns an array of sample positions of any index points found (not including
  28805. the index that marks the start of the track)
  28806. */
  28807. const Array <int> findIndexesInTrack (const int trackNumber);
  28808. /** Returns the CDDB id number for the CD.
  28809. It's not a great way of identifying a disc, but it's traditional.
  28810. */
  28811. int getCDDBId();
  28812. /** Tries to eject the disk.
  28813. Of course this might not be possible, if some other process is using it.
  28814. */
  28815. void ejectDisk();
  28816. juce_UseDebuggingNewOperator
  28817. private:
  28818. #if JUCE_MAC
  28819. File volumeDir;
  28820. OwnedArray<File> tracks;
  28821. Array <int> trackStartSamples;
  28822. int currentReaderTrack;
  28823. AudioFormatReader* reader;
  28824. AudioCDReader (const File& volume);
  28825. public:
  28826. static int compareElements (const File* const, const File* const) throw();
  28827. private:
  28828. #elif JUCE_WINDOWS
  28829. int numTracks;
  28830. int trackStarts[100];
  28831. bool audioTracks [100];
  28832. void* handle;
  28833. bool indexingEnabled;
  28834. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28835. MemoryBlock buffer;
  28836. AudioCDReader (void* handle);
  28837. int getIndexAt (int samplePos);
  28838. #elif JUCE_LINUX
  28839. AudioCDReader();
  28840. #endif
  28841. AudioCDReader (const AudioCDReader&);
  28842. const AudioCDReader& operator= (const AudioCDReader&);
  28843. };
  28844. #endif
  28845. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28846. /********* End of inlined file: juce_AudioCDReader.h *********/
  28847. #endif
  28848. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28849. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  28850. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28851. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28852. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28853. /**
  28854. Reads and writes the Ogg-Vorbis audio format.
  28855. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28856. and make sure your include search path and library search path are set up to find
  28857. the Vorbis and Ogg header files and static libraries.
  28858. @see AudioFormat,
  28859. */
  28860. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28861. {
  28862. public:
  28863. OggVorbisAudioFormat();
  28864. ~OggVorbisAudioFormat();
  28865. const Array <int> getPossibleSampleRates();
  28866. const Array <int> getPossibleBitDepths();
  28867. bool canDoStereo();
  28868. bool canDoMono();
  28869. bool isCompressed();
  28870. const StringArray getQualityOptions();
  28871. /** Tries to estimate the quality level of an ogg file based on its size.
  28872. If it can't read the file for some reason, this will just return 1 (medium quality),
  28873. otherwise it will return the approximate quality setting that would have been used
  28874. to create the file.
  28875. @see getQualityOptions
  28876. */
  28877. int estimateOggFileQuality (const File& source);
  28878. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28879. const bool deleteStreamIfOpeningFails);
  28880. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28881. double sampleRateToUse,
  28882. unsigned int numberOfChannels,
  28883. int bitsPerSample,
  28884. const StringPairArray& metadataValues,
  28885. int qualityOptionIndex);
  28886. juce_UseDebuggingNewOperator
  28887. };
  28888. #endif
  28889. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28890. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  28891. #endif
  28892. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28893. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  28894. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28895. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28896. #if JUCE_QUICKTIME
  28897. /**
  28898. Uses QuickTime to read the audio track a movie or media file.
  28899. As well as QuickTime movies, this should also manage to open other audio
  28900. files that quicktime can understand, like mp3, m4a, etc.
  28901. @see AudioFormat
  28902. */
  28903. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28904. {
  28905. public:
  28906. /** Creates a format object. */
  28907. QuickTimeAudioFormat();
  28908. /** Destructor. */
  28909. ~QuickTimeAudioFormat();
  28910. const Array <int> getPossibleSampleRates();
  28911. const Array <int> getPossibleBitDepths();
  28912. bool canDoStereo();
  28913. bool canDoMono();
  28914. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28915. const bool deleteStreamIfOpeningFails);
  28916. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28917. double sampleRateToUse,
  28918. unsigned int numberOfChannels,
  28919. int bitsPerSample,
  28920. const StringPairArray& metadataValues,
  28921. int qualityOptionIndex);
  28922. juce_UseDebuggingNewOperator
  28923. };
  28924. #endif
  28925. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28926. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  28927. #endif
  28928. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28929. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  28930. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28931. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28932. #if JUCE_USE_CDBURNER
  28933. /**
  28934. */
  28935. class AudioCDBurner
  28936. {
  28937. public:
  28938. /** Returns a list of available optical drives.
  28939. Use openDevice() to open one of the items from this list.
  28940. */
  28941. static const StringArray findAvailableDevices();
  28942. /** Tries to open one of the optical drives.
  28943. The deviceIndex is an index into the array returned by findAvailableDevices().
  28944. */
  28945. static AudioCDBurner* openDevice (const int deviceIndex);
  28946. /** Destructor. */
  28947. ~AudioCDBurner();
  28948. /** Returns true if there's a writable disk in the drive.
  28949. */
  28950. bool isDiskPresent() const;
  28951. /** Returns the number of free blocks on the disk.
  28952. There are 75 blocks per second, at 44100Hz.
  28953. */
  28954. int getNumAvailableAudioBlocks() const;
  28955. /** Adds a track to be written.
  28956. The source passed-in here will be kept by this object, and it will
  28957. be used and deleted at some point in the future, either during the
  28958. burn() method or when this AudioCDBurner object is deleted. Your caller
  28959. method shouldn't keep a reference to it or use it again after passing
  28960. it in here.
  28961. */
  28962. bool addAudioTrack (AudioSource* source, int numSamples);
  28963. /**
  28964. Return true to cancel the current burn operation
  28965. */
  28966. class BurnProgressListener
  28967. {
  28968. public:
  28969. BurnProgressListener() throw() {}
  28970. virtual ~BurnProgressListener() {}
  28971. /** Called at intervals to report on the progress of the AudioCDBurner.
  28972. To cancel the burn, return true from this.
  28973. */
  28974. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28975. };
  28976. const String burn (BurnProgressListener* listener,
  28977. const bool ejectDiscAfterwards,
  28978. const bool peformFakeBurnForTesting);
  28979. juce_UseDebuggingNewOperator
  28980. private:
  28981. AudioCDBurner (const int deviceIndex);
  28982. void* internal;
  28983. };
  28984. #endif
  28985. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28986. /********* End of inlined file: juce_AudioCDBurner.h *********/
  28987. #endif
  28988. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28989. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  28990. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28991. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28992. /********* Start of inlined file: juce_ActionListenerList.h *********/
  28993. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28994. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28995. /**
  28996. A set of ActionListeners.
  28997. Listeners can be added and removed from the list, and messages can be
  28998. broadcast to all the listeners.
  28999. @see ActionListener, ActionBroadcaster
  29000. */
  29001. class JUCE_API ActionListenerList : public MessageListener
  29002. {
  29003. public:
  29004. /** Creates an empty list. */
  29005. ActionListenerList() throw();
  29006. /** Destructor. */
  29007. ~ActionListenerList() throw();
  29008. /** Adds a listener to the list.
  29009. (Trying to add a listener that's already on the list will have no effect).
  29010. */
  29011. void addActionListener (ActionListener* const listener) throw();
  29012. /** Removes a listener from the list.
  29013. If the listener isn't on the list, this won't have any effect.
  29014. */
  29015. void removeActionListener (ActionListener* const listener) throw();
  29016. /** Removes all listeners from the list. */
  29017. void removeAllActionListeners() throw();
  29018. /** Broadcasts a message to all the registered listeners.
  29019. This sends the message asynchronously.
  29020. If a listener is on the list when this method is called but is removed from
  29021. the list before the message arrives, it won't receive the message. Similarly
  29022. listeners that are added to the list after the message is sent but before it
  29023. arrives won't get the message either.
  29024. */
  29025. void sendActionMessage (const String& message) const;
  29026. /** @internal */
  29027. void handleMessage (const Message&);
  29028. juce_UseDebuggingNewOperator
  29029. private:
  29030. SortedSet <void*> actionListeners_;
  29031. CriticalSection actionListenerLock_;
  29032. ActionListenerList (const ActionListenerList&);
  29033. const ActionListenerList& operator= (const ActionListenerList&);
  29034. };
  29035. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29036. /********* End of inlined file: juce_ActionListenerList.h *********/
  29037. /** Manages a list of ActionListeners, and can send them messages.
  29038. To quickly add methods to your class that can add/remove action
  29039. listeners and broadcast to them, you can derive from this.
  29040. @see ActionListenerList, ActionListener
  29041. */
  29042. class JUCE_API ActionBroadcaster
  29043. {
  29044. public:
  29045. /** Creates an ActionBroadcaster. */
  29046. ActionBroadcaster() throw();
  29047. /** Destructor. */
  29048. virtual ~ActionBroadcaster();
  29049. /** Adds a listener to the list.
  29050. (Trying to add a listener that's already on the list will have no effect).
  29051. */
  29052. void addActionListener (ActionListener* const listener);
  29053. /** Removes a listener from the list.
  29054. If the listener isn't on the list, this won't have any effect.
  29055. */
  29056. void removeActionListener (ActionListener* const listener);
  29057. /** Removes all listeners from the list. */
  29058. void removeAllActionListeners();
  29059. /** Broadcasts a message to all the registered listeners.
  29060. @see ActionListenerList::sendActionMessage
  29061. */
  29062. void sendActionMessage (const String& message) const;
  29063. private:
  29064. ActionListenerList actionListenerList;
  29065. ActionBroadcaster (const ActionBroadcaster&);
  29066. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  29067. };
  29068. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29069. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  29070. #endif
  29071. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  29072. #endif
  29073. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29074. #endif
  29075. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  29076. #endif
  29077. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29078. /********* Start of inlined file: juce_CallbackMessage.h *********/
  29079. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29080. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29081. /**
  29082. A message that calls a custom function when it gets delivered.
  29083. You can use this class to fire off actions that you want to be performed later
  29084. on the message thread.
  29085. Unlike other Message objects, these don't get sent to a MessageListener, you
  29086. just call the post() method to send them, and when they arrive, your
  29087. messageCallback() method will automatically be invoked.
  29088. @see MessageListener, MessageManager, ActionListener, ChangeListener
  29089. */
  29090. class JUCE_API CallbackMessage : public Message
  29091. {
  29092. public:
  29093. CallbackMessage() throw();
  29094. /** Destructor. */
  29095. ~CallbackMessage() throw();
  29096. /** Called when the message is delivered.
  29097. You should implement this method and make it do whatever action you want
  29098. to perform.
  29099. Note that like all other messages, this object will be deleted immediately
  29100. after this method has been invoked.
  29101. */
  29102. virtual void messageCallback() = 0;
  29103. /** Instead of sending this message to a MessageListener, just call this method
  29104. to post it to the event queue.
  29105. After you've called this, this object will belong to the MessageManager,
  29106. which will delete it later. So make sure you don't delete the object yourself,
  29107. call post() more than once, or call post() on a stack-based obect!
  29108. */
  29109. void post();
  29110. juce_UseDebuggingNewOperator
  29111. private:
  29112. CallbackMessage (const CallbackMessage&);
  29113. const CallbackMessage& operator= (const CallbackMessage&);
  29114. };
  29115. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29116. /********* End of inlined file: juce_CallbackMessage.h *********/
  29117. #endif
  29118. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  29119. #endif
  29120. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  29121. #endif
  29122. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  29123. #endif
  29124. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29125. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  29126. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29127. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29128. class InterprocessConnectionServer;
  29129. /**
  29130. Manages a simple two-way messaging connection to another process, using either
  29131. a socket or a named pipe as the transport medium.
  29132. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  29133. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  29134. and incoming messages will result in a callback via the messageReceived()
  29135. method.
  29136. To open a pipe and wait for another client to connect to it, use the createPipe()
  29137. method.
  29138. To act as a socket server and create connections for one or more client, see the
  29139. InterprocessConnectionServer class.
  29140. @see InterprocessConnectionServer, Socket, NamedPipe
  29141. */
  29142. class JUCE_API InterprocessConnection : public Thread,
  29143. private MessageListener
  29144. {
  29145. public:
  29146. /** Creates a connection.
  29147. Connections are created manually, connecting them with the connectToSocket()
  29148. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  29149. when a client wants to connect.
  29150. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  29151. connectionLost() and messageReceived() methods will
  29152. always be made using the message thread; if false,
  29153. these will be called immediately on the connection's
  29154. own thread.
  29155. @param magicMessageHeaderNumber a magic number to use in the header to check the
  29156. validity of the data blocks being sent and received. This
  29157. can be any number, but the sender and receiver must obviously
  29158. use matching values or they won't recognise each other.
  29159. */
  29160. InterprocessConnection (const bool callbacksOnMessageThread = true,
  29161. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  29162. /** Destructor. */
  29163. ~InterprocessConnection();
  29164. /** Tries to connect this object to a socket.
  29165. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  29166. object waiting to receive client connections on this port number.
  29167. @param hostName the host computer, either a network address or name
  29168. @param portNumber the socket port number to try to connect to
  29169. @param timeOutMillisecs how long to keep trying before giving up
  29170. @returns true if the connection is established successfully
  29171. @see Socket
  29172. */
  29173. bool connectToSocket (const String& hostName,
  29174. const int portNumber,
  29175. const int timeOutMillisecs);
  29176. /** Tries to connect the object to an existing named pipe.
  29177. For this to work, another process on the same computer must already have opened
  29178. an InterprocessConnection object and used createPipe() to create a pipe for this
  29179. to connect to.
  29180. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  29181. @returns true if it connects successfully.
  29182. @see createPipe, NamedPipe
  29183. */
  29184. bool connectToPipe (const String& pipeName,
  29185. const int pipeReceiveMessageTimeoutMs = -1);
  29186. /** Tries to create a new pipe for other processes to connect to.
  29187. This creates a pipe with the given name, so that other processes can use
  29188. connectToPipe() to connect to the other end.
  29189. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  29190. If another process is already using this pipe, this will fail and return false.
  29191. */
  29192. bool createPipe (const String& pipeName,
  29193. const int pipeReceiveMessageTimeoutMs = -1);
  29194. /** Disconnects and closes any currently-open sockets or pipes. */
  29195. void disconnect();
  29196. /** True if a socket or pipe is currently active. */
  29197. bool isConnected() const;
  29198. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  29199. StreamingSocket* getSocket() const throw() { return socket; }
  29200. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  29201. NamedPipe* getPipe() const throw() { return pipe; }
  29202. /** Returns the name of the machine at the other end of this connection.
  29203. This will return an empty string if the other machine isn't known for
  29204. some reason.
  29205. */
  29206. const String getConnectedHostName() const;
  29207. /** Tries to send a message to the other end of this connection.
  29208. This will fail if it's not connected, or if there's some kind of write error. If
  29209. it succeeds, the connection object at the other end will receive the message by
  29210. a callback to its messageReceived() method.
  29211. @see messageReceived
  29212. */
  29213. bool sendMessage (const MemoryBlock& message);
  29214. /** Called when the connection is first connected.
  29215. If the connection was created with the callbacksOnMessageThread flag set, then
  29216. this will be called on the message thread; otherwise it will be called on a server
  29217. thread.
  29218. */
  29219. virtual void connectionMade() = 0;
  29220. /** Called when the connection is broken.
  29221. If the connection was created with the callbacksOnMessageThread flag set, then
  29222. this will be called on the message thread; otherwise it will be called on a server
  29223. thread.
  29224. */
  29225. virtual void connectionLost() = 0;
  29226. /** Called when a message arrives.
  29227. When the object at the other end of this connection sends us a message with sendMessage(),
  29228. this callback is used to deliver it to us.
  29229. If the connection was created with the callbacksOnMessageThread flag set, then
  29230. this will be called on the message thread; otherwise it will be called on a server
  29231. thread.
  29232. @see sendMessage
  29233. */
  29234. virtual void messageReceived (const MemoryBlock& message) = 0;
  29235. juce_UseDebuggingNewOperator
  29236. private:
  29237. CriticalSection pipeAndSocketLock;
  29238. StreamingSocket* socket;
  29239. NamedPipe* pipe;
  29240. bool callbackConnectionState;
  29241. const bool useMessageThread;
  29242. const uint32 magicMessageHeader;
  29243. int pipeReceiveMessageTimeout;
  29244. friend class InterprocessConnectionServer;
  29245. void initialiseWithSocket (StreamingSocket* const socket_);
  29246. void initialiseWithPipe (NamedPipe* const pipe_);
  29247. void handleMessage (const Message& message);
  29248. void connectionMadeInt();
  29249. void connectionLostInt();
  29250. void deliverDataInt (const MemoryBlock& data);
  29251. bool readNextMessageInt();
  29252. void run();
  29253. InterprocessConnection (const InterprocessConnection&);
  29254. const InterprocessConnection& operator= (const InterprocessConnection&);
  29255. };
  29256. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29257. /********* End of inlined file: juce_InterprocessConnection.h *********/
  29258. #endif
  29259. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29260. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  29261. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29262. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29263. /**
  29264. An object that waits for client sockets to connect to a port on this host, and
  29265. creates InterprocessConnection objects for each one.
  29266. To use this, create a class derived from it which implements the createConnectionObject()
  29267. method, so that it creates suitable connection objects for each client that tries
  29268. to connect.
  29269. @see InterprocessConnection
  29270. */
  29271. class JUCE_API InterprocessConnectionServer : private Thread
  29272. {
  29273. public:
  29274. /** Creates an uninitialised server object.
  29275. */
  29276. InterprocessConnectionServer();
  29277. /** Destructor. */
  29278. ~InterprocessConnectionServer();
  29279. /** Starts an internal thread which listens on the given port number.
  29280. While this is running, in another process tries to connect with the
  29281. InterprocessConnection::connectToSocket() method, this object will call
  29282. createConnectionObject() to create a connection to that client.
  29283. Use stop() to stop the thread running.
  29284. @see createConnectionObject, stop
  29285. */
  29286. bool beginWaitingForSocket (const int portNumber);
  29287. /** Terminates the listener thread, if it's active.
  29288. @see beginWaitingForSocket
  29289. */
  29290. void stop();
  29291. protected:
  29292. /** Creates a suitable connection object for a client process that wants to
  29293. connect to this one.
  29294. This will be called by the listener thread when a client process tries
  29295. to connect, and must return a new InterprocessConnection object that will
  29296. then run as this end of the connection.
  29297. @see InterprocessConnection
  29298. */
  29299. virtual InterprocessConnection* createConnectionObject() = 0;
  29300. public:
  29301. juce_UseDebuggingNewOperator
  29302. private:
  29303. StreamingSocket* volatile socket;
  29304. void run();
  29305. InterprocessConnectionServer (const InterprocessConnectionServer&);
  29306. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  29307. };
  29308. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29309. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  29310. #endif
  29311. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  29312. #endif
  29313. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  29314. #endif
  29315. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29316. /********* Start of inlined file: juce_MessageManager.h *********/
  29317. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29318. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29319. class Component;
  29320. class MessageManagerLock;
  29321. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  29322. */
  29323. typedef void* (MessageCallbackFunction) (void* userData);
  29324. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  29325. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  29326. */
  29327. class JUCE_API MessageManager
  29328. {
  29329. public:
  29330. /** Returns the global instance of the MessageManager. */
  29331. static MessageManager* getInstance() throw();
  29332. /** Runs the event dispatch loop until a stop message is posted.
  29333. This method is only intended to be run by the application's startup routine,
  29334. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  29335. @see stopDispatchLoop
  29336. */
  29337. void runDispatchLoop();
  29338. /** Sends a signal that the dispatch loop should terminate.
  29339. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  29340. will be interrupted and will return.
  29341. @see runDispatchLoop
  29342. */
  29343. void stopDispatchLoop();
  29344. /** Returns true if the stopDispatchLoop() method has been called.
  29345. */
  29346. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  29347. /** Synchronously dispatches messages until a given time has elapsed.
  29348. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  29349. otherwise returns true.
  29350. */
  29351. bool runDispatchLoopUntil (int millisecondsToRunFor);
  29352. /** Calls a function using the message-thread.
  29353. This can be used by any thread to cause this function to be called-back
  29354. by the message thread. If it's the message-thread that's calling this method,
  29355. then the function will just be called; if another thread is calling, a message
  29356. will be posted to the queue, and this method will block until that message
  29357. is delivered, the function is called, and the result is returned.
  29358. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  29359. thread has a critical section locked, which an unrelated message callback then tries to lock
  29360. before the message thread gets round to processing this callback.
  29361. @param callback the function to call - its signature must be @code
  29362. void* myCallbackFunction (void*) @endcode
  29363. @param userData a user-defined pointer that will be passed to the function that gets called
  29364. @returns the value that the callback function returns.
  29365. @see MessageManagerLock
  29366. */
  29367. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  29368. void* userData);
  29369. /** Returns true if the caller-thread is the message thread. */
  29370. bool isThisTheMessageThread() const throw();
  29371. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  29372. (Best to ignore this method unless you really know what you're doing..)
  29373. @see getCurrentMessageThread
  29374. */
  29375. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  29376. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  29377. (Best to ignore this method unless you really know what you're doing..)
  29378. @see setCurrentMessageThread
  29379. */
  29380. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  29381. /** Returns true if the caller thread has currenltly got the message manager locked.
  29382. see the MessageManagerLock class for more info about this.
  29383. This will be true if the caller is the message thread, because that automatically
  29384. gains a lock while a message is being dispatched.
  29385. */
  29386. bool currentThreadHasLockedMessageManager() const throw();
  29387. /** Sends a message to all other JUCE applications that are running.
  29388. @param messageText the string that will be passed to the actionListenerCallback()
  29389. method of the broadcast listeners in the other app.
  29390. @see registerBroadcastListener, ActionListener
  29391. */
  29392. static void broadcastMessage (const String& messageText) throw();
  29393. /** Registers a listener to get told about broadcast messages.
  29394. The actionListenerCallback() callback's string parameter
  29395. is the message passed into broadcastMessage().
  29396. @see broadcastMessage
  29397. */
  29398. void registerBroadcastListener (ActionListener* listener) throw();
  29399. /** Deregisters a broadcast listener. */
  29400. void deregisterBroadcastListener (ActionListener* listener) throw();
  29401. /** @internal */
  29402. void deliverMessage (void*);
  29403. /** @internal */
  29404. void deliverBroadcastMessage (const String&);
  29405. /** @internal */
  29406. ~MessageManager() throw();
  29407. juce_UseDebuggingNewOperator
  29408. private:
  29409. MessageManager() throw();
  29410. friend class MessageListener;
  29411. friend class ChangeBroadcaster;
  29412. friend class ActionBroadcaster;
  29413. friend class CallbackMessage;
  29414. static MessageManager* instance;
  29415. SortedSet<const MessageListener*> messageListeners;
  29416. ActionListenerList* broadcastListeners;
  29417. friend class JUCEApplication;
  29418. bool quitMessagePosted, quitMessageReceived;
  29419. Thread::ThreadID messageThreadId;
  29420. VoidArray modalComponents;
  29421. static void* exitModalLoopCallback (void*);
  29422. void postMessageToQueue (Message* const message);
  29423. void postCallbackMessage (Message* const message);
  29424. static void doPlatformSpecificInitialisation();
  29425. static void doPlatformSpecificShutdown();
  29426. friend class MessageManagerLock;
  29427. Thread::ThreadID volatile threadWithLock;
  29428. CriticalSection lockingLock;
  29429. MessageManager (const MessageManager&);
  29430. const MessageManager& operator= (const MessageManager&);
  29431. };
  29432. /** Used to make sure that the calling thread has exclusive access to the message loop.
  29433. Because it's not thread-safe to call any of the Component or other UI classes
  29434. from threads other than the message thread, one of these objects can be used to
  29435. lock the message loop and allow this to be done. The message thread will be
  29436. suspended for the lifetime of the MessageManagerLock object, so create one on
  29437. the stack like this: @code
  29438. void MyThread::run()
  29439. {
  29440. someData = 1234;
  29441. const MessageManagerLock mmLock;
  29442. // the event loop will now be locked so it's safe to make a few calls..
  29443. myComponent->setBounds (newBounds);
  29444. myComponent->repaint();
  29445. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  29446. }
  29447. @endcode
  29448. Obviously be careful not to create one of these and leave it lying around, or
  29449. your app will grind to a halt!
  29450. Another caveat is that using this in conjunction with other CriticalSections
  29451. can create lots of interesting ways of producing a deadlock! In particular, if
  29452. your message thread calls stopThread() for a thread that uses these locks,
  29453. you'll get an (occasional) deadlock..
  29454. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  29455. */
  29456. class JUCE_API MessageManagerLock
  29457. {
  29458. public:
  29459. /** Tries to acquire a lock on the message manager.
  29460. The constructor attempts to gain a lock on the message loop, and the lock will be
  29461. kept for the lifetime of this object.
  29462. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  29463. this method will keep checking whether the thread has been given the
  29464. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  29465. without gaining the lock. If you pass a thread, you must check whether the lock was
  29466. successful by calling lockWasGained(). If this is false, your thread is being told to
  29467. die, so you should take evasive action.
  29468. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  29469. careful when doing this, because it's very easy to deadlock if your message thread
  29470. attempts to call stopThread() on a thread just as that thread attempts to get the
  29471. message lock.
  29472. If the calling thread already has the lock, nothing will be done, so it's safe and
  29473. quick to use these locks recursively.
  29474. E.g.
  29475. @code
  29476. void run()
  29477. {
  29478. ...
  29479. while (! threadShouldExit())
  29480. {
  29481. MessageManagerLock mml (Thread::getCurrentThread());
  29482. if (! mml.lockWasGained())
  29483. return; // another thread is trying to kill us!
  29484. ..do some locked stuff here..
  29485. }
  29486. ..and now the MM is now unlocked..
  29487. }
  29488. @endcode
  29489. */
  29490. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  29491. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  29492. instead of a thread.
  29493. See the MessageManagerLock (Thread*) constructor for details on how this works.
  29494. */
  29495. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  29496. /** Releases the current thread's lock on the message manager.
  29497. Make sure this object is created and deleted by the same thread,
  29498. otherwise there are no guarantees what will happen!
  29499. */
  29500. ~MessageManagerLock() throw();
  29501. /** Returns true if the lock was successfully acquired.
  29502. (See the constructor that takes a Thread for more info).
  29503. */
  29504. bool lockWasGained() const throw() { return locked; }
  29505. private:
  29506. bool locked, needsUnlocking;
  29507. void* sharedEvents;
  29508. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  29509. MessageManagerLock (const MessageManagerLock&);
  29510. const MessageManagerLock& operator= (const MessageManagerLock&);
  29511. };
  29512. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29513. /********* End of inlined file: juce_MessageManager.h *********/
  29514. #endif
  29515. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  29516. /********* Start of inlined file: juce_MultiTimer.h *********/
  29517. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  29518. #define __JUCE_MULTITIMER_JUCEHEADER__
  29519. /**
  29520. A type of timer class that can run multiple timers with different frequencies,
  29521. all of which share a single callback.
  29522. This class is very similar to the Timer class, but allows you run multiple
  29523. separate timers, where each one has a unique ID number. The methods in this
  29524. class are exactly equivalent to those in Timer, but with the addition of
  29525. this ID number.
  29526. To use it, you need to create a subclass of MultiTimer, implementing the
  29527. timerCallback() method. Then you can start timers with startTimer(), and
  29528. each time the callback is triggered, it passes in the ID of the timer that
  29529. caused it.
  29530. @see Timer
  29531. */
  29532. class JUCE_API MultiTimer
  29533. {
  29534. protected:
  29535. /** Creates a MultiTimer.
  29536. When created, no timers are running, so use startTimer() to start things off.
  29537. */
  29538. MultiTimer() throw();
  29539. /** Creates a copy of another timer.
  29540. Note that this timer will not contain any running timers, even if the one you're
  29541. copying from was running.
  29542. */
  29543. MultiTimer (const MultiTimer& other) throw();
  29544. public:
  29545. /** Destructor. */
  29546. virtual ~MultiTimer();
  29547. /** The user-defined callback routine that actually gets called by each of the
  29548. timers that are running.
  29549. It's perfectly ok to call startTimer() or stopTimer() from within this
  29550. callback to change the subsequent intervals.
  29551. */
  29552. virtual void timerCallback (const int timerId) = 0;
  29553. /** Starts a timer and sets the length of interval required.
  29554. If the timer is already started, this will reset it, so the
  29555. time between calling this method and the next timer callback
  29556. will not be less than the interval length passed in.
  29557. @param timerId a unique Id number that identifies the timer to
  29558. start. This is the id that will be passed back
  29559. to the timerCallback() method when this timer is
  29560. triggered
  29561. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  29562. rounded up to 1)
  29563. */
  29564. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  29565. /** Stops a timer.
  29566. If a timer has been started with the given ID number, it will be cancelled.
  29567. No more callbacks will be made for the specified timer after this method returns.
  29568. If this is called from a different thread, any callbacks that may
  29569. be currently executing may be allowed to finish before the method
  29570. returns.
  29571. */
  29572. void stopTimer (const int timerId) throw();
  29573. /** Checks whether a timer has been started for a specified ID.
  29574. @returns true if a timer with the given ID is running.
  29575. */
  29576. bool isTimerRunning (const int timerId) const throw();
  29577. /** Returns the interval for a specified timer ID.
  29578. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  29579. is running for the ID number specified.
  29580. */
  29581. int getTimerInterval (const int timerId) const throw();
  29582. private:
  29583. CriticalSection timerListLock;
  29584. VoidArray timers;
  29585. const MultiTimer& operator= (const MultiTimer&);
  29586. };
  29587. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  29588. /********* End of inlined file: juce_MultiTimer.h *********/
  29589. #endif
  29590. #ifndef __JUCE_TIMER_JUCEHEADER__
  29591. #endif
  29592. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  29593. #endif
  29594. #ifndef __JUCE_COLOUR_JUCEHEADER__
  29595. #endif
  29596. #ifndef __JUCE_COLOURS_JUCEHEADER__
  29597. #endif
  29598. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  29599. #endif
  29600. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29601. #endif
  29602. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29603. /********* Start of inlined file: juce_TextLayout.h *********/
  29604. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29605. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  29606. class Graphics;
  29607. /**
  29608. A laid-out arrangement of text.
  29609. You can add text in different fonts to a TextLayout object, then call its
  29610. layout() method to word-wrap it into lines. The layout can then be drawn
  29611. using a graphics context.
  29612. It's handy if you've got a message to display, because you can format it,
  29613. measure the extent of the layout, and then create a suitably-sized window
  29614. to show it in.
  29615. @see Font, Graphics::drawFittedText, GlyphArrangement
  29616. */
  29617. class JUCE_API TextLayout
  29618. {
  29619. public:
  29620. /** Creates an empty text layout.
  29621. Text can then be appended using the appendText() method.
  29622. */
  29623. TextLayout() throw();
  29624. /** Creates a copy of another layout object. */
  29625. TextLayout (const TextLayout& other) throw();
  29626. /** Creates a text layout from an initial string and font. */
  29627. TextLayout (const String& text, const Font& font) throw();
  29628. /** Destructor. */
  29629. ~TextLayout() throw();
  29630. /** Copies another layout onto this one. */
  29631. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  29632. /** Clears the layout, removing all its text. */
  29633. void clear() throw();
  29634. /** Adds a string to the end of the arrangement.
  29635. The string will be broken onto new lines wherever it contains
  29636. carriage-returns or linefeeds. After adding it, you can call layout()
  29637. to wrap long lines into a paragraph and justify it.
  29638. */
  29639. void appendText (const String& textToAppend,
  29640. const Font& fontToUse) throw();
  29641. /** Replaces all the text with a new string.
  29642. This is equivalent to calling clear() followed by appendText().
  29643. */
  29644. void setText (const String& newText,
  29645. const Font& fontToUse) throw();
  29646. /** Breaks the text up to form a paragraph with the given width.
  29647. @param maximumWidth any text wider than this will be split
  29648. across multiple lines
  29649. @param justification how the lines are to be laid-out horizontally
  29650. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29651. width that keeps all the lines of text at a
  29652. similar length - this is good when you're displaying
  29653. a short message and don't want it to get split
  29654. onto two lines with only a couple of words on
  29655. the second line, which looks untidy.
  29656. */
  29657. void layout (int maximumWidth,
  29658. const Justification& justification,
  29659. const bool attemptToBalanceLineLengths) throw();
  29660. /** Returns the overall width of the entire text layout. */
  29661. int getWidth() const throw();
  29662. /** Returns the overall height of the entire text layout. */
  29663. int getHeight() const throw();
  29664. /** Returns the total number of lines of text. */
  29665. int getNumLines() const throw() { return totalLines; }
  29666. /** Returns the width of a particular line of text.
  29667. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29668. */
  29669. int getLineWidth (const int lineNumber) const throw();
  29670. /** Renders the text at a specified position using a graphics context.
  29671. */
  29672. void draw (Graphics& g,
  29673. const int topLeftX,
  29674. const int topLeftY) const throw();
  29675. /** Renders the text within a specified rectangle using a graphics context.
  29676. The justification flags dictate how the block of text should be positioned
  29677. within the rectangle.
  29678. */
  29679. void drawWithin (Graphics& g,
  29680. int x, int y, int w, int h,
  29681. const Justification& layoutFlags) const throw();
  29682. juce_UseDebuggingNewOperator
  29683. private:
  29684. VoidArray tokens;
  29685. int totalLines;
  29686. };
  29687. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29688. /********* End of inlined file: juce_TextLayout.h *********/
  29689. #endif
  29690. #ifndef __JUCE_FONT_JUCEHEADER__
  29691. #endif
  29692. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29693. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  29694. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29695. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29696. /**
  29697. A glyph from a particular font, with a particular size, style,
  29698. typeface and position.
  29699. @see GlyphArrangement, Font
  29700. */
  29701. class JUCE_API PositionedGlyph
  29702. {
  29703. public:
  29704. /** Returns the character the glyph represents. */
  29705. juce_wchar getCharacter() const throw() { return character; }
  29706. /** Checks whether the glyph is actually empty. */
  29707. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  29708. /** Returns the position of the glyph's left-hand edge. */
  29709. float getLeft() const throw() { return x; }
  29710. /** Returns the position of the glyph's right-hand edge. */
  29711. float getRight() const throw() { return x + w; }
  29712. /** Returns the y position of the glyph's baseline. */
  29713. float getBaselineY() const throw() { return y; }
  29714. /** Returns the y position of the top of the glyph. */
  29715. float getTop() const throw() { return y - font.getAscent(); }
  29716. /** Returns the y position of the bottom of the glyph. */
  29717. float getBottom() const throw() { return y + font.getDescent(); }
  29718. /** Shifts the glyph's position by a relative amount. */
  29719. void moveBy (const float deltaX,
  29720. const float deltaY) throw();
  29721. /** Draws the glyph into a graphics context. */
  29722. void draw (const Graphics& g) const throw();
  29723. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  29724. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29725. /** Returns the path for this glyph.
  29726. @param path the glyph's outline will be appended to this path
  29727. */
  29728. void createPath (Path& path) const throw();
  29729. /** Checks to see if a point lies within this glyph. */
  29730. bool hitTest (float x, float y) const throw();
  29731. juce_UseDebuggingNewOperator
  29732. private:
  29733. friend class GlyphArrangement;
  29734. float x, y, w;
  29735. Font font;
  29736. juce_wchar character;
  29737. int glyph;
  29738. PositionedGlyph() throw();
  29739. };
  29740. /**
  29741. A set of glyphs, each with a position.
  29742. You can create a GlyphArrangement, text to it and then draw it onto a
  29743. graphics context. It's used internally by the text methods in the
  29744. Graphics class, but can be used directly if more control is needed.
  29745. @see Font, PositionedGlyph
  29746. */
  29747. class JUCE_API GlyphArrangement
  29748. {
  29749. public:
  29750. /** Creates an empty arrangement. */
  29751. GlyphArrangement() throw();
  29752. /** Takes a copy of another arrangement. */
  29753. GlyphArrangement (const GlyphArrangement& other) throw();
  29754. /** Copies another arrangement onto this one.
  29755. To add another arrangement without clearing this one, use addGlyphArrangement().
  29756. */
  29757. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  29758. /** Destructor. */
  29759. ~GlyphArrangement() throw();
  29760. /** Returns the total number of glyphs in the arrangement. */
  29761. int getNumGlyphs() const throw() { return glyphs.size(); }
  29762. /** Returns one of the glyphs from the arrangement.
  29763. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  29764. careful not to pass an out-of-range index here, as it
  29765. doesn't do any bounds-checking.
  29766. */
  29767. PositionedGlyph& getGlyph (const int index) const throw();
  29768. /** Clears all text from the arrangement and resets it.
  29769. */
  29770. void clear() throw();
  29771. /** Appends a line of text to the arrangement.
  29772. This will add the text as a single line, where x is the left-hand edge of the
  29773. first character, and y is the position for the text's baseline.
  29774. If the text contains new-lines or carriage-returns, this will ignore them - use
  29775. addJustifiedText() to add multi-line arrangements.
  29776. */
  29777. void addLineOfText (const Font& font,
  29778. const String& text,
  29779. const float x,
  29780. const float y) throw();
  29781. /** Adds a line of text, truncating it if it's wider than a specified size.
  29782. This is the same as addLineOfText(), but if the line's width exceeds the value
  29783. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  29784. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  29785. */
  29786. void addCurtailedLineOfText (const Font& font,
  29787. const String& text,
  29788. float x,
  29789. const float y,
  29790. const float maxWidthPixels,
  29791. const bool useEllipsis) throw();
  29792. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  29793. This will add text to the arrangement, breaking it into new lines either where there
  29794. is a new-line or carriage-return character in the text, or where a line's width
  29795. exceeds the value set in maxLineWidth.
  29796. Each line that is added will be laid out using the flags set in horizontalLayout, so
  29797. the lines can be left- or right-justified, or centred horizontally in the space
  29798. between x and (x + maxLineWidth).
  29799. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  29800. lines will be placed below it, separated by a distance of font.getHeight().
  29801. */
  29802. void addJustifiedText (const Font& font,
  29803. const String& text,
  29804. float x, float y,
  29805. const float maxLineWidth,
  29806. const Justification& horizontalLayout) throw();
  29807. /** Tries to fit some text withing a given space.
  29808. This does its best to make the given text readable within the specified rectangle,
  29809. so it useful for labelling things.
  29810. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  29811. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  29812. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  29813. it's been truncated.
  29814. A Justification parameter lets you specify how the text is laid out within the rectangle,
  29815. both horizontally and vertically.
  29816. @see Graphics::drawFittedText
  29817. */
  29818. void addFittedText (const Font& font,
  29819. const String& text,
  29820. const float x, const float y,
  29821. const float width, const float height,
  29822. const Justification& layout,
  29823. int maximumLinesToUse,
  29824. const float minimumHorizontalScale = 0.7f) throw();
  29825. /** Appends another glyph arrangement to this one. */
  29826. void addGlyphArrangement (const GlyphArrangement& other) throw();
  29827. /** Draws this glyph arrangement to a graphics context.
  29828. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  29829. method, which renders the glyphs as filled vectors.
  29830. */
  29831. void draw (const Graphics& g) const throw();
  29832. /** Draws this glyph arrangement to a graphics context.
  29833. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  29834. method for non-transformed arrangements.
  29835. */
  29836. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29837. /** Converts the set of glyphs into a path.
  29838. @param path the glyphs' outlines will be appended to this path
  29839. */
  29840. void createPath (Path& path) const throw();
  29841. /** Looks for a glyph that contains the given co-ordinate.
  29842. @returns the index of the glyph, or -1 if none were found.
  29843. */
  29844. int findGlyphIndexAt (float x, float y) const throw();
  29845. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  29846. @param startIndex the first glyph to test
  29847. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  29848. startIndex will be included
  29849. @param left on return, the leftmost co-ordinate of the rectangle
  29850. @param top on return, the top co-ordinate of the rectangle
  29851. @param right on return, the rightmost co-ordinate of the rectangle
  29852. @param bottom on return, the bottom co-ordinate of the rectangle
  29853. @param includeWhitespace if true, the extent of any whitespace characters will also
  29854. be taken into account
  29855. */
  29856. void getBoundingBox (int startIndex,
  29857. int numGlyphs,
  29858. float& left,
  29859. float& top,
  29860. float& right,
  29861. float& bottom,
  29862. const bool includeWhitespace) const throw();
  29863. /** Shifts a set of glyphs by a given amount.
  29864. @param startIndex the first glyph to transform
  29865. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  29866. startIndex will be used
  29867. @param deltaX the amount to add to their x-positions
  29868. @param deltaY the amount to add to their y-positions
  29869. */
  29870. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  29871. const float deltaX,
  29872. const float deltaY) throw();
  29873. /** Removes a set of glyphs from the arrangement.
  29874. @param startIndex the first glyph to remove
  29875. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  29876. startIndex will be deleted
  29877. */
  29878. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  29879. /** Expands or compresses a set of glyphs horizontally.
  29880. @param startIndex the first glyph to transform
  29881. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  29882. startIndex will be used
  29883. @param horizontalScaleFactor how much to scale their horizontal width by
  29884. */
  29885. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  29886. const float horizontalScaleFactor) throw();
  29887. /** Justifies a set of glyphs within a given space.
  29888. This moves the glyphs as a block so that the whole thing is located within the
  29889. given rectangle with the specified layout.
  29890. If the Justification::horizontallyJustified flag is specified, each line will
  29891. be stretched out to fill the specified width.
  29892. */
  29893. void justifyGlyphs (const int startIndex, const int numGlyphs,
  29894. const float x,
  29895. const float y,
  29896. const float width,
  29897. const float height,
  29898. const Justification& justification) throw();
  29899. juce_UseDebuggingNewOperator
  29900. private:
  29901. OwnedArray <PositionedGlyph> glyphs;
  29902. int insertEllipsis (const Font& font, const float maxXPos, const int startIndex, int endIndex) throw();
  29903. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  29904. const Justification& justification, float minimumHorizontalScale) throw();
  29905. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  29906. };
  29907. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29908. /********* End of inlined file: juce_GlyphArrangement.h *********/
  29909. #endif
  29910. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  29911. #endif
  29912. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29913. #endif
  29914. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29915. #endif
  29916. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29917. #endif
  29918. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29919. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29920. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29921. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29922. /********* Start of inlined file: juce_Image.h *********/
  29923. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29924. #define __JUCE_IMAGE_JUCEHEADER__
  29925. /**
  29926. Holds a fixed-size bitmap.
  29927. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  29928. To draw into an image, create a Graphics object for it.
  29929. e.g. @code
  29930. // create a transparent 500x500 image..
  29931. Image myImage (Image::RGB, 500, 500, true);
  29932. Graphics g (myImage);
  29933. g.setColour (Colours::red);
  29934. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  29935. @endcode
  29936. Other useful ways to create an image are with the ImageCache class, or the
  29937. ImageFileFormat, which provides a way to load common image files.
  29938. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  29939. */
  29940. class JUCE_API Image
  29941. {
  29942. public:
  29943. enum PixelFormat
  29944. {
  29945. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  29946. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  29947. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  29948. };
  29949. /** Creates an in-memory image with a specified size and format.
  29950. To create an image that can use native OS rendering methods, see createNativeImage().
  29951. @param format the number of colour channels in the image
  29952. @param imageWidth the desired width of the image, in pixels - this value must be
  29953. greater than zero (otherwise a width of 1 will be used)
  29954. @param imageHeight the desired width of the image, in pixels - this value must be
  29955. greater than zero (otherwise a height of 1 will be used)
  29956. @param clearImage if true, the image will initially be cleared to black or transparent
  29957. black. If false, the image may contain random data, and the
  29958. user will have to deal with this
  29959. */
  29960. Image (const PixelFormat format,
  29961. const int imageWidth,
  29962. const int imageHeight,
  29963. const bool clearImage);
  29964. /** Creates a copy of another image.
  29965. @see createCopy
  29966. */
  29967. Image (const Image& other);
  29968. /** Destructor. */
  29969. virtual ~Image();
  29970. /** Tries to create an image that is uses native drawing methods when you render
  29971. onto it.
  29972. On some platforms this will just return a normal software-based image.
  29973. */
  29974. static Image* createNativeImage (const PixelFormat format,
  29975. const int imageWidth,
  29976. const int imageHeight,
  29977. const bool clearImage);
  29978. /** Returns the image's width (in pixels). */
  29979. int getWidth() const throw() { return imageWidth; }
  29980. /** Returns the image's height (in pixels). */
  29981. int getHeight() const throw() { return imageHeight; }
  29982. /** Returns a rectangle with the same size as this image.
  29983. The rectangle is always at position (0, 0).
  29984. */
  29985. const Rectangle getBounds() const throw() { return Rectangle (0, 0, imageWidth, imageHeight); }
  29986. /** Returns the image's pixel format. */
  29987. PixelFormat getFormat() const throw() { return format; }
  29988. /** True if the image's format is ARGB. */
  29989. bool isARGB() const throw() { return format == ARGB; }
  29990. /** True if the image's format is RGB. */
  29991. bool isRGB() const throw() { return format == RGB; }
  29992. /** True if the image contains an alpha-channel. */
  29993. bool hasAlphaChannel() const throw() { return format != RGB; }
  29994. /** Clears a section of the image with a given colour.
  29995. This won't do any alpha-blending - it just sets all pixels in the image to
  29996. the given colour (which may be non-opaque if the image has an alpha channel).
  29997. */
  29998. virtual void clear (int x, int y, int w, int h,
  29999. const Colour& colourToClearTo = Colour (0x00000000));
  30000. /** Returns a new image that's a copy of this one.
  30001. A new size for the copied image can be specified, or values less than
  30002. zero can be passed-in to use the image's existing dimensions.
  30003. It's up to the caller to delete the image when no longer needed.
  30004. */
  30005. virtual Image* createCopy (int newWidth = -1,
  30006. int newHeight = -1,
  30007. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  30008. /** Returns a new single-channel image which is a copy of the alpha-channel of this image.
  30009. */
  30010. virtual Image* createCopyOfAlphaChannel() const;
  30011. /** Returns the colour of one of the pixels in the image.
  30012. If the co-ordinates given are beyond the image's boundaries, this will
  30013. return Colours::transparentBlack.
  30014. (0, 0) is the image's top-left corner.
  30015. @see getAlphaAt, setPixelAt, blendPixelAt
  30016. */
  30017. virtual const Colour getPixelAt (const int x, const int y) const;
  30018. /** Sets the colour of one of the image's pixels.
  30019. If the co-ordinates are beyond the image's boundaries, then nothing will
  30020. happen.
  30021. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  30022. just replace the existing pixel with the given one. The colour's opacity
  30023. will be ignored if this image doesn't have an alpha-channel.
  30024. (0, 0) is the image's top-left corner.
  30025. @see blendPixelAt
  30026. */
  30027. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  30028. /** Changes the opacity of a pixel.
  30029. This only has an effect if the image has an alpha channel and if the
  30030. given co-ordinates are inside the image's boundary.
  30031. The multiplier must be in the range 0 to 1.0, and the current alpha
  30032. at the given co-ordinates will be multiplied by this value.
  30033. @see getAlphaAt, setPixelAt
  30034. */
  30035. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  30036. /** Changes the overall opacity of the image.
  30037. This will multiply the alpha value of each pixel in the image by the given
  30038. amount (limiting the resulting alpha values between 0 and 255). This allows
  30039. you to make an image more or less transparent.
  30040. If the image doesn't have an alpha channel, this won't have any effect.
  30041. */
  30042. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  30043. /** Changes all the colours to be shades of grey, based on their current luminosity.
  30044. */
  30045. virtual void desaturate();
  30046. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  30047. You should only use this class as a last resort - messing about with the internals of
  30048. an image is only recommended for people who really know what they're doing!
  30049. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  30050. hanging around while the image is being used elsewhere.
  30051. Depending on the way the image class is implemented, this may create a temporary buffer
  30052. which is copied back to the image when the object is deleted, or it may just get a pointer
  30053. directly into the image's raw data.
  30054. You can use the stride and data values in this class directly, but don't alter them!
  30055. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  30056. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  30057. */
  30058. class BitmapData
  30059. {
  30060. public:
  30061. BitmapData (Image& image, int x, int y, int w, int h, const bool needsToBeWritable) throw();
  30062. BitmapData (const Image& image, int x, int y, int w, int h) throw();
  30063. ~BitmapData() throw();
  30064. /** Returns a pointer to the start of a line in the image.
  30065. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  30066. sure it's not out-of-range.
  30067. */
  30068. inline uint8* getLinePointer (const int y) const throw() { return data + y * lineStride; }
  30069. /** Returns a pointer to a pixel in the image.
  30070. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  30071. not out-of-range.
  30072. */
  30073. inline uint8* getPixelPointer (const int x, const int y) const throw() { return data + y * lineStride + x * pixelStride; }
  30074. uint8* data;
  30075. int lineStride, pixelStride, width, height;
  30076. private:
  30077. BitmapData (const BitmapData&);
  30078. const BitmapData& operator= (const BitmapData&);
  30079. };
  30080. /** Copies some pixel values to a rectangle of the image.
  30081. The format of the pixel data must match that of the image itself, and the
  30082. rectangle supplied must be within the image's bounds.
  30083. */
  30084. virtual void setPixelData (int destX, int destY, int destW, int destH,
  30085. const uint8* sourcePixelData, int sourceLineStride);
  30086. /** Copies a section of the image to somewhere else within itself.
  30087. */
  30088. virtual void moveImageSection (int destX, int destY,
  30089. int sourceX, int sourceY,
  30090. int width, int height);
  30091. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  30092. of the image.
  30093. @param result the list that will have the area added to it
  30094. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  30095. above this level will be considered opaque
  30096. */
  30097. void createSolidAreaMask (RectangleList& result,
  30098. const float alphaThreshold = 0.5f) const;
  30099. juce_UseDebuggingNewOperator
  30100. /** Creates a context suitable for drawing onto this image.
  30101. Don't call this method directly! It's used internally by the Graphics class.
  30102. */
  30103. virtual LowLevelGraphicsContext* createLowLevelContext();
  30104. protected:
  30105. friend class BitmapData;
  30106. const PixelFormat format;
  30107. const int imageWidth, imageHeight;
  30108. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  30109. Image (const PixelFormat format,
  30110. const int imageWidth,
  30111. const int imageHeight);
  30112. int pixelStride, lineStride;
  30113. uint8* imageData;
  30114. private:
  30115. const Image& operator= (const Image&);
  30116. };
  30117. #endif // __JUCE_IMAGE_JUCEHEADER__
  30118. /********* End of inlined file: juce_Image.h *********/
  30119. /**
  30120. Interface class for graphics context objects, used internally by the Graphics class.
  30121. Users are not supposed to create instances of this class directly - do your drawing
  30122. via the Graphics object instead.
  30123. It's a base class for different types of graphics context, that may perform software-based
  30124. or OS-accelerated rendering.
  30125. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  30126. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  30127. context.
  30128. */
  30129. class JUCE_API LowLevelGraphicsContext
  30130. {
  30131. protected:
  30132. LowLevelGraphicsContext();
  30133. public:
  30134. virtual ~LowLevelGraphicsContext();
  30135. /** Returns true if this device is vector-based, e.g. a printer. */
  30136. virtual bool isVectorDevice() const = 0;
  30137. /** Moves the origin to a new position.
  30138. The co-ords are relative to the current origin, and indicate the new position
  30139. of (0, 0).
  30140. */
  30141. virtual void setOrigin (int x, int y) = 0;
  30142. virtual bool clipToRectangle (const Rectangle& r) = 0;
  30143. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  30144. virtual void excludeClipRectangle (const Rectangle& r) = 0;
  30145. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  30146. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform) = 0;
  30147. virtual bool clipRegionIntersects (const Rectangle& r) = 0;
  30148. virtual const Rectangle getClipBounds() const = 0;
  30149. virtual bool isClipEmpty() const = 0;
  30150. virtual void saveState() = 0;
  30151. virtual void restoreState() = 0;
  30152. virtual void setFill (const FillType& fillType) = 0;
  30153. virtual void setOpacity (float newOpacity) = 0;
  30154. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  30155. virtual void fillRect (const Rectangle& r, const bool replaceExistingContents) = 0;
  30156. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  30157. virtual void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  30158. const AffineTransform& transform, const bool fillEntireClipAsTiles) = 0;
  30159. virtual void drawLine (double x1, double y1, double x2, double y2) = 0;
  30160. virtual void drawVerticalLine (const int x, double top, double bottom) = 0;
  30161. virtual void drawHorizontalLine (const int y, double left, double right) = 0;
  30162. virtual void setFont (const Font& newFont) = 0;
  30163. virtual const Font getFont() = 0;
  30164. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  30165. };
  30166. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  30167. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  30168. #endif
  30169. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  30170. #endif
  30171. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  30172. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  30173. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  30174. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  30175. class LLGCSavedState;
  30176. /**
  30177. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  30178. its rendering in memory.
  30179. User code is not supposed to create instances of this class directly - do all your
  30180. rendering via the Graphics class instead.
  30181. */
  30182. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  30183. {
  30184. public:
  30185. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  30186. ~LowLevelGraphicsSoftwareRenderer();
  30187. bool isVectorDevice() const;
  30188. void setOrigin (int x, int y);
  30189. bool clipToRectangle (const Rectangle& r);
  30190. bool clipToRectangleList (const RectangleList& clipRegion);
  30191. void excludeClipRectangle (const Rectangle& r);
  30192. void clipToPath (const Path& path, const AffineTransform& transform);
  30193. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  30194. bool clipRegionIntersects (const Rectangle& r);
  30195. const Rectangle getClipBounds() const;
  30196. bool isClipEmpty() const;
  30197. void saveState();
  30198. void restoreState();
  30199. void setFill (const FillType& fillType);
  30200. void setOpacity (float opacity);
  30201. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  30202. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  30203. void fillPath (const Path& path, const AffineTransform& transform);
  30204. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  30205. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  30206. void drawLine (double x1, double y1, double x2, double y2);
  30207. void drawVerticalLine (const int x, double top, double bottom);
  30208. void drawHorizontalLine (const int x, double top, double bottom);
  30209. void setFont (const Font& newFont);
  30210. const Font getFont();
  30211. void drawGlyph (int glyphNumber, float x, float y);
  30212. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  30213. juce_UseDebuggingNewOperator
  30214. protected:
  30215. Image& image;
  30216. LLGCSavedState* currentState;
  30217. OwnedArray <LLGCSavedState> stateStack;
  30218. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  30219. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  30220. };
  30221. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  30222. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  30223. #endif
  30224. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  30225. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  30226. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  30227. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  30228. /**
  30229. An implementation of LowLevelGraphicsContext that turns the drawing operations
  30230. into a PostScript document.
  30231. */
  30232. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  30233. {
  30234. public:
  30235. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  30236. const String& documentTitle,
  30237. const int totalWidth,
  30238. const int totalHeight);
  30239. ~LowLevelGraphicsPostScriptRenderer();
  30240. bool isVectorDevice() const;
  30241. void setOrigin (int x, int y);
  30242. bool clipToRectangle (const Rectangle& r);
  30243. bool clipToRectangleList (const RectangleList& clipRegion);
  30244. void excludeClipRectangle (const Rectangle& r);
  30245. void clipToPath (const Path& path, const AffineTransform& transform);
  30246. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  30247. void saveState();
  30248. void restoreState();
  30249. bool clipRegionIntersects (const Rectangle& r);
  30250. const Rectangle getClipBounds() const;
  30251. bool isClipEmpty() const;
  30252. void setFill (const FillType& fillType);
  30253. void setOpacity (float opacity);
  30254. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  30255. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  30256. void fillPath (const Path& path, const AffineTransform& transform);
  30257. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  30258. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  30259. void drawLine (double x1, double y1, double x2, double y2);
  30260. void drawVerticalLine (const int x, double top, double bottom);
  30261. void drawHorizontalLine (const int x, double top, double bottom);
  30262. const Font getFont();
  30263. void setFont (const Font& newFont);
  30264. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  30265. juce_UseDebuggingNewOperator
  30266. protected:
  30267. OutputStream& out;
  30268. int totalWidth, totalHeight;
  30269. bool needToClip;
  30270. Colour lastColour;
  30271. struct SavedState
  30272. {
  30273. SavedState();
  30274. ~SavedState();
  30275. RectangleList clip;
  30276. int xOffset, yOffset;
  30277. FillType fillType;
  30278. Font font;
  30279. private:
  30280. const SavedState& operator= (const SavedState&);
  30281. };
  30282. OwnedArray <SavedState> stateStack;
  30283. void writeClip();
  30284. void writeColour (const Colour& colour);
  30285. void writePath (const Path& path) const;
  30286. void writeXY (const float x, const float y) const;
  30287. void writeTransform (const AffineTransform& trans) const;
  30288. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  30289. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  30290. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  30291. };
  30292. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  30293. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  30294. #endif
  30295. #ifndef __JUCE_PATH_JUCEHEADER__
  30296. #endif
  30297. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  30298. #endif
  30299. #ifndef __JUCE_LINE_JUCEHEADER__
  30300. #endif
  30301. #ifndef __JUCE_POINT_JUCEHEADER__
  30302. #endif
  30303. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  30304. #endif
  30305. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  30306. #endif
  30307. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30308. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  30309. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30310. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30311. /**
  30312. A rectangle whose co-ordinates can be defined in terms of absolute or
  30313. proportional distances.
  30314. Designed mainly for storing component positions, this gives you a lot of
  30315. control over how each co-ordinate is stored, either as an absolute position,
  30316. or as a proportion of the size of a parent rectangle.
  30317. It also allows you to define the anchor points by which the rectangle is
  30318. positioned, so for example you could specify that the top right of the
  30319. rectangle should be an absolute distance from its parent's bottom-right corner.
  30320. This object can be stored as a string, which takes the form "x y w h", including
  30321. symbols like '%' and letters to indicate the anchor point. See its toString()
  30322. method for more info.
  30323. Example usage:
  30324. @code
  30325. class MyComponent
  30326. {
  30327. void resized()
  30328. {
  30329. // this will set the child component's x to be 20% of our width, its y
  30330. // to be 30, its width to be 150, and its height to be 50% of our
  30331. // height..
  30332. const PositionedRectangle pos1 ("20% 30 150 50%");
  30333. pos1.applyToComponent (*myChildComponent1);
  30334. // this will inset the child component with a gap of 10 pixels
  30335. // around each of its edges..
  30336. const PositionedRectangle pos2 ("10 10 20M 20M");
  30337. pos2.applyToComponent (*myChildComponent2);
  30338. }
  30339. };
  30340. @endcode
  30341. */
  30342. class JUCE_API PositionedRectangle
  30343. {
  30344. public:
  30345. /** Creates an empty rectangle with all co-ordinates set to zero.
  30346. The default anchor point is top-left; the default
  30347. */
  30348. PositionedRectangle() throw();
  30349. /** Initialises a PositionedRectangle from a saved string version.
  30350. The string must be in the format generated by toString().
  30351. */
  30352. PositionedRectangle (const String& stringVersion) throw();
  30353. /** Creates a copy of another PositionedRectangle. */
  30354. PositionedRectangle (const PositionedRectangle& other) throw();
  30355. /** Copies another PositionedRectangle. */
  30356. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  30357. /** Destructor. */
  30358. ~PositionedRectangle() throw();
  30359. /** Returns a string version of this position, from which it can later be
  30360. re-generated.
  30361. The format is four co-ordinates, "x y w h".
  30362. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  30363. - If a co-ordinate is proportional to its parent's width or height, it is stored
  30364. as a percentage, e.g. "80%".
  30365. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  30366. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  30367. the parent's right-hand edge.
  30368. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  30369. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  30370. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  30371. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  30372. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  30373. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  30374. has "c" appended to it. So "-50Rc" would mean that this component's
  30375. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  30376. this component's centre should be placed 40% across the parent's width.
  30377. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  30378. the number has "M" appended to it.
  30379. To reload a stored string, use the constructor that takes a string parameter.
  30380. */
  30381. const String toString() const throw();
  30382. /** Calculates the absolute position, given the size of the space that
  30383. it should go in.
  30384. This will work out any proportional distances and sizes relative to the
  30385. target rectangle, and will return the absolute position.
  30386. @see applyToComponent
  30387. */
  30388. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  30389. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  30390. */
  30391. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  30392. double& x,
  30393. double& y,
  30394. double& width,
  30395. double& height) const throw();
  30396. /** This sets the bounds of the given component to this position.
  30397. This is equivalent to writing:
  30398. @code
  30399. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  30400. @endcode
  30401. @see getRectangle, updateFromComponent
  30402. */
  30403. void applyToComponent (Component& comp) const throw();
  30404. /** Updates this object's co-ordinates to match the given rectangle.
  30405. This will set all co-ordinates based on the given rectangle, re-calculating
  30406. any proportional distances, and using the current anchor points.
  30407. So for example if the x co-ordinate mode is currently proportional, this will
  30408. re-calculate x based on the rectangle's relative position within the target
  30409. rectangle's width.
  30410. If the target rectangle's width or height are zero then it may not be possible
  30411. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  30412. will not be changed.
  30413. */
  30414. void updateFrom (const Rectangle& newPosition,
  30415. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30416. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  30417. */
  30418. void updateFromDouble (const double x, const double y,
  30419. const double width, const double height,
  30420. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30421. /** Updates this object's co-ordinates to match the bounds of this component.
  30422. This is equivalent to calling updateFrom() with the component's bounds and
  30423. it parent size.
  30424. If the component doesn't currently have a parent, then proportional co-ordinates
  30425. might not be updated because it would need to know the parent's size to do the
  30426. maths for this.
  30427. */
  30428. void updateFromComponent (const Component& comp) throw();
  30429. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  30430. enum AnchorPoint
  30431. {
  30432. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  30433. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  30434. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  30435. };
  30436. /** Specifies how an x or y co-ordinate should be interpreted. */
  30437. enum PositionMode
  30438. {
  30439. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  30440. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  30441. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  30442. 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. */
  30443. };
  30444. /** Specifies how the width or height should be interpreted. */
  30445. enum SizeMode
  30446. {
  30447. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  30448. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  30449. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  30450. };
  30451. /** Sets all options for all co-ordinates.
  30452. This requires a reference rectangle to be specified, because if you're changing any
  30453. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  30454. the co-ordinates, and will need to know the parent size so it can calculate this.
  30455. */
  30456. void setModes (const AnchorPoint xAnchorMode,
  30457. const PositionMode xPositionMode,
  30458. const AnchorPoint yAnchorMode,
  30459. const PositionMode yPositionMode,
  30460. const SizeMode widthMode,
  30461. const SizeMode heightMode,
  30462. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30463. /** Returns the anchoring mode for the x co-ordinate.
  30464. To change any of the modes, use setModes().
  30465. */
  30466. AnchorPoint getAnchorPointX() const throw();
  30467. /** Returns the positioning mode for the x co-ordinate.
  30468. To change any of the modes, use setModes().
  30469. */
  30470. PositionMode getPositionModeX() const throw();
  30471. /** Returns the raw x co-ordinate.
  30472. If the x position mode is absolute, then this will be the absolute value. If it's
  30473. proportional, then this will be a fractional proportion, where 1.0 means the full
  30474. width of the parent space.
  30475. */
  30476. double getX() const throw() { return x; }
  30477. /** Sets the raw value of the x co-ordinate.
  30478. See getX() for the meaning of this value.
  30479. */
  30480. void setX (const double newX) throw() { x = newX; }
  30481. /** Returns the anchoring mode for the y co-ordinate.
  30482. To change any of the modes, use setModes().
  30483. */
  30484. AnchorPoint getAnchorPointY() const throw();
  30485. /** Returns the positioning mode for the y co-ordinate.
  30486. To change any of the modes, use setModes().
  30487. */
  30488. PositionMode getPositionModeY() const throw();
  30489. /** Returns the raw y co-ordinate.
  30490. If the y position mode is absolute, then this will be the absolute value. If it's
  30491. proportional, then this will be a fractional proportion, where 1.0 means the full
  30492. height of the parent space.
  30493. */
  30494. double getY() const throw() { return y; }
  30495. /** Sets the raw value of the y co-ordinate.
  30496. See getY() for the meaning of this value.
  30497. */
  30498. void setY (const double newY) throw() { y = newY; }
  30499. /** Returns the mode used to calculate the width.
  30500. To change any of the modes, use setModes().
  30501. */
  30502. SizeMode getWidthMode() const throw();
  30503. /** Returns the raw width value.
  30504. If the width mode is absolute, then this will be the absolute value. If the mode is
  30505. proportional, then this will be a fractional proportion, where 1.0 means the full
  30506. width of the parent space.
  30507. */
  30508. double getWidth() const throw() { return w; }
  30509. /** Sets the raw width value.
  30510. See getWidth() for the details about what this value means.
  30511. */
  30512. void setWidth (const double newWidth) throw() { w = newWidth; }
  30513. /** Returns the mode used to calculate the height.
  30514. To change any of the modes, use setModes().
  30515. */
  30516. SizeMode getHeightMode() const throw();
  30517. /** Returns the raw height value.
  30518. If the height mode is absolute, then this will be the absolute value. If the mode is
  30519. proportional, then this will be a fractional proportion, where 1.0 means the full
  30520. height of the parent space.
  30521. */
  30522. double getHeight() const throw() { return h; }
  30523. /** Sets the raw height value.
  30524. See getHeight() for the details about what this value means.
  30525. */
  30526. void setHeight (const double newHeight) throw() { h = newHeight; }
  30527. /** If the size and position are constance, and wouldn't be affected by changes
  30528. in the parent's size, then this will return true.
  30529. */
  30530. bool isPositionAbsolute() const throw();
  30531. /** Compares two objects. */
  30532. const bool operator== (const PositionedRectangle& other) const throw();
  30533. /** Compares two objects. */
  30534. const bool operator!= (const PositionedRectangle& other) const throw();
  30535. juce_UseDebuggingNewOperator
  30536. private:
  30537. double x, y, w, h;
  30538. uint8 xMode, yMode, wMode, hMode;
  30539. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  30540. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  30541. void decodePosString (const String& s, uint8& mode, double& value) throw();
  30542. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  30543. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  30544. const uint8 xMode, const uint8 wMode,
  30545. const int parentPos, const int parentSize) const throw();
  30546. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  30547. const uint8 xMode, const uint8 wMode,
  30548. const int parentPos, const int parentSize) const throw();
  30549. };
  30550. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30551. /********* End of inlined file: juce_PositionedRectangle.h *********/
  30552. #endif
  30553. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  30554. #endif
  30555. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  30556. /********* Start of inlined file: juce_PathIterator.h *********/
  30557. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  30558. #define __JUCE_PATHITERATOR_JUCEHEADER__
  30559. /**
  30560. Flattens a Path object into a series of straight-line sections.
  30561. Use one of these to iterate through a Path object, and it will convert
  30562. all the curves into line sections so it's easy to render or perform
  30563. geometric operations on.
  30564. @see Path
  30565. */
  30566. class JUCE_API PathFlatteningIterator
  30567. {
  30568. public:
  30569. /** Creates a PathFlatteningIterator.
  30570. After creation, use the next() method to initialise the fields in the
  30571. object with the first line's position.
  30572. @param path the path to iterate along
  30573. @param transform a transform to apply to each point in the path being iterated
  30574. @param tolerence the amount by which the curves are allowed to deviate from the
  30575. lines into which they are being broken down - a higher tolerence
  30576. is a bit faster, but less smooth.
  30577. */
  30578. PathFlatteningIterator (const Path& path,
  30579. const AffineTransform& transform = AffineTransform::identity,
  30580. float tolerence = 6.0f) throw();
  30581. /** Destructor. */
  30582. ~PathFlatteningIterator() throw();
  30583. /** Fetches the next line segment from the path.
  30584. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  30585. so that they describe the new line segment.
  30586. @returns false when there are no more lines to fetch.
  30587. */
  30588. bool next() throw();
  30589. /** The x position of the start of the current line segment. */
  30590. float x1;
  30591. /** The y position of the start of the current line segment. */
  30592. float y1;
  30593. /** The x position of the end of the current line segment. */
  30594. float x2;
  30595. /** The y position of the end of the current line segment. */
  30596. float y2;
  30597. /** Indicates whether the current line segment is closing a sub-path.
  30598. If the current line is the one that connects the end of a sub-path
  30599. back to the start again, this will be true.
  30600. */
  30601. bool closesSubPath;
  30602. /** The index of the current line within the current sub-path.
  30603. E.g. you can use this to see whether the line is the first one in the
  30604. subpath by seeing if it's 0.
  30605. */
  30606. int subPathIndex;
  30607. /** Returns true if the current segment is the last in the current sub-path. */
  30608. bool isLastInSubpath() const throw() { return stackPos == stackBase
  30609. && (index >= path.numElements
  30610. || points [index] == Path::moveMarker); }
  30611. juce_UseDebuggingNewOperator
  30612. private:
  30613. const Path& path;
  30614. const AffineTransform transform;
  30615. float* points;
  30616. float tolerence, subPathCloseX, subPathCloseY;
  30617. bool isIdentityTransform;
  30618. float* stackBase;
  30619. float* stackPos;
  30620. int index, stackSize;
  30621. PathFlatteningIterator (const PathFlatteningIterator&);
  30622. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  30623. };
  30624. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  30625. /********* End of inlined file: juce_PathIterator.h *********/
  30626. #endif
  30627. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  30628. #endif
  30629. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30630. /********* Start of inlined file: juce_CameraDevice.h *********/
  30631. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30632. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  30633. #if JUCE_USE_CAMERA
  30634. /**
  30635. Receives callbacks with images from a CameraDevice.
  30636. @see CameraDevice::addListener
  30637. */
  30638. class CameraImageListener
  30639. {
  30640. public:
  30641. CameraImageListener() {}
  30642. virtual ~CameraImageListener() {}
  30643. /** This method is called when a new image arrives.
  30644. This may be called by any thread, so be careful about thread-safety,
  30645. and make sure that you process the data as quickly as possible to
  30646. avoid glitching!
  30647. */
  30648. virtual void imageReceived (Image& image) = 0;
  30649. };
  30650. /**
  30651. Controls any camera capture devices that might be available.
  30652. Use getAvailableDevices() to list the devices that are attached to the
  30653. system, then call openDevice to open one for use. Once you have a CameraDevice
  30654. object, you can get a viewer component from it, and use its methods to
  30655. stream to a file or capture still-frames.
  30656. */
  30657. class JUCE_API CameraDevice
  30658. {
  30659. public:
  30660. /** Destructor. */
  30661. virtual ~CameraDevice();
  30662. /** Returns a list of the available cameras on this machine.
  30663. You can open one of these devices by calling openDevice().
  30664. */
  30665. static const StringArray getAvailableDevices();
  30666. /** Opens a camera device.
  30667. The index parameter indicates which of the items returned by getAvailableDevices()
  30668. to open.
  30669. The size constraints allow the method to choose between different resolutions if
  30670. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  30671. then these will be ignored.
  30672. */
  30673. static CameraDevice* openDevice (int deviceIndex,
  30674. int minWidth = 128, int minHeight = 64,
  30675. int maxWidth = 1024, int maxHeight = 768);
  30676. /** Returns the name of this device */
  30677. const String getName() const throw() { return name; }
  30678. /** Creates a component that can be used to display a preview of the
  30679. video from this camera.
  30680. */
  30681. Component* createViewerComponent();
  30682. /** Starts recording video to the specified file.
  30683. You should use getFileExtension() to find out the correct extension to
  30684. use for your filename.
  30685. If the file exists, it will be deleted before the recording starts.
  30686. This method may not start recording instantly, so if you need to know the
  30687. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  30688. after the recording has finished.
  30689. */
  30690. void startRecordingToFile (const File& file);
  30691. /** Stops recording, after a call to startRecordingToFile().
  30692. */
  30693. void stopRecording();
  30694. /** Returns the file extension that should be used for the files
  30695. that you pass to startRecordingToFile().
  30696. This may be platform-specific, e.g. ".mov" or ".avi".
  30697. */
  30698. static const String getFileExtension();
  30699. /** After calling stopRecording(), this method can be called to return the timestamp
  30700. of the first frame that was written to the file.
  30701. */
  30702. const Time getTimeOfFirstRecordedFrame() const;
  30703. /** Adds a listener to receive images from the camera.
  30704. Be very careful not to delete the listener without first removing it by calling
  30705. removeListener().
  30706. */
  30707. void addListener (CameraImageListener* listenerToAdd);
  30708. /** Removes a listener that was previously added with addListener().
  30709. */
  30710. void removeListener (CameraImageListener* listenerToRemove);
  30711. juce_UseDebuggingNewOperator
  30712. protected:
  30713. /** @internal */
  30714. CameraDevice (const String& name, int index);
  30715. private:
  30716. void* internal;
  30717. bool isRecording;
  30718. String name;
  30719. CameraDevice (const CameraDevice&);
  30720. const CameraDevice& operator= (const CameraDevice&);
  30721. };
  30722. #endif
  30723. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  30724. /********* End of inlined file: juce_CameraDevice.h *********/
  30725. #endif
  30726. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30727. /********* Start of inlined file: juce_ImageCache.h *********/
  30728. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30729. #define __JUCE_IMAGECACHE_JUCEHEADER__
  30730. /**
  30731. A global cache of images that have been loaded from files or memory.
  30732. If you're loading an image and may need to use the image in more than one
  30733. place, this is used to allow the same image to be shared rather than loading
  30734. multiple copies into memory.
  30735. Another advantage is that after images are released, they will be kept in
  30736. memory for a few seconds before it is actually deleted, so if you're repeatedly
  30737. loading/deleting the same image, it'll reduce the chances of having to reload it
  30738. each time.
  30739. @see Image, ImageFileFormat
  30740. */
  30741. class JUCE_API ImageCache : private DeletedAtShutdown,
  30742. private Timer
  30743. {
  30744. public:
  30745. /** Loads an image from a file, (or just returns the image if it's already cached).
  30746. If the cache already contains an image that was loaded from this file,
  30747. that image will be returned. Otherwise, this method will try to load the
  30748. file, add it to the cache, and return it.
  30749. It's very important not to delete the image that is returned - instead use
  30750. the ImageCache::release() method.
  30751. Also, remember that the image returned is shared, so drawing into it might
  30752. affect other things that are using it!
  30753. @param file the file to try to load
  30754. @returns the image, or null if it there was an error loading it
  30755. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30756. */
  30757. static Image* getFromFile (const File& file);
  30758. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  30759. If the cache already contains an image that was loaded from this block of memory,
  30760. that image will be returned. Otherwise, this method will try to load the
  30761. file, add it to the cache, and return it.
  30762. It's very important not to delete the image that is returned - instead use
  30763. the ImageCache::release() method.
  30764. Also, remember that the image returned is shared, so drawing into it might
  30765. affect other things that are using it!
  30766. @param imageData the block of memory containing the image data
  30767. @param dataSize the data size in bytes
  30768. @returns the image, or null if it there was an error loading it
  30769. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30770. */
  30771. static Image* getFromMemory (const void* imageData,
  30772. const int dataSize);
  30773. /** Releases an image that was previously created by the ImageCache.
  30774. If an image has been returned by the getFromFile() or getFromMemory() methods,
  30775. it mustn't be deleted directly, but should be released with this method
  30776. instead.
  30777. @see getFromFile, getFromMemory
  30778. */
  30779. static void release (Image* const imageToRelease);
  30780. /** Checks whether an image is in the cache or not.
  30781. @returns true if the image is currently in the cache
  30782. */
  30783. static bool isImageInCache (Image* const imageToLookFor);
  30784. /** Increments the reference-count for a cached image.
  30785. If the image isn't in the cache, this method won't do anything.
  30786. */
  30787. static void incReferenceCount (Image* const image);
  30788. /** Checks the cache for an image with a particular hashcode.
  30789. If there's an image in the cache with this hashcode, it will be returned,
  30790. otherwise it will return zero.
  30791. If an image is returned, it must be released with the release() method
  30792. when no longer needed, to maintain the correct reference counts.
  30793. @param hashCode the hash code that would have been associated with the
  30794. image by addImageToCache()
  30795. @see addImageToCache
  30796. */
  30797. static Image* getFromHashCode (const int64 hashCode);
  30798. /** Adds an image to the cache with a user-defined hash-code.
  30799. After calling this, responsibilty for deleting the image will be taken
  30800. by the ImageCache.
  30801. The image will be initially be given a reference count of 1, so call
  30802. the release() method to delete it.
  30803. @param image the image to add
  30804. @param hashCode the hash-code to associate with it
  30805. @see getFromHashCode
  30806. */
  30807. static void addImageToCache (Image* const image,
  30808. const int64 hashCode);
  30809. /** Changes the amount of time before an unused image will be removed from the cache.
  30810. By default this is about 5 seconds.
  30811. */
  30812. static void setCacheTimeout (const int millisecs);
  30813. juce_UseDebuggingNewOperator
  30814. private:
  30815. CriticalSection lock;
  30816. VoidArray images;
  30817. ImageCache() throw();
  30818. ImageCache (const ImageCache&);
  30819. const ImageCache& operator= (const ImageCache&);
  30820. ~ImageCache();
  30821. void timerCallback();
  30822. };
  30823. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  30824. /********* End of inlined file: juce_ImageCache.h *********/
  30825. #endif
  30826. #ifndef __JUCE_IMAGE_JUCEHEADER__
  30827. #endif
  30828. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30829. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30830. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30831. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30832. /**
  30833. Base-class for codecs that can read and write image file formats such
  30834. as PNG, JPEG, etc.
  30835. This class also contains static methods to make it easy to load images
  30836. from files, streams or from memory.
  30837. @see Image, ImageCache
  30838. */
  30839. class JUCE_API ImageFileFormat
  30840. {
  30841. protected:
  30842. /** Creates an ImageFormat. */
  30843. ImageFileFormat() throw() {}
  30844. public:
  30845. /** Destructor. */
  30846. virtual ~ImageFileFormat() throw() {}
  30847. /** Returns a description of this file format.
  30848. E.g. "JPEG", "PNG"
  30849. */
  30850. virtual const String getFormatName() = 0;
  30851. /** Returns true if the given stream seems to contain data that this format
  30852. understands.
  30853. The format class should only read the first few bytes of the stream and sniff
  30854. for header bytes that it understands.
  30855. @see decodeImage
  30856. */
  30857. virtual bool canUnderstand (InputStream& input) = 0;
  30858. /** Tries to decode and return an image from the given stream.
  30859. This will be called for an image format after calling its canUnderStand() method
  30860. to see if it can handle the stream.
  30861. @param input the stream to read the data from. The stream will be positioned
  30862. at the start of the image data (but this may not necessarily
  30863. be position 0)
  30864. @returns the image that was decoded, or 0 if it fails. It's the
  30865. caller's responsibility to delete this image when no longer needed.
  30866. @see loadFrom
  30867. */
  30868. virtual Image* decodeImage (InputStream& input) = 0;
  30869. /** Attempts to write an image to a stream.
  30870. To specify extra information like encoding quality, there will be appropriate parameters
  30871. in the subclasses of the specific file types.
  30872. @returns true if it nothing went wrong.
  30873. */
  30874. virtual bool writeImageToStream (const Image& sourceImage,
  30875. OutputStream& destStream) = 0;
  30876. /** Tries the built-in decoders to see if it can find one to read this stream.
  30877. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30878. The object that is returned should not be deleted by the caller.
  30879. @see canUnderstand, decodeImage, loadFrom
  30880. */
  30881. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30882. /** Tries to load an image from a stream.
  30883. This will use the findImageFormatForStream() method to locate a suitable
  30884. codec, and use that to load the image.
  30885. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30886. caller's responsibility to delete this image when no longer needed.
  30887. */
  30888. static Image* loadFrom (InputStream& input);
  30889. /** Tries to load an image from a file.
  30890. This will use the findImageFormatForStream() method to locate a suitable
  30891. codec, and use that to load the image.
  30892. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30893. caller's responsibility to delete this image when no longer needed.
  30894. */
  30895. static Image* loadFrom (const File& file);
  30896. /** Tries to load an image from a block of raw image data.
  30897. This will use the findImageFormatForStream() method to locate a suitable
  30898. codec, and use that to load the image.
  30899. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30900. caller's responsibility to delete this image when no longer needed.
  30901. */
  30902. static Image* loadFrom (const void* rawData,
  30903. const int numBytesOfData);
  30904. };
  30905. /**
  30906. A type of ImageFileFormat for reading and writing PNG files.
  30907. @see ImageFileFormat, JPEGImageFormat
  30908. */
  30909. class JUCE_API PNGImageFormat : public ImageFileFormat
  30910. {
  30911. public:
  30912. PNGImageFormat() throw();
  30913. ~PNGImageFormat() throw();
  30914. const String getFormatName();
  30915. bool canUnderstand (InputStream& input);
  30916. Image* decodeImage (InputStream& input);
  30917. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30918. };
  30919. /**
  30920. A type of ImageFileFormat for reading and writing JPEG files.
  30921. @see ImageFileFormat, PNGImageFormat
  30922. */
  30923. class JUCE_API JPEGImageFormat : public ImageFileFormat
  30924. {
  30925. public:
  30926. JPEGImageFormat() throw();
  30927. ~JPEGImageFormat() throw();
  30928. /** Specifies the quality to be used when writing a JPEG file.
  30929. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30930. any negative value is "default" quality
  30931. */
  30932. void setQuality (const float newQuality);
  30933. const String getFormatName();
  30934. bool canUnderstand (InputStream& input);
  30935. Image* decodeImage (InputStream& input);
  30936. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30937. private:
  30938. float quality;
  30939. };
  30940. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30941. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30942. #endif
  30943. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30944. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  30945. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30946. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30947. /**
  30948. Represents a filter kernel to use in convoluting an image.
  30949. @see Image::applyConvolution
  30950. */
  30951. class JUCE_API ImageConvolutionKernel
  30952. {
  30953. public:
  30954. /** Creates an empty convulution kernel.
  30955. @param size the length of each dimension of the kernel, so e.g. if the size
  30956. is 5, it will create a 5x5 kernel
  30957. */
  30958. ImageConvolutionKernel (const int size) throw();
  30959. /** Destructor. */
  30960. ~ImageConvolutionKernel() throw();
  30961. /** Resets all values in the kernel to zero.
  30962. */
  30963. void clear() throw();
  30964. /** Sets the value of a specific cell in the kernel.
  30965. The x and y parameters must be in the range 0 < x < getKernelSize().
  30966. @see setOverallSum
  30967. */
  30968. void setKernelValue (const int x,
  30969. const int y,
  30970. const float value) throw();
  30971. /** Rescales all values in the kernel to make the total add up to a fixed value.
  30972. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  30973. */
  30974. void setOverallSum (const float desiredTotalSum) throw();
  30975. /** Multiplies all values in the kernel by a value. */
  30976. void rescaleAllValues (const float multiplier) throw();
  30977. /** Intialises the kernel for a gaussian blur.
  30978. @param blurRadius this may be larger or smaller than the kernel's actual
  30979. size but this will obviously be wasteful or clip at the
  30980. edges. Ideally the kernel should be just larger than
  30981. (blurRadius * 2).
  30982. */
  30983. void createGaussianBlur (const float blurRadius) throw();
  30984. /** Returns the size of the kernel.
  30985. E.g. if it's a 3x3 kernel, this returns 3.
  30986. */
  30987. int getKernelSize() const throw() { return size; }
  30988. /** Returns a 2-dimensional array of the kernel's values.
  30989. The size of each dimension of the array will be getKernelSize().
  30990. */
  30991. float** getValues() const throw() { return values; }
  30992. /** Applies the kernel to an image.
  30993. @param destImage the image that will receive the resultant convoluted pixels.
  30994. @param sourceImage an optional source image to read from - if this is 0, then the
  30995. destination image will be used as the source. If an image is
  30996. specified, it must be exactly the same size and type as the destination
  30997. image.
  30998. @param x the region of the image to apply the filter to
  30999. @param y the region of the image to apply the filter to
  31000. @param width the region of the image to apply the filter to
  31001. @param height the region of the image to apply the filter to
  31002. */
  31003. void applyToImage (Image& destImage,
  31004. const Image* sourceImage,
  31005. int x,
  31006. int y,
  31007. int width,
  31008. int height) const;
  31009. juce_UseDebuggingNewOperator
  31010. private:
  31011. float** values;
  31012. int size;
  31013. // no reason not to implement these one day..
  31014. ImageConvolutionKernel (const ImageConvolutionKernel&);
  31015. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  31016. };
  31017. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  31018. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  31019. #endif
  31020. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  31021. /********* Start of inlined file: juce_Drawable.h *********/
  31022. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  31023. #define __JUCE_DRAWABLE_JUCEHEADER__
  31024. /**
  31025. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  31026. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  31027. */
  31028. class JUCE_API Drawable
  31029. {
  31030. protected:
  31031. /** The base class can't be instantiated directly.
  31032. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  31033. */
  31034. Drawable();
  31035. public:
  31036. /** Destructor. */
  31037. virtual ~Drawable();
  31038. /** Creates a deep copy of this Drawable object.
  31039. Use this to create a new copy of this and any sub-objects in the tree.
  31040. */
  31041. virtual Drawable* createCopy() const = 0;
  31042. /** Renders this Drawable object.
  31043. @see drawWithin
  31044. */
  31045. void draw (Graphics& g, const float opacity,
  31046. const AffineTransform& transform = AffineTransform::identity) const;
  31047. /** Renders the Drawable at a given offset within the Graphics context.
  31048. The co-ordinates passed-in are used to translate the object relative to its own
  31049. origin before drawing it - this is basically a quick way of saying:
  31050. @code
  31051. draw (g, AffineTransform::translation (x, y)).
  31052. @endcode
  31053. */
  31054. void drawAt (Graphics& g,
  31055. const float x,
  31056. const float y,
  31057. const float opacity) const;
  31058. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  31059. changing its aspect-ratio.
  31060. The object can placed arbitrarily within the rectangle based on a Justification type,
  31061. and can either be made as big as possible, or just reduced to fit.
  31062. @param g the graphics context to render onto
  31063. @param destX top-left of the target rectangle to fit it into
  31064. @param destY top-left of the target rectangle to fit it into
  31065. @param destWidth size of the target rectangle to fit the image into
  31066. @param destHeight size of the target rectangle to fit the image into
  31067. @param placement defines the alignment and rescaling to use to fit
  31068. this object within the target rectangle.
  31069. @param opacity the opacity to use, in the range 0 to 1.0
  31070. */
  31071. void drawWithin (Graphics& g,
  31072. const int destX,
  31073. const int destY,
  31074. const int destWidth,
  31075. const int destHeight,
  31076. const RectanglePlacement& placement,
  31077. const float opacity) const;
  31078. /** Holds the information needed when telling a drawable to render itself.
  31079. @see Drawable::draw
  31080. */
  31081. class RenderingContext
  31082. {
  31083. public:
  31084. RenderingContext (Graphics& g, const AffineTransform& transform, const float opacity) throw();
  31085. Graphics& g;
  31086. AffineTransform transform;
  31087. float opacity;
  31088. private:
  31089. const RenderingContext& operator= (const RenderingContext&);
  31090. };
  31091. /** Renders this Drawable object.
  31092. @see draw
  31093. */
  31094. virtual void render (const RenderingContext& context) const = 0;
  31095. /** Returns the smallest rectangle that can contain this Drawable object.
  31096. Co-ordinates are relative to the object's own origin.
  31097. */
  31098. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  31099. /** Returns true if the given point is somewhere inside this Drawable.
  31100. Co-ordinates are relative to the object's own origin.
  31101. */
  31102. virtual bool hitTest (float x, float y) const = 0;
  31103. /** Returns the name given to this drawable.
  31104. @see setName
  31105. */
  31106. const String& getName() const throw() { return name; }
  31107. /** Assigns a name to this drawable. */
  31108. void setName (const String& newName) throw() { name = newName; }
  31109. /** Tries to turn some kind of image file into a drawable.
  31110. The data could be an image that the ImageFileFormat class understands, or it
  31111. could be SVG.
  31112. */
  31113. static Drawable* createFromImageData (const void* data, const int numBytes);
  31114. /** Tries to turn a stream containing some kind of image data into a drawable.
  31115. The data could be an image that the ImageFileFormat class understands, or it
  31116. could be SVG.
  31117. */
  31118. static Drawable* createFromImageDataStream (InputStream& dataSource);
  31119. /** Tries to turn a file containing some kind of image data into a drawable.
  31120. The data could be an image that the ImageFileFormat class understands, or it
  31121. could be SVG.
  31122. */
  31123. static Drawable* createFromImageFile (const File& file);
  31124. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  31125. into a Drawable tree.
  31126. The object returned must be deleted by the caller. If something goes wrong
  31127. while parsing, it may return 0.
  31128. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  31129. implementation, but it can return the basic vector objects.
  31130. */
  31131. static Drawable* createFromSVG (const XmlElement& svgDocument);
  31132. /** Tries to create a Drawable from a previously-saved ValueTree.
  31133. The ValueTree must have been created by the createValueTree() method.
  31134. */
  31135. static Drawable* createFromValueTree (const ValueTree& tree) throw();
  31136. /** Creates a ValueTree to represent this Drawable.
  31137. The VarTree that is returned can be turned back into a Drawable with
  31138. createFromValueTree().
  31139. */
  31140. virtual ValueTree createValueTree() const throw() = 0;
  31141. juce_UseDebuggingNewOperator
  31142. private:
  31143. Drawable (const Drawable&);
  31144. const Drawable& operator= (const Drawable&);
  31145. String name;
  31146. };
  31147. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  31148. /********* End of inlined file: juce_Drawable.h *********/
  31149. #endif
  31150. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  31151. /********* Start of inlined file: juce_DrawableComposite.h *********/
  31152. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  31153. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  31154. /**
  31155. A drawable object which acts as a container for a set of other Drawables.
  31156. @see Drawable
  31157. */
  31158. class JUCE_API DrawableComposite : public Drawable
  31159. {
  31160. public:
  31161. /** Creates a composite Drawable.
  31162. */
  31163. DrawableComposite();
  31164. /** Destructor. */
  31165. virtual ~DrawableComposite();
  31166. /** Adds a new sub-drawable to this one.
  31167. This passes in a Drawable pointer for this object to look after. To add a copy
  31168. of a drawable, use the form of this method that takes a Drawable reference instead.
  31169. @param drawable the object to add - this will be deleted automatically
  31170. when no longer needed, so the caller mustn't keep any
  31171. pointers to it.
  31172. @param transform the transform to apply to this drawable when it's being
  31173. drawn
  31174. @param index where to insert it in the list of drawables. 0 is the back,
  31175. -1 is the front, or any value from 0 and getNumDrawables()
  31176. can be used
  31177. @see removeDrawable
  31178. */
  31179. void insertDrawable (Drawable* drawable,
  31180. const AffineTransform& transform = AffineTransform::identity,
  31181. const int index = -1);
  31182. /** Adds a new sub-drawable to this one.
  31183. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  31184. for this object to look after, use the form of this method that takes a Drawable
  31185. pointer instead.
  31186. @param drawable the object to add - an internal copy will be made of this object
  31187. @param transform the transform to apply to this drawable when it's being
  31188. drawn
  31189. @param index where to insert it in the list of drawables. 0 is the back,
  31190. -1 is the front, or any value from 0 and getNumDrawables()
  31191. can be used
  31192. @see removeDrawable
  31193. */
  31194. void insertDrawable (const Drawable& drawable,
  31195. const AffineTransform& transform = AffineTransform::identity,
  31196. const int index = -1);
  31197. /** Deletes one of the Drawable objects.
  31198. @param index the index of the drawable to delete, between 0
  31199. and (getNumDrawables() - 1).
  31200. @param deleteDrawable if this is true, the drawable that is removed will also
  31201. be deleted. If false, it'll just be removed.
  31202. @see insertDrawable, getNumDrawables
  31203. */
  31204. void removeDrawable (const int index, const bool deleteDrawable = true);
  31205. /** Returns the number of drawables contained inside this one.
  31206. @see getDrawable
  31207. */
  31208. int getNumDrawables() const throw() { return drawables.size(); }
  31209. /** Returns one of the drawables that are contained in this one.
  31210. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  31211. to find it.
  31212. The pointer returned is managed by this object and will be deleted when no longer
  31213. needed, so be careful what you do with it.
  31214. @see getNumDrawables
  31215. */
  31216. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  31217. /** Returns the transform that applies to one of the drawables that are contained in this one.
  31218. The pointer returned is managed by this object and will be deleted when no longer
  31219. needed, so be careful what you do with it.
  31220. @see getNumDrawables
  31221. */
  31222. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  31223. /** Brings one of the Drawables to the front.
  31224. @param index the index of the drawable to move, between 0
  31225. and (getNumDrawables() - 1).
  31226. @see insertDrawable, getNumDrawables
  31227. */
  31228. void bringToFront (const int index);
  31229. /** @internal */
  31230. void render (const Drawable::RenderingContext& context) const;
  31231. /** @internal */
  31232. void getBounds (float& x, float& y, float& width, float& height) const;
  31233. /** @internal */
  31234. bool hitTest (float x, float y) const;
  31235. /** @internal */
  31236. Drawable* createCopy() const;
  31237. /** @internal */
  31238. ValueTree createValueTree() const throw();
  31239. /** @internal */
  31240. static DrawableComposite* createFromValueTree (const ValueTree& tree) throw();
  31241. juce_UseDebuggingNewOperator
  31242. private:
  31243. OwnedArray <Drawable> drawables;
  31244. OwnedArray <AffineTransform> transforms;
  31245. DrawableComposite (const DrawableComposite&);
  31246. const DrawableComposite& operator= (const DrawableComposite&);
  31247. };
  31248. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  31249. /********* End of inlined file: juce_DrawableComposite.h *********/
  31250. #endif
  31251. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31252. /********* Start of inlined file: juce_DrawableImage.h *********/
  31253. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31254. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31255. /**
  31256. A drawable object which is a bitmap image.
  31257. @see Drawable
  31258. */
  31259. class JUCE_API DrawableImage : public Drawable
  31260. {
  31261. public:
  31262. DrawableImage();
  31263. /** Destructor. */
  31264. virtual ~DrawableImage();
  31265. /** Sets the image that this drawable will render.
  31266. An internal copy is made of the image passed-in. If you want to provide an
  31267. image that this object can take charge of without needing to create a copy,
  31268. use the other setImage() method.
  31269. */
  31270. void setImage (const Image& imageToCopy);
  31271. /** Sets the image that this drawable will render.
  31272. An internal copy of this will not be made, so the caller mustn't delete
  31273. the image while it's still being used by this object.
  31274. A good way to use this is with the ImageCache - if you create an image
  31275. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  31276. it'll be released neatly with its reference count being decreased.
  31277. @param imageToUse the image to render
  31278. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  31279. then the image will be deleted when this object no longer
  31280. needs it - unless the image was created by the ImageCache,
  31281. in which case it will be released with ImageCache::release().
  31282. */
  31283. void setImage (Image* imageToUse,
  31284. const bool releaseWhenNotNeeded);
  31285. /** Returns the current image. */
  31286. Image* getImage() const throw() { return image; }
  31287. /** Clears (and possibly deletes) the currently set image. */
  31288. void clearImage();
  31289. /** Sets the opacity to use when drawing the image. */
  31290. void setOpacity (const float newOpacity);
  31291. /** Returns the image's opacity. */
  31292. float getOpacity() const throw() { return opacity; }
  31293. /** Sets a colour to draw over the image's alpha channel.
  31294. By default this is transparent so isn't drawn, but if you set a non-transparent
  31295. colour here, then it will be overlaid on the image, using the image's alpha
  31296. channel as a mask.
  31297. This is handy for doing things like darkening or lightening an image by overlaying
  31298. it with semi-transparent black or white.
  31299. */
  31300. void setOverlayColour (const Colour& newOverlayColour);
  31301. /** Returns the overlay colour. */
  31302. const Colour& getOverlayColour() const throw() { return overlayColour; }
  31303. /** @internal */
  31304. void render (const Drawable::RenderingContext& context) const;
  31305. /** @internal */
  31306. void getBounds (float& x, float& y, float& width, float& height) const;
  31307. /** @internal */
  31308. bool hitTest (float x, float y) const;
  31309. /** @internal */
  31310. Drawable* createCopy() const;
  31311. /** @internal */
  31312. ValueTree createValueTree() const throw();
  31313. /** @internal */
  31314. static DrawableImage* createFromValueTree (const ValueTree& tree) throw();
  31315. juce_UseDebuggingNewOperator
  31316. private:
  31317. Image* image;
  31318. bool canDeleteImage;
  31319. float opacity;
  31320. Colour overlayColour;
  31321. DrawableImage (const DrawableImage&);
  31322. const DrawableImage& operator= (const DrawableImage&);
  31323. };
  31324. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31325. /********* End of inlined file: juce_DrawableImage.h *********/
  31326. #endif
  31327. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  31328. /********* Start of inlined file: juce_DrawableText.h *********/
  31329. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  31330. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  31331. /**
  31332. A drawable object which renders a line of text.
  31333. @see Drawable
  31334. */
  31335. class JUCE_API DrawableText : public Drawable
  31336. {
  31337. public:
  31338. /** Creates a DrawableText object. */
  31339. DrawableText();
  31340. /** Destructor. */
  31341. virtual ~DrawableText();
  31342. /** Sets the block of text to render */
  31343. void setText (const GlyphArrangement& newText);
  31344. /** Sets a single line of text to render.
  31345. This is a convenient method of adding a single line - for
  31346. more complex text, use the setText() that takes a
  31347. GlyphArrangement instead.
  31348. */
  31349. void setText (const String& newText, const Font& fontToUse);
  31350. /** Returns the text arrangement that was set with setText(). */
  31351. const GlyphArrangement& getText() const throw() { return text; }
  31352. /** Sets the colour of the text. */
  31353. void setColour (const Colour& newColour);
  31354. /** Returns the current text colour. */
  31355. const Colour& getColour() const throw() { return colour; }
  31356. /** @internal */
  31357. void render (const Drawable::RenderingContext& context) const;
  31358. /** @internal */
  31359. void getBounds (float& x, float& y, float& width, float& height) const;
  31360. /** @internal */
  31361. bool hitTest (float x, float y) const;
  31362. /** @internal */
  31363. Drawable* createCopy() const;
  31364. /** @internal */
  31365. ValueTree createValueTree() const throw();
  31366. /** @internal */
  31367. static DrawableText* createFromValueTree (const ValueTree& tree) throw();
  31368. juce_UseDebuggingNewOperator
  31369. private:
  31370. GlyphArrangement text;
  31371. Colour colour;
  31372. DrawableText (const DrawableText&);
  31373. const DrawableText& operator= (const DrawableText&);
  31374. };
  31375. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  31376. /********* End of inlined file: juce_DrawableText.h *********/
  31377. #endif
  31378. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  31379. /********* Start of inlined file: juce_DrawablePath.h *********/
  31380. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  31381. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  31382. /**
  31383. A drawable object which renders a filled or outlined shape.
  31384. @see Drawable
  31385. */
  31386. class JUCE_API DrawablePath : public Drawable
  31387. {
  31388. public:
  31389. /** Creates a DrawablePath.
  31390. */
  31391. DrawablePath();
  31392. /** Destructor. */
  31393. virtual ~DrawablePath();
  31394. /** Changes the path that will be drawn.
  31395. @see setFillColour, setStrokeType
  31396. */
  31397. void setPath (const Path& newPath) throw();
  31398. /** Returns the current path. */
  31399. const Path& getPath() const throw() { return path; }
  31400. /** Sets a fill type for the path.
  31401. This colour is used to fill the path - if you don't want the path to be
  31402. filled (e.g. if you're just drawing an outline), set this to a transparent
  31403. colour.
  31404. @see setPath, setStrokeFill
  31405. */
  31406. void setFill (const FillType& newFill) throw();
  31407. /** Returns the current fill type.
  31408. @see setFill
  31409. */
  31410. const FillType& getFill() const throw() { return mainFill; }
  31411. /** Sets the fill type with which the outline will be drawn.
  31412. @see setFill
  31413. */
  31414. void setStrokeFill (const FillType& newStrokeFill) throw();
  31415. /** Returns the current stroke fill.
  31416. @see setStrokeFill
  31417. */
  31418. const FillType& getStrokeFill() const throw() { return strokeFill; }
  31419. /** Changes the properties of the outline that will be drawn around the path.
  31420. If the stroke has 0 thickness, no stroke will be drawn.
  31421. @see setStrokeThickness, setStrokeColour
  31422. */
  31423. void setStrokeType (const PathStrokeType& newStrokeType) throw();
  31424. /** Changes the stroke thickness.
  31425. This is a shortcut for calling setStrokeType.
  31426. */
  31427. void setStrokeThickness (const float newThickness) throw();
  31428. /** Returns the current outline style. */
  31429. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  31430. /** @internal */
  31431. void render (const Drawable::RenderingContext& context) const;
  31432. /** @internal */
  31433. void getBounds (float& x, float& y, float& width, float& height) const;
  31434. /** @internal */
  31435. bool hitTest (float x, float y) const;
  31436. /** @internal */
  31437. Drawable* createCopy() const;
  31438. /** @internal */
  31439. ValueTree createValueTree() const throw();
  31440. /** @internal */
  31441. static DrawablePath* createFromValueTree (const ValueTree& tree) throw();
  31442. juce_UseDebuggingNewOperator
  31443. private:
  31444. Path path, stroke;
  31445. FillType mainFill, strokeFill;
  31446. PathStrokeType strokeType;
  31447. void updateOutline();
  31448. DrawablePath (const DrawablePath&);
  31449. const DrawablePath& operator= (const DrawablePath&);
  31450. };
  31451. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  31452. /********* End of inlined file: juce_DrawablePath.h *********/
  31453. #endif
  31454. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  31455. #endif
  31456. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  31457. #endif
  31458. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  31459. #endif
  31460. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  31461. #endif
  31462. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31463. /********* Start of inlined file: juce_ArrowButton.h *********/
  31464. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31465. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31466. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  31467. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31468. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31469. /**
  31470. An effect filter that adds a drop-shadow behind the image's content.
  31471. (This will only work on images/components that aren't opaque, of course).
  31472. When added to a component, this effect will draw a soft-edged
  31473. shadow based on what gets drawn inside it. The shadow will also
  31474. be applied to the component's children.
  31475. For speed, this doesn't use a proper gaussian blur, but cheats by
  31476. using a simple bilinear filter. If you need a really high-quality
  31477. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31478. @see Component::setComponentEffect
  31479. */
  31480. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31481. {
  31482. public:
  31483. /** Creates a default drop-shadow effect.
  31484. To customise the shadow's appearance, use the setShadowProperties()
  31485. method.
  31486. */
  31487. DropShadowEffect();
  31488. /** Destructor. */
  31489. ~DropShadowEffect();
  31490. /** Sets up parameters affecting the shadow's appearance.
  31491. @param newRadius the (approximate) radius of the blur used
  31492. @param newOpacity the opacity with which the shadow is rendered
  31493. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31494. component's contents
  31495. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31496. component's contents
  31497. */
  31498. void setShadowProperties (const float newRadius,
  31499. const float newOpacity,
  31500. const int newShadowOffsetX,
  31501. const int newShadowOffsetY);
  31502. /** @internal */
  31503. void applyEffect (Image& sourceImage, Graphics& destContext);
  31504. juce_UseDebuggingNewOperator
  31505. private:
  31506. int offsetX, offsetY;
  31507. float radius, opacity;
  31508. };
  31509. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31510. /********* End of inlined file: juce_DropShadowEffect.h *********/
  31511. /**
  31512. A button with an arrow in it.
  31513. @see Button
  31514. */
  31515. class JUCE_API ArrowButton : public Button
  31516. {
  31517. public:
  31518. /** Creates an ArrowButton.
  31519. @param buttonName the name to give the button
  31520. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31521. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31522. @param arrowColour the colour to use for the arrow
  31523. */
  31524. ArrowButton (const String& buttonName,
  31525. float arrowDirection,
  31526. const Colour& arrowColour);
  31527. /** Destructor. */
  31528. ~ArrowButton();
  31529. juce_UseDebuggingNewOperator
  31530. protected:
  31531. /** @internal */
  31532. void paintButton (Graphics& g,
  31533. bool isMouseOverButton,
  31534. bool isButtonDown);
  31535. /** @internal */
  31536. void buttonStateChanged();
  31537. private:
  31538. Colour colour;
  31539. DropShadowEffect shadow;
  31540. Path path;
  31541. int offset;
  31542. ArrowButton (const ArrowButton&);
  31543. const ArrowButton& operator= (const ArrowButton&);
  31544. };
  31545. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31546. /********* End of inlined file: juce_ArrowButton.h *********/
  31547. #endif
  31548. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31549. #endif
  31550. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31551. /********* Start of inlined file: juce_DrawableButton.h *********/
  31552. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31553. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31554. /**
  31555. A button that displays a Drawable.
  31556. Up to three Drawable objects can be given to this button, to represent the
  31557. 'normal', 'over' and 'down' states.
  31558. @see Button
  31559. */
  31560. class JUCE_API DrawableButton : public Button
  31561. {
  31562. public:
  31563. enum ButtonStyle
  31564. {
  31565. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  31566. ImageRaw, /**< The button will just display the images in their normal size and position.
  31567. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  31568. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  31569. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  31570. };
  31571. /** Creates a DrawableButton.
  31572. After creating one of these, use setImages() to specify the drawables to use.
  31573. @param buttonName the name to give the component
  31574. @param buttonStyle the layout to use
  31575. @see ButtonStyle, setButtonStyle, setImages
  31576. */
  31577. DrawableButton (const String& buttonName,
  31578. const ButtonStyle buttonStyle);
  31579. /** Destructor. */
  31580. ~DrawableButton();
  31581. /** Sets up the images to draw for the various button states.
  31582. The button will keep its own internal copies of these drawables.
  31583. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  31584. will be made of the object passed-in if it is non-zero.
  31585. @param overImage the thing to draw for the button's 'over' state - if this is
  31586. zero, the button's normal image will be used when the mouse is
  31587. over it. An internal copy will be made of the object passed-in
  31588. if it is non-zero.
  31589. @param downImage the thing to draw for the button's 'down' state - if this is
  31590. zero, the 'over' image will be used instead (or the normal image
  31591. as a last resort). An internal copy will be made of the object
  31592. passed-in if it is non-zero.
  31593. @param disabledImage an image to draw when the button is disabled. If this is zero,
  31594. the normal image will be drawn with a reduced opacity instead.
  31595. An internal copy will be made of the object passed-in if it is
  31596. non-zero.
  31597. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  31598. state is 'on'. If this is 0, the normal image is used instead
  31599. @param overImageOn same as the overImage, but this is used when the button's toggle
  31600. state is 'on'. If this is 0, the normalImageOn is drawn instead
  31601. @param downImageOn same as the downImage, but this is used when the button's toggle
  31602. state is 'on'. If this is 0, the overImageOn is drawn instead
  31603. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  31604. state is 'on'. If this is 0, the normal image will be drawn instead
  31605. with a reduced opacity
  31606. */
  31607. void setImages (const Drawable* normalImage,
  31608. const Drawable* overImage = 0,
  31609. const Drawable* downImage = 0,
  31610. const Drawable* disabledImage = 0,
  31611. const Drawable* normalImageOn = 0,
  31612. const Drawable* overImageOn = 0,
  31613. const Drawable* downImageOn = 0,
  31614. const Drawable* disabledImageOn = 0);
  31615. /** Changes the button's style.
  31616. @see ButtonStyle
  31617. */
  31618. void setButtonStyle (const ButtonStyle newStyle);
  31619. /** Changes the button's background colours.
  31620. The toggledOffColour is the colour to use when the button's toggle state
  31621. is off, and toggledOnColour when it's on.
  31622. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  31623. used to fill the background of the component.
  31624. For an ImageOnButtonBackground style, the colour is used to draw the
  31625. button's lozenge shape and exactly how the colour's used will depend
  31626. on the LookAndFeel.
  31627. */
  31628. void setBackgroundColours (const Colour& toggledOffColour,
  31629. const Colour& toggledOnColour);
  31630. /** Returns the current background colour being used.
  31631. @see setBackgroundColour
  31632. */
  31633. const Colour& getBackgroundColour() const throw();
  31634. /** Gives the button an optional amount of space around the edge of the drawable.
  31635. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  31636. ones on a button background. If the button is too small for the given gap, a
  31637. smaller gap will be used.
  31638. By default there's a gap of about 3 pixels.
  31639. */
  31640. void setEdgeIndent (const int numPixelsIndent);
  31641. /** Returns the image that the button is currently displaying. */
  31642. const Drawable* getCurrentImage() const throw();
  31643. const Drawable* getNormalImage() const throw();
  31644. const Drawable* getOverImage() const throw();
  31645. const Drawable* getDownImage() const throw();
  31646. juce_UseDebuggingNewOperator
  31647. protected:
  31648. /** @internal */
  31649. void paintButton (Graphics& g,
  31650. bool isMouseOverButton,
  31651. bool isButtonDown);
  31652. private:
  31653. ButtonStyle style;
  31654. Drawable* normalImage;
  31655. Drawable* overImage;
  31656. Drawable* downImage;
  31657. Drawable* disabledImage;
  31658. Drawable* normalImageOn;
  31659. Drawable* overImageOn;
  31660. Drawable* downImageOn;
  31661. Drawable* disabledImageOn;
  31662. Colour backgroundOff, backgroundOn;
  31663. int edgeIndent;
  31664. void deleteImages();
  31665. DrawableButton (const DrawableButton&);
  31666. const DrawableButton& operator= (const DrawableButton&);
  31667. };
  31668. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31669. /********* End of inlined file: juce_DrawableButton.h *********/
  31670. #endif
  31671. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31672. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  31673. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31674. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31675. /**
  31676. A button showing an underlined weblink, that will launch the link
  31677. when it's clicked.
  31678. @see Button
  31679. */
  31680. class JUCE_API HyperlinkButton : public Button
  31681. {
  31682. public:
  31683. /** Creates a HyperlinkButton.
  31684. @param linkText the text that will be displayed in the button - this is
  31685. also set as the Component's name, but the text can be
  31686. changed later with the Button::getButtonText() method
  31687. @param linkURL the URL to launch when the user clicks the button
  31688. */
  31689. HyperlinkButton (const String& linkText,
  31690. const URL& linkURL);
  31691. /** Destructor. */
  31692. ~HyperlinkButton();
  31693. /** Changes the font to use for the text.
  31694. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  31695. to match the size of the component.
  31696. */
  31697. void setFont (const Font& newFont,
  31698. const bool resizeToMatchComponentHeight,
  31699. const Justification& justificationType = Justification::horizontallyCentred);
  31700. /** A set of colour IDs to use to change the colour of various aspects of the link.
  31701. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31702. methods.
  31703. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31704. */
  31705. enum ColourIds
  31706. {
  31707. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  31708. };
  31709. /** Changes the URL that the button will trigger. */
  31710. void setURL (const URL& newURL) throw();
  31711. /** Returns the URL that the button will trigger. */
  31712. const URL& getURL() const throw() { return url; }
  31713. /** Resizes the button horizontally to fit snugly around the text.
  31714. This won't affect the button's height.
  31715. */
  31716. void changeWidthToFitText();
  31717. juce_UseDebuggingNewOperator
  31718. protected:
  31719. /** @internal */
  31720. void clicked();
  31721. /** @internal */
  31722. void colourChanged();
  31723. /** @internal */
  31724. void paintButton (Graphics& g,
  31725. bool isMouseOverButton,
  31726. bool isButtonDown);
  31727. private:
  31728. URL url;
  31729. Font font;
  31730. bool resizeFont;
  31731. Justification justification;
  31732. const Font getFontToUse() const;
  31733. HyperlinkButton (const HyperlinkButton&);
  31734. const HyperlinkButton& operator= (const HyperlinkButton&);
  31735. };
  31736. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31737. /********* End of inlined file: juce_HyperlinkButton.h *********/
  31738. #endif
  31739. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31740. /********* Start of inlined file: juce_ImageButton.h *********/
  31741. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31742. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  31743. /**
  31744. As the title suggests, this is a button containing an image.
  31745. The colour and transparency of the image can be set to vary when the
  31746. button state changes.
  31747. @see Button, ShapeButton, TextButton
  31748. */
  31749. class JUCE_API ImageButton : public Button
  31750. {
  31751. public:
  31752. /** Creates an ImageButton.
  31753. Use setImage() to specify the image to use. The colours and opacities that
  31754. are specified here can be changed later using setDrawingOptions().
  31755. @param name the name to give the component
  31756. */
  31757. ImageButton (const String& name);
  31758. /** Destructor. */
  31759. ~ImageButton();
  31760. /** Sets up the images to draw in various states.
  31761. Important! Bear in mind that if you pass the same image in for more than one of
  31762. these parameters, this button will delete it (or release from the ImageCache)
  31763. multiple times!
  31764. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  31765. resized to the same dimensions as the normal image
  31766. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  31767. button when the button's size changes
  31768. @param preserveImageProportions if true then any rescaling of the image to fit
  31769. the button will keep the image's x and y proportions
  31770. correct - i.e. it won't distort its shape, although
  31771. this might create gaps around the edges
  31772. @param normalImage the image to use when the button is in its normal state. The
  31773. image passed in will be deleted (or released if it
  31774. was created by the ImageCache class) when the
  31775. button no longer needs it.
  31776. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  31777. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  31778. normal image - if this colour is transparent, no overlay
  31779. will be drawn. The overlay will be drawn over the top of the
  31780. image, so you can basically add a solid or semi-transparent
  31781. colour to the image to brighten or darken it
  31782. @param overImage the image to use when the mouse is over the button. If
  31783. you want to use the same image as was set in the normalImage
  31784. parameter, this value can be 0. As for normalImage, it
  31785. will be deleted or released by the button when no longer
  31786. needed
  31787. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  31788. is over the button
  31789. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  31790. image when the mouse is over - if this colour is transparent,
  31791. no overlay will be drawn
  31792. @param downImage an image to use when the button is pressed down. If set
  31793. to zero, the 'over' image will be drawn instead (or the
  31794. normal image if there isn't an 'over' image either). This
  31795. image will be deleted or released by the button when no
  31796. longer needed
  31797. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  31798. is pressed
  31799. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  31800. image when the button is pressed down - if this colour is
  31801. transparent, no overlay will be drawn
  31802. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  31803. whenever it's inside the button's bounding rectangle. If
  31804. set to values higher than 0, the mouse will only be
  31805. considered to be over the image when the value of the
  31806. image's alpha channel at that position is greater than
  31807. this level.
  31808. */
  31809. void setImages (const bool resizeButtonNowToFitThisImage,
  31810. const bool rescaleImagesWhenButtonSizeChanges,
  31811. const bool preserveImageProportions,
  31812. Image* const normalImage,
  31813. const float imageOpacityWhenNormal,
  31814. const Colour& overlayColourWhenNormal,
  31815. Image* const overImage,
  31816. const float imageOpacityWhenOver,
  31817. const Colour& overlayColourWhenOver,
  31818. Image* const downImage,
  31819. const float imageOpacityWhenDown,
  31820. const Colour& overlayColourWhenDown,
  31821. const float hitTestAlphaThreshold = 0.0f);
  31822. /** Returns the currently set 'normal' image. */
  31823. Image* getNormalImage() const throw();
  31824. /** Returns the image that's drawn when the mouse is over the button.
  31825. If an 'over' image has been set, this will return it; otherwise it'll
  31826. just return the normal image.
  31827. */
  31828. Image* getOverImage() const throw();
  31829. /** Returns the image that's drawn when the button is held down.
  31830. If a 'down' image has been set, this will return it; otherwise it'll
  31831. return the 'over' image or normal image, depending on what's available.
  31832. */
  31833. Image* getDownImage() const throw();
  31834. juce_UseDebuggingNewOperator
  31835. protected:
  31836. /** @internal */
  31837. bool hitTest (int x, int y);
  31838. /** @internal */
  31839. void paintButton (Graphics& g,
  31840. bool isMouseOverButton,
  31841. bool isButtonDown);
  31842. private:
  31843. bool scaleImageToFit, preserveProportions;
  31844. unsigned char alphaThreshold;
  31845. int imageX, imageY, imageW, imageH;
  31846. Image* normalImage;
  31847. Image* overImage;
  31848. Image* downImage;
  31849. float normalOpacity, overOpacity, downOpacity;
  31850. Colour normalOverlay, overOverlay, downOverlay;
  31851. Image* getCurrentImage() const;
  31852. void deleteImages();
  31853. ImageButton (const ImageButton&);
  31854. const ImageButton& operator= (const ImageButton&);
  31855. };
  31856. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  31857. /********* End of inlined file: juce_ImageButton.h *********/
  31858. #endif
  31859. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31860. /********* Start of inlined file: juce_ShapeButton.h *********/
  31861. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31862. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  31863. /**
  31864. A button that contains a filled shape.
  31865. @see Button, ImageButton, TextButton, ArrowButton
  31866. */
  31867. class JUCE_API ShapeButton : public Button
  31868. {
  31869. public:
  31870. /** Creates a ShapeButton.
  31871. @param name a name to give the component - see Component::setName()
  31872. @param normalColour the colour to fill the shape with when the mouse isn't over
  31873. @param overColour the colour to use when the mouse is over the shape
  31874. @param downColour the colour to use when the button is in the pressed-down state
  31875. */
  31876. ShapeButton (const String& name,
  31877. const Colour& normalColour,
  31878. const Colour& overColour,
  31879. const Colour& downColour);
  31880. /** Destructor. */
  31881. ~ShapeButton();
  31882. /** Sets the shape to use.
  31883. @param newShape the shape to use
  31884. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  31885. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  31886. the button is resized
  31887. @param hasDropShadow if true, the button will be given a drop-shadow effect
  31888. */
  31889. void setShape (const Path& newShape,
  31890. const bool resizeNowToFitThisShape,
  31891. const bool maintainShapeProportions,
  31892. const bool hasDropShadow);
  31893. /** Set the colours to use for drawing the shape.
  31894. @param normalColour the colour to fill the shape with when the mouse isn't over
  31895. @param overColour the colour to use when the mouse is over the shape
  31896. @param downColour the colour to use when the button is in the pressed-down state
  31897. */
  31898. void setColours (const Colour& normalColour,
  31899. const Colour& overColour,
  31900. const Colour& downColour);
  31901. /** Sets up an outline to draw around the shape.
  31902. @param outlineColour the colour to use
  31903. @param outlineStrokeWidth the thickness of line to draw
  31904. */
  31905. void setOutline (const Colour& outlineColour,
  31906. const float outlineStrokeWidth);
  31907. juce_UseDebuggingNewOperator
  31908. protected:
  31909. /** @internal */
  31910. void paintButton (Graphics& g,
  31911. bool isMouseOverButton,
  31912. bool isButtonDown);
  31913. private:
  31914. Colour normalColour, overColour, downColour, outlineColour;
  31915. DropShadowEffect shadow;
  31916. Path shape;
  31917. bool maintainShapeProportions;
  31918. float outlineWidth;
  31919. ShapeButton (const ShapeButton&);
  31920. const ShapeButton& operator= (const ShapeButton&);
  31921. };
  31922. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31923. /********* End of inlined file: juce_ShapeButton.h *********/
  31924. #endif
  31925. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31926. #endif
  31927. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31928. /********* Start of inlined file: juce_ToggleButton.h *********/
  31929. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31930. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31931. /**
  31932. A button that can be toggled on/off.
  31933. All buttons can be toggle buttons, but this lets you create one of the
  31934. standard ones which has a tick-box and a text label next to it.
  31935. @see Button, DrawableButton, TextButton
  31936. */
  31937. class JUCE_API ToggleButton : public Button
  31938. {
  31939. public:
  31940. /** Creates a ToggleButton.
  31941. @param buttonText the text to put in the button (the component's name is also
  31942. initially set to this string, but these can be changed later
  31943. using the setName() and setButtonText() methods)
  31944. */
  31945. ToggleButton (const String& buttonText);
  31946. /** Destructor. */
  31947. ~ToggleButton();
  31948. /** Resizes the button to fit neatly around its current text.
  31949. The button's height won't be affected, only its width.
  31950. */
  31951. void changeWidthToFitText();
  31952. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31953. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31954. methods.
  31955. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31956. */
  31957. enum ColourIds
  31958. {
  31959. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31960. };
  31961. juce_UseDebuggingNewOperator
  31962. protected:
  31963. /** @internal */
  31964. void paintButton (Graphics& g,
  31965. bool isMouseOverButton,
  31966. bool isButtonDown);
  31967. /** @internal */
  31968. void colourChanged();
  31969. private:
  31970. ToggleButton (const ToggleButton&);
  31971. const ToggleButton& operator= (const ToggleButton&);
  31972. };
  31973. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31974. /********* End of inlined file: juce_ToggleButton.h *********/
  31975. #endif
  31976. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31977. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31978. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31979. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31980. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31981. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31982. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31983. /********* Start of inlined file: juce_Toolbar.h *********/
  31984. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31985. #define __JUCE_TOOLBAR_JUCEHEADER__
  31986. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31987. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31988. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31989. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31990. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31991. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31992. /**
  31993. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31994. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31995. derive your component from this class, and make sure that it is somewhere inside a
  31996. DragAndDropContainer component.
  31997. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31998. the operating system onto your component, you don't need any of these classes: instead
  31999. see the FileDragAndDropTarget class.
  32000. @see DragAndDropContainer, FileDragAndDropTarget
  32001. */
  32002. class JUCE_API DragAndDropTarget
  32003. {
  32004. public:
  32005. /** Destructor. */
  32006. virtual ~DragAndDropTarget() {}
  32007. /** Callback to check whether this target is interested in the type of object being
  32008. dragged.
  32009. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32010. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32011. @returns true if this component wants to receive the other callbacks regarging this
  32012. type of object; if it returns false, no other callbacks will be made.
  32013. */
  32014. virtual bool isInterestedInDragSource (const String& sourceDescription,
  32015. Component* sourceComponent) = 0;
  32016. /** Callback to indicate that something is being dragged over this component.
  32017. This gets called when the user moves the mouse into this component while dragging
  32018. something.
  32019. Use this callback as a trigger to make your component repaint itself to give the
  32020. user feedback about whether the item can be dropped here or not.
  32021. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32022. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32023. @param x the mouse x position, relative to this component
  32024. @param y the mouse y position, relative to this component
  32025. @see itemDragExit
  32026. */
  32027. virtual void itemDragEnter (const String& sourceDescription,
  32028. Component* sourceComponent,
  32029. int x,
  32030. int y);
  32031. /** Callback to indicate that the user is dragging something over this component.
  32032. This gets called when the user moves the mouse over this component while dragging
  32033. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32034. this lets you know what happens in-between.
  32035. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32036. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32037. @param x the mouse x position, relative to this component
  32038. @param y the mouse y position, relative to this component
  32039. */
  32040. virtual void itemDragMove (const String& sourceDescription,
  32041. Component* sourceComponent,
  32042. int x,
  32043. int y);
  32044. /** Callback to indicate that something has been dragged off the edge of this component.
  32045. This gets called when the user moves the mouse out of this component while dragging
  32046. something.
  32047. If you've used itemDragEnter() to repaint your component and give feedback, use this
  32048. as a signal to repaint it in its normal state.
  32049. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32050. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32051. @see itemDragEnter
  32052. */
  32053. virtual void itemDragExit (const String& sourceDescription,
  32054. Component* sourceComponent);
  32055. /** Callback to indicate that the user has dropped something onto this component.
  32056. When the user drops an item this get called, and you can use the description to
  32057. work out whether your object wants to deal with it or not.
  32058. Note that after this is called, the itemDragExit method may not be called, so you should
  32059. clean up in here if there's anything you need to do when the drag finishes.
  32060. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32061. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32062. @param x the mouse x position, relative to this component
  32063. @param y the mouse y position, relative to this component
  32064. */
  32065. virtual void itemDropped (const String& sourceDescription,
  32066. Component* sourceComponent,
  32067. int x,
  32068. int y) = 0;
  32069. /** Overriding this allows the target to tell the drag container whether to
  32070. draw the drag image while the cursor is over it.
  32071. By default it returns true, but if you return false, then the normal drag
  32072. image will not be shown when the cursor is over this target.
  32073. */
  32074. virtual bool shouldDrawDragImageWhenOver();
  32075. };
  32076. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32077. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  32078. /**
  32079. Enables drag-and-drop behaviour for a component and all its sub-components.
  32080. For a component to be able to make or receive drag-and-drop events, one of its parent
  32081. components must derive from this class. It's probably best for the top-level
  32082. component to implement it.
  32083. Then to start a drag operation, any sub-component can just call the startDragging()
  32084. method, and this object will take over, tracking the mouse and sending appropriate
  32085. callbacks to any child components derived from DragAndDropTarget which the mouse
  32086. moves over.
  32087. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32088. the operating system onto your component, you don't need any of these classes: you can do this
  32089. simply by overriding Component::filesDropped().
  32090. @see DragAndDropTarget
  32091. */
  32092. class JUCE_API DragAndDropContainer
  32093. {
  32094. public:
  32095. /** Creates a DragAndDropContainer.
  32096. The object that derives from this class must also be a Component.
  32097. */
  32098. DragAndDropContainer();
  32099. /** Destructor. */
  32100. virtual ~DragAndDropContainer();
  32101. /** Begins a drag-and-drop operation.
  32102. This starts a drag-and-drop operation - call it when the user drags the
  32103. mouse in your drag-source component, and this object will track mouse
  32104. movements until the user lets go of the mouse button, and will send
  32105. appropriate messages to DragAndDropTarget objects that the mouse moves
  32106. over.
  32107. findParentDragContainerFor() is a handy method to call to find the
  32108. drag container to use for a component.
  32109. @param sourceDescription a string to use as the description of the thing being
  32110. dragged - this will be passed to the objects that might be
  32111. dropped-onto so they can decide if they want to handle it or
  32112. not
  32113. @param sourceComponent the component that is being dragged
  32114. @param dragImage the image to drag around underneath the mouse. If this is
  32115. zero, a snapshot of the sourceComponent will be used instead. An
  32116. image passed-in will be deleted by this object when no longer
  32117. needed.
  32118. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  32119. window, and can be dragged to DragAndDropTargets that are the
  32120. children of components other than this one.
  32121. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  32122. at which the image should be drawn from the mouse. If it isn't
  32123. specified, then the image will be centred around the mouse. If
  32124. an image hasn't been passed-in, this will be ignored.
  32125. */
  32126. void startDragging (const String& sourceDescription,
  32127. Component* sourceComponent,
  32128. Image* dragImage = 0,
  32129. const bool allowDraggingToOtherJuceWindows = false,
  32130. const Point* imageOffsetFromMouse = 0);
  32131. /** Returns true if something is currently being dragged. */
  32132. bool isDragAndDropActive() const;
  32133. /** Returns the description of the thing that's currently being dragged.
  32134. If nothing's being dragged, this will return an empty string, otherwise it's the
  32135. string that was passed into startDragging().
  32136. @see startDragging
  32137. */
  32138. const String getCurrentDragDescription() const;
  32139. /** Utility to find the DragAndDropContainer for a given Component.
  32140. This will search up this component's parent hierarchy looking for the first
  32141. parent component which is a DragAndDropContainer.
  32142. It's useful when a component wants to call startDragging but doesn't know
  32143. the DragAndDropContainer it should to use.
  32144. Obviously this may return 0 if it doesn't find a suitable component.
  32145. */
  32146. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  32147. /** This performs a synchronous drag-and-drop of a set of files to some external
  32148. application.
  32149. You can call this function in response to a mouseDrag callback, and it will
  32150. block, running its own internal message loop and tracking the mouse, while it
  32151. uses a native operating system drag-and-drop operation to move or copy some
  32152. files to another application.
  32153. @param files a list of filenames to drag
  32154. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  32155. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  32156. @returns true if the files were successfully dropped somewhere, or false if it
  32157. was interrupted
  32158. @see performExternalDragDropOfText
  32159. */
  32160. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  32161. /** This performs a synchronous drag-and-drop of a block of text to some external
  32162. application.
  32163. You can call this function in response to a mouseDrag callback, and it will
  32164. block, running its own internal message loop and tracking the mouse, while it
  32165. uses a native operating system drag-and-drop operation to move or copy some
  32166. text to another application.
  32167. @param text the text to copy
  32168. @returns true if the text was successfully dropped somewhere, or false if it
  32169. was interrupted
  32170. @see performExternalDragDropOfFiles
  32171. */
  32172. static bool performExternalDragDropOfText (const String& text);
  32173. juce_UseDebuggingNewOperator
  32174. protected:
  32175. /** Override this if you want to be able to perform an external drag a set of files
  32176. when the user drags outside of this container component.
  32177. This method will be called when a drag operation moves outside the Juce-based window,
  32178. and if you want it to then perform a file drag-and-drop, add the filenames you want
  32179. to the array passed in, and return true.
  32180. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  32181. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  32182. @param files on return, the filenames you want to drag
  32183. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  32184. it must make a copy of them (see the performExternalDragDropOfFiles()
  32185. method)
  32186. @see performExternalDragDropOfFiles
  32187. */
  32188. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  32189. Component* dragSourceComponent,
  32190. StringArray& files,
  32191. bool& canMoveFiles);
  32192. private:
  32193. friend class DragImageComponent;
  32194. Component* dragImageComponent;
  32195. String currentDragDesc;
  32196. };
  32197. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32198. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  32199. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  32200. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32201. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32202. /**
  32203. Animates a set of components, moving it to a new position.
  32204. To use this, create a ComponentAnimator, and use its animateComponent() method
  32205. to tell it to move components to destination positions. Any number of
  32206. components can be animated by one ComponentAnimator object (if you've got a
  32207. lot of components to move, it's much more efficient to share a single animator
  32208. than to have many animators running at once).
  32209. You'll need to make sure the animator object isn't deleted before it finishes
  32210. moving the components.
  32211. The class is a ChangeBroadcaster and sends a notification when any components
  32212. start or finish being animated.
  32213. */
  32214. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  32215. private Timer
  32216. {
  32217. public:
  32218. /** Creates a ComponentAnimator. */
  32219. ComponentAnimator();
  32220. /** Destructor. */
  32221. ~ComponentAnimator();
  32222. /** Starts a component moving from its current position to a specified position.
  32223. If the component is already in the middle of an animation, that will be abandoned,
  32224. and a new animation will begin, moving the component from its current location.
  32225. The start and end speed parameters let you apply some acceleration to the component's
  32226. movement.
  32227. @param component the component to move
  32228. @param finalPosition the destination position and size to move it to
  32229. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  32230. to arrive at its destination
  32231. @param startSpeed a value to indicate the relative start speed of the
  32232. animation. If this is 0, the component will start
  32233. by accelerating from rest; higher values mean that it
  32234. will have an initial speed greater than zero. If the
  32235. value if greater than 1, it will decelerate towards the
  32236. middle of its journey. To move the component at a constant
  32237. rate for its entire animation, set both the start and
  32238. end speeds to 1.0
  32239. @param endSpeed a relative speed at which the component should be moving
  32240. when the animation finishes. If this is 0, the component
  32241. will decelerate to a standstill at its final position; higher
  32242. values mean the component will still be moving when it stops.
  32243. To move the component at a constant rate for its entire
  32244. animation, set both the start and end speeds to 1.0
  32245. */
  32246. void animateComponent (Component* const component,
  32247. const Rectangle& finalPosition,
  32248. const int millisecondsToSpendMoving,
  32249. const double startSpeed = 1.0,
  32250. const double endSpeed = 1.0);
  32251. /** Stops a component if it's currently being animated.
  32252. If moveComponentToItsFinalPosition is true, then the component will
  32253. be immediately moved to its destination position and size. If false, it will be
  32254. left in whatever location it currently occupies.
  32255. */
  32256. void cancelAnimation (Component* const component,
  32257. const bool moveComponentToItsFinalPosition);
  32258. /** Clears all of the active animations.
  32259. If moveComponentsToTheirFinalPositions is true, all the components will
  32260. be immediately set to their final positions. If false, they will be
  32261. left in whatever locations they currently occupy.
  32262. */
  32263. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  32264. /** Returns the destination position for a component.
  32265. If the component is being animated, this will return the target position that
  32266. was specified when animateComponent() was called.
  32267. If the specified component isn't currently being animated, this method will just
  32268. return its current position.
  32269. */
  32270. const Rectangle getComponentDestination (Component* const component);
  32271. /** Returns true if the specified component is currently being animated.
  32272. */
  32273. bool isAnimating (Component* component) const;
  32274. juce_UseDebuggingNewOperator
  32275. private:
  32276. VoidArray tasks;
  32277. uint32 lastTime;
  32278. void* findTaskFor (Component* const component) const;
  32279. void timerCallback();
  32280. };
  32281. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32282. /********* End of inlined file: juce_ComponentAnimator.h *********/
  32283. class ToolbarItemComponent;
  32284. class ToolbarItemFactory;
  32285. class MissingItemsComponent;
  32286. /**
  32287. A toolbar component.
  32288. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  32289. and looks after their order and layout.
  32290. Items (icon buttons or other custom components) are added to a toolbar using a
  32291. ToolbarItemFactory - each type of item is given a unique ID number, and a
  32292. toolbar might contain more than one instance of a particular item type.
  32293. Toolbars can be interactively customised, allowing the user to drag the items
  32294. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  32295. component as a source of new items.
  32296. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  32297. */
  32298. class JUCE_API Toolbar : public Component,
  32299. public DragAndDropContainer,
  32300. public DragAndDropTarget,
  32301. private ButtonListener
  32302. {
  32303. public:
  32304. /** Creates an empty toolbar component.
  32305. To add some icons or other components to your toolbar, you'll need to
  32306. create a ToolbarItemFactory class that can create a suitable set of
  32307. ToolbarItemComponents.
  32308. @see ToolbarItemFactory, ToolbarItemComponents
  32309. */
  32310. Toolbar();
  32311. /** Destructor.
  32312. Any items on the bar will be deleted when the toolbar is deleted.
  32313. */
  32314. ~Toolbar();
  32315. /** Changes the bar's orientation.
  32316. @see isVertical
  32317. */
  32318. void setVertical (const bool shouldBeVertical);
  32319. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  32320. You can change the bar's orientation with setVertical().
  32321. */
  32322. bool isVertical() const throw() { return vertical; }
  32323. /** Returns the depth of the bar.
  32324. If the bar is horizontal, this will return its height; if it's vertical, it
  32325. will return its width.
  32326. @see getLength
  32327. */
  32328. int getThickness() const throw();
  32329. /** Returns the length of the bar.
  32330. If the bar is horizontal, this will return its width; if it's vertical, it
  32331. will return its height.
  32332. @see getThickness
  32333. */
  32334. int getLength() const throw();
  32335. /** Deletes all items from the bar.
  32336. */
  32337. void clear();
  32338. /** Adds an item to the toolbar.
  32339. The factory's ToolbarItemFactory::createItem() will be called by this method
  32340. to create the component that will actually be added to the bar.
  32341. The new item will be inserted at the specified index (if the index is -1, it
  32342. will be added to the right-hand or bottom end of the bar).
  32343. Once added, the component will be automatically deleted by this object when it
  32344. is no longer needed.
  32345. @see ToolbarItemFactory
  32346. */
  32347. void addItem (ToolbarItemFactory& factory,
  32348. const int itemId,
  32349. const int insertIndex = -1);
  32350. /** Deletes one of the items from the bar.
  32351. */
  32352. void removeToolbarItem (const int itemIndex);
  32353. /** Returns the number of items currently on the toolbar.
  32354. @see getItemId, getItemComponent
  32355. */
  32356. int getNumItems() const throw();
  32357. /** Returns the ID of the item with the given index.
  32358. If the index is less than zero or greater than the number of items,
  32359. this will return 0.
  32360. @see getNumItems
  32361. */
  32362. int getItemId (const int itemIndex) const throw();
  32363. /** Returns the component being used for the item with the given index.
  32364. If the index is less than zero or greater than the number of items,
  32365. this will return 0.
  32366. @see getNumItems
  32367. */
  32368. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  32369. /** Clears this toolbar and adds to it the default set of items that the specified
  32370. factory creates.
  32371. @see ToolbarItemFactory::getDefaultItemSet
  32372. */
  32373. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  32374. /** Options for the way items should be displayed.
  32375. @see setStyle, getStyle
  32376. */
  32377. enum ToolbarItemStyle
  32378. {
  32379. iconsOnly, /**< Means that the toolbar should just contain icons. */
  32380. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  32381. textOnly /**< Means that the toolbar only display text labels for each item. */
  32382. };
  32383. /** Returns the toolbar's current style.
  32384. @see ToolbarItemStyle, setStyle
  32385. */
  32386. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32387. /** Changes the toolbar's current style.
  32388. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  32389. */
  32390. void setStyle (const ToolbarItemStyle& newStyle);
  32391. /** Flags used by the showCustomisationDialog() method. */
  32392. enum CustomisationFlags
  32393. {
  32394. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  32395. show the "icons only" option on its choice of toolbar styles. */
  32396. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  32397. show the "icons with text" option on its choice of toolbar styles. */
  32398. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  32399. show the "text only" option on its choice of toolbar styles. */
  32400. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  32401. show a button to reset the toolbar to its default set of items. */
  32402. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  32403. };
  32404. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  32405. The dialog contains a ToolbarItemPalette and various controls for editing other
  32406. aspects of the toolbar. This method will block and run the dialog box modally,
  32407. returning when the user closes it.
  32408. The factory is used to determine the set of items that will be shown on the
  32409. palette.
  32410. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  32411. enum.
  32412. @see ToolbarItemPalette
  32413. */
  32414. void showCustomisationDialog (ToolbarItemFactory& factory,
  32415. const int optionFlags = allCustomisationOptionsEnabled);
  32416. /** Turns on or off the toolbar's editing mode, in which its items can be
  32417. rearranged by the user.
  32418. (In most cases it's easier just to use showCustomisationDialog() instead of
  32419. trying to enable editing directly).
  32420. @see ToolbarItemPalette
  32421. */
  32422. void setEditingActive (const bool editingEnabled);
  32423. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  32424. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32425. methods.
  32426. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32427. */
  32428. enum ColourIds
  32429. {
  32430. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  32431. more control over this, override LookAndFeel::paintToolbarBackground(). */
  32432. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  32433. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  32434. over them. */
  32435. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  32436. held down on them. */
  32437. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  32438. when the style is set to iconsWithText or textOnly. */
  32439. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  32440. the customisation dialog is active and the mouse moves over them. */
  32441. };
  32442. /** Returns a string that represents the toolbar's current set of items.
  32443. This lets you later restore the same item layout using restoreFromString().
  32444. @see restoreFromString
  32445. */
  32446. const String toString() const;
  32447. /** Restores a set of items that was previously stored in a string by the toString()
  32448. method.
  32449. The factory object is used to create any item components that are needed.
  32450. @see toString
  32451. */
  32452. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  32453. const String& savedVersion);
  32454. /** @internal */
  32455. void paint (Graphics& g);
  32456. /** @internal */
  32457. void resized();
  32458. /** @internal */
  32459. void buttonClicked (Button*);
  32460. /** @internal */
  32461. void mouseDown (const MouseEvent&);
  32462. /** @internal */
  32463. bool isInterestedInDragSource (const String&, Component*);
  32464. /** @internal */
  32465. void itemDragMove (const String&, Component*, int, int);
  32466. /** @internal */
  32467. void itemDragExit (const String&, Component*);
  32468. /** @internal */
  32469. void itemDropped (const String&, Component*, int, int);
  32470. /** @internal */
  32471. void updateAllItemPositions (const bool animate);
  32472. /** @internal */
  32473. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  32474. juce_UseDebuggingNewOperator
  32475. private:
  32476. Button* missingItemsButton;
  32477. bool vertical, isEditingActive;
  32478. ToolbarItemStyle toolbarStyle;
  32479. ComponentAnimator animator;
  32480. friend class MissingItemsComponent;
  32481. Array <ToolbarItemComponent*> items;
  32482. friend class ItemDragAndDropOverlayComponent;
  32483. static const tchar* const toolbarDragDescriptor;
  32484. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  32485. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  32486. Toolbar (const Toolbar&);
  32487. const Toolbar& operator= (const Toolbar&);
  32488. };
  32489. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  32490. /********* End of inlined file: juce_Toolbar.h *********/
  32491. class ItemDragAndDropOverlayComponent;
  32492. /**
  32493. A component that can be used as one of the items in a Toolbar.
  32494. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  32495. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  32496. class for further info about creating them.
  32497. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  32498. components too. To do this, set the value of isBeingUsedAsAButton to false when
  32499. calling the constructor, and override contentAreaChanged(), in which you can position
  32500. any sub-components you need to add.
  32501. To add basic buttons without writing a special subclass, have a look at the
  32502. ToolbarButton class.
  32503. @see ToolbarButton, Toolbar, ToolbarItemFactory
  32504. */
  32505. class JUCE_API ToolbarItemComponent : public Button
  32506. {
  32507. public:
  32508. /** Constructor.
  32509. @param itemId the ID of the type of toolbar item which this represents
  32510. @param labelText the text to display if the toolbar's style is set to
  32511. Toolbar::iconsWithText or Toolbar::textOnly
  32512. @param isBeingUsedAsAButton set this to false if you don't want the button
  32513. to draw itself with button over/down states when the mouse
  32514. moves over it or clicks
  32515. */
  32516. ToolbarItemComponent (const int itemId,
  32517. const String& labelText,
  32518. const bool isBeingUsedAsAButton);
  32519. /** Destructor. */
  32520. ~ToolbarItemComponent();
  32521. /** Returns the item type ID that this component represents.
  32522. This value is in the constructor.
  32523. */
  32524. int getItemId() const throw() { return itemId; }
  32525. /** Returns the toolbar that contains this component, or 0 if it's not currently
  32526. inside one.
  32527. */
  32528. Toolbar* getToolbar() const;
  32529. /** Returns true if this component is currently inside a toolbar which is vertical.
  32530. @see Toolbar::isVertical
  32531. */
  32532. bool isToolbarVertical() const;
  32533. /** Returns the current style setting of this item.
  32534. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  32535. @see setStyle, Toolbar::getStyle
  32536. */
  32537. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32538. /** Changes the current style setting of this item.
  32539. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  32540. by the toolbar that holds this item.
  32541. @see setStyle, Toolbar::setStyle
  32542. */
  32543. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  32544. /** Returns the area of the component that should be used to display the button image or
  32545. other contents of the item.
  32546. This content area may change when the item's style changes, and may leave a space around the
  32547. edge of the component where the text label can be shown.
  32548. @see contentAreaChanged
  32549. */
  32550. const Rectangle getContentArea() const throw() { return contentArea; }
  32551. /** This method must return the size criteria for this item, based on a given toolbar
  32552. size and orientation.
  32553. The preferredSize, minSize and maxSize values must all be set by your implementation
  32554. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  32555. toolbar, they refer to the item's height.
  32556. The preferredSize is the size that the component would like to be, and this must be
  32557. between the min and max sizes. For a fixed-size item, simply set all three variables to
  32558. the same value.
  32559. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  32560. Toolbar::getThickness().
  32561. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  32562. vertically.
  32563. */
  32564. virtual bool getToolbarItemSizes (int toolbarThickness,
  32565. bool isToolbarVertical,
  32566. int& preferredSize,
  32567. int& minSize,
  32568. int& maxSize) = 0;
  32569. /** Your subclass should use this method to draw its content area.
  32570. The graphics object that is passed-in will have been clipped and had its origin
  32571. moved to fit the content area as specified get getContentArea(). The width and height
  32572. parameters are the width and height of the content area.
  32573. If the component you're writing isn't a button, you can just do nothing in this method.
  32574. */
  32575. virtual void paintButtonArea (Graphics& g,
  32576. int width, int height,
  32577. bool isMouseOver, bool isMouseDown) = 0;
  32578. /** Callback to indicate that the content area of this item has changed.
  32579. This might be because the component was resized, or because the style changed and
  32580. the space needed for the text label is different.
  32581. See getContentArea() for a description of what the area is.
  32582. */
  32583. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  32584. /** Editing modes.
  32585. These are used by setEditingMode(), but will be rarely needed in user code.
  32586. */
  32587. enum ToolbarEditingMode
  32588. {
  32589. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  32590. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  32591. customisation mode, and the items can be dragged around. */
  32592. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  32593. dragged onto a toolbar to add it to that bar.*/
  32594. };
  32595. /** Changes the editing mode of this component.
  32596. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32597. and is unlikely to be of much use in end-user-code.
  32598. */
  32599. void setEditingMode (const ToolbarEditingMode newMode);
  32600. /** Returns the current editing mode of this component.
  32601. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32602. and is unlikely to be of much use in end-user-code.
  32603. */
  32604. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  32605. /** @internal */
  32606. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  32607. /** @internal */
  32608. void resized();
  32609. juce_UseDebuggingNewOperator
  32610. private:
  32611. friend class Toolbar;
  32612. friend class ItemDragAndDropOverlayComponent;
  32613. const int itemId;
  32614. ToolbarEditingMode mode;
  32615. Toolbar::ToolbarItemStyle toolbarStyle;
  32616. Component* overlayComp;
  32617. int dragOffsetX, dragOffsetY;
  32618. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  32619. Rectangle contentArea;
  32620. ToolbarItemComponent (const ToolbarItemComponent&);
  32621. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  32622. };
  32623. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32624. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  32625. /**
  32626. A type of button designed to go on a toolbar.
  32627. This simple button can have two Drawable objects specified - one for normal
  32628. use and another one (optionally) for the button's "on" state if it's a
  32629. toggle button.
  32630. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  32631. */
  32632. class JUCE_API ToolbarButton : public ToolbarItemComponent
  32633. {
  32634. public:
  32635. /** Creates a ToolbarButton.
  32636. @param itemId the ID for this toolbar item type. This is passed through to the
  32637. ToolbarItemComponent constructor
  32638. @param labelText the text to display on the button (if the toolbar is using a style
  32639. that shows text labels). This is passed through to the
  32640. ToolbarItemComponent constructor
  32641. @param normalImage a drawable object that the button should use as its icon. The object
  32642. that is passed-in here will be kept by this object and will be
  32643. deleted when no longer needed or when this button is deleted.
  32644. @param toggledOnImage a drawable object that the button can use as its icon if the button
  32645. is in a toggled-on state (see the Button::getToggleState() method). If
  32646. 0 is passed-in here, then the normal image will be used instead, regardless
  32647. of the toggle state. The object that is passed-in here will be kept by
  32648. this object and will be deleted when no longer needed or when this button
  32649. is deleted.
  32650. */
  32651. ToolbarButton (const int itemId,
  32652. const String& labelText,
  32653. Drawable* const normalImage,
  32654. Drawable* const toggledOnImage);
  32655. /** Destructor. */
  32656. ~ToolbarButton();
  32657. /** @internal */
  32658. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  32659. int& minSize, int& maxSize);
  32660. /** @internal */
  32661. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  32662. /** @internal */
  32663. void contentAreaChanged (const Rectangle& newBounds);
  32664. juce_UseDebuggingNewOperator
  32665. private:
  32666. Drawable* const normalImage;
  32667. Drawable* const toggledOnImage;
  32668. ToolbarButton (const ToolbarButton&);
  32669. const ToolbarButton& operator= (const ToolbarButton&);
  32670. };
  32671. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32672. /********* End of inlined file: juce_ToolbarButton.h *********/
  32673. #endif
  32674. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32675. #endif
  32676. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32677. /********* Start of inlined file: juce_GlowEffect.h *********/
  32678. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32679. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  32680. /**
  32681. A component effect that adds a coloured blur around the component's contents.
  32682. (This will only work on non-opaque components).
  32683. @see Component::setComponentEffect, DropShadowEffect
  32684. */
  32685. class JUCE_API GlowEffect : public ImageEffectFilter
  32686. {
  32687. public:
  32688. /** Creates a default 'glow' effect.
  32689. To customise its appearance, use the setGlowProperties() method.
  32690. */
  32691. GlowEffect();
  32692. /** Destructor. */
  32693. ~GlowEffect();
  32694. /** Sets the glow's radius and colour.
  32695. The radius is how large the blur should be, and the colour is
  32696. used to render it (for a less intense glow, lower the colour's
  32697. opacity).
  32698. */
  32699. void setGlowProperties (const float newRadius,
  32700. const Colour& newColour);
  32701. /** @internal */
  32702. void applyEffect (Image& sourceImage, Graphics& destContext);
  32703. juce_UseDebuggingNewOperator
  32704. private:
  32705. float radius;
  32706. Colour colour;
  32707. };
  32708. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  32709. /********* End of inlined file: juce_GlowEffect.h *********/
  32710. #endif
  32711. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  32712. #endif
  32713. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32714. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  32715. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32716. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32717. /**
  32718. An effect filter that reduces the image's opacity.
  32719. This can be used to make a component (and its child components) more
  32720. transparent.
  32721. @see Component::setComponentEffect
  32722. */
  32723. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  32724. {
  32725. public:
  32726. /** Creates the effect object.
  32727. The opacity of the component to which the effect is applied will be
  32728. scaled by the given factor (in the range 0 to 1.0f).
  32729. */
  32730. ReduceOpacityEffect (const float opacity = 1.0f);
  32731. /** Destructor. */
  32732. ~ReduceOpacityEffect();
  32733. /** Sets how much to scale the component's opacity.
  32734. @param newOpacity should be between 0 and 1.0f
  32735. */
  32736. void setOpacity (const float newOpacity);
  32737. /** @internal */
  32738. void applyEffect (Image& sourceImage, Graphics& destContext);
  32739. juce_UseDebuggingNewOperator
  32740. private:
  32741. float opacity;
  32742. };
  32743. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32744. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  32745. #endif
  32746. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  32747. #endif
  32748. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32749. #endif
  32750. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32751. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  32752. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32753. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32754. /**
  32755. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  32756. command in a ApplicationCommandManager.
  32757. Normally, you won't actually create a KeyPressMappingSet directly, because
  32758. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  32759. you'd create yourself an ApplicationCommandManager, and call its
  32760. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  32761. KeyPressMappingSet.
  32762. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  32763. to the top-level component for which you want to handle keystrokes. So for example:
  32764. @code
  32765. class MyMainWindow : public Component
  32766. {
  32767. ApplicationCommandManager* myCommandManager;
  32768. public:
  32769. MyMainWindow()
  32770. {
  32771. myCommandManager = new ApplicationCommandManager();
  32772. // first, make sure the command manager has registered all the commands that its
  32773. // targets can perform..
  32774. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  32775. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  32776. // this will use the command manager to initialise the KeyPressMappingSet with
  32777. // the default keypresses that were specified when the targets added their commands
  32778. // to the manager.
  32779. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  32780. // having set up the default key-mappings, you might now want to load the last set
  32781. // of mappings that the user configured.
  32782. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  32783. // Now tell our top-level window to send any keypresses that arrive to the
  32784. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  32785. addKeyListener (myCommandManager->getKeyMappings());
  32786. }
  32787. ...
  32788. }
  32789. @endcode
  32790. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  32791. register to be told when a command or mapping is added, removed, etc.
  32792. There's also a UI component called KeyMappingEditorComponent that can be used
  32793. to easily edit the key mappings.
  32794. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  32795. */
  32796. class JUCE_API KeyPressMappingSet : public KeyListener,
  32797. public ChangeBroadcaster,
  32798. public FocusChangeListener
  32799. {
  32800. public:
  32801. /** Creates a KeyPressMappingSet for a given command manager.
  32802. Normally, you won't actually create a KeyPressMappingSet directly, because
  32803. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  32804. best thing to do is to create your ApplicationCommandManager, and use the
  32805. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  32806. When a suitable keypress happens, the manager's invoke() method will be
  32807. used to invoke the appropriate command.
  32808. @see ApplicationCommandManager
  32809. */
  32810. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  32811. /** Creates an copy of a KeyPressMappingSet. */
  32812. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  32813. /** Destructor. */
  32814. ~KeyPressMappingSet();
  32815. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  32816. /** Returns a list of keypresses that are assigned to a particular command.
  32817. @param commandID the command's ID
  32818. */
  32819. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  32820. /** Assigns a keypress to a command.
  32821. If the keypress is already assigned to a different command, it will first be
  32822. removed from that command, to avoid it triggering multiple functions.
  32823. @param commandID the ID of the command that you want to add a keypress to. If
  32824. this is 0, the keypress will be removed from anything that it
  32825. was previously assigned to, but not re-assigned
  32826. @param newKeyPress the new key-press
  32827. @param insertIndex if this is less than zero, the key will be appended to the
  32828. end of the list of keypresses; otherwise the new keypress will
  32829. be inserted into the existing list at this index
  32830. */
  32831. void addKeyPress (const CommandID commandID,
  32832. const KeyPress& newKeyPress,
  32833. int insertIndex = -1) throw();
  32834. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  32835. @see resetToDefaultMapping
  32836. */
  32837. void resetToDefaultMappings() throw();
  32838. /** Resets all key-mappings to the defaults for a particular command.
  32839. @see resetToDefaultMappings
  32840. */
  32841. void resetToDefaultMapping (const CommandID commandID) throw();
  32842. /** Removes all keypresses that are assigned to any commands. */
  32843. void clearAllKeyPresses() throw();
  32844. /** Removes all keypresses that are assigned to a particular command. */
  32845. void clearAllKeyPresses (const CommandID commandID) throw();
  32846. /** Removes one of the keypresses that are assigned to a command.
  32847. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  32848. which the keyPressIndex refers.
  32849. */
  32850. void removeKeyPress (const CommandID commandID,
  32851. const int keyPressIndex) throw();
  32852. /** Removes a keypress from any command that it may be assigned to.
  32853. */
  32854. void removeKeyPress (const KeyPress& keypress) throw();
  32855. /** Returns true if the given command is linked to this key. */
  32856. bool containsMapping (const CommandID commandID,
  32857. const KeyPress& keyPress) const throw();
  32858. /** Looks for a command that corresponds to a keypress.
  32859. @returns the UID of the command or 0 if none was found
  32860. */
  32861. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  32862. /** Tries to recreate the mappings from a previously stored state.
  32863. The XML passed in must have been created by the createXml() method.
  32864. If the stored state makes any reference to commands that aren't
  32865. currently available, these will be ignored.
  32866. If the set of mappings being loaded was a set of differences (using createXml (true)),
  32867. then this will call resetToDefaultMappings() and then merge the saved mappings
  32868. on top. If the saved set was created with createXml (false), then this method
  32869. will first clear all existing mappings and load the saved ones as a complete set.
  32870. @returns true if it manages to load the XML correctly
  32871. @see createXml
  32872. */
  32873. bool restoreFromXml (const XmlElement& xmlVersion);
  32874. /** Creates an XML representation of the current mappings.
  32875. This will produce a lump of XML that can be later reloaded using
  32876. restoreFromXml() to recreate the current mapping state.
  32877. The object that is returned must be deleted by the caller.
  32878. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  32879. will be saved into the XML. If it's true, then the XML will
  32880. only store the differences between the current mappings and
  32881. the default mappings you'd get from calling resetToDefaultMappings().
  32882. The advantage of saving a set of differences from the default is that
  32883. if you change the default mappings (in a new version of your app, for
  32884. example), then these will be merged into a user's saved preferences.
  32885. @see restoreFromXml
  32886. */
  32887. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  32888. /** @internal */
  32889. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  32890. /** @internal */
  32891. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  32892. /** @internal */
  32893. void globalFocusChanged (Component* focusedComponent);
  32894. juce_UseDebuggingNewOperator
  32895. private:
  32896. ApplicationCommandManager* commandManager;
  32897. struct CommandMapping
  32898. {
  32899. CommandID commandID;
  32900. Array <KeyPress> keypresses;
  32901. bool wantsKeyUpDownCallbacks;
  32902. };
  32903. OwnedArray <CommandMapping> mappings;
  32904. struct KeyPressTime
  32905. {
  32906. KeyPress key;
  32907. uint32 timeWhenPressed;
  32908. };
  32909. OwnedArray <KeyPressTime> keysDown;
  32910. void handleMessage (const Message& message);
  32911. void invokeCommand (const CommandID commandID,
  32912. const KeyPress& keyPress,
  32913. const bool isKeyDown,
  32914. const int millisecsSinceKeyPressed,
  32915. Component* const originatingComponent) const;
  32916. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  32917. };
  32918. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32919. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  32920. #endif
  32921. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  32922. #endif
  32923. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32924. #endif
  32925. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32926. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  32927. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32928. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32929. /********* Start of inlined file: juce_TreeView.h *********/
  32930. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  32931. #define __JUCE_TREEVIEW_JUCEHEADER__
  32932. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32933. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32934. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32935. /**
  32936. Components derived from this class can have files dropped onto them by an external application.
  32937. @see DragAndDropContainer
  32938. */
  32939. class JUCE_API FileDragAndDropTarget
  32940. {
  32941. public:
  32942. /** Destructor. */
  32943. virtual ~FileDragAndDropTarget() {}
  32944. /** Callback to check whether this target is interested in the set of files being offered.
  32945. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32946. component, so don't do anything time-consuming in here, like opening the files to have a look
  32947. inside them!
  32948. @param files the set of (absolute) pathnames of the files that the user is dragging
  32949. @returns true if this component wants to receive the other callbacks regarging this
  32950. type of object; if it returns false, no other callbacks will be made.
  32951. */
  32952. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32953. /** Callback to indicate that some files are being dragged over this component.
  32954. This gets called when the user moves the mouse into this component while dragging.
  32955. Use this callback as a trigger to make your component repaint itself to give the
  32956. user feedback about whether the files can be dropped here or not.
  32957. @param files the set of (absolute) pathnames of the files that the user is dragging
  32958. @param x the mouse x position, relative to this component
  32959. @param y the mouse y position, relative to this component
  32960. */
  32961. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32962. /** Callback to indicate that the user is dragging some files over this component.
  32963. This gets called when the user moves the mouse over this component while dragging.
  32964. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32965. this lets you know what happens in-between.
  32966. @param files the set of (absolute) pathnames of the files that the user is dragging
  32967. @param x the mouse x position, relative to this component
  32968. @param y the mouse y position, relative to this component
  32969. */
  32970. virtual void fileDragMove (const StringArray& files, int x, int y);
  32971. /** Callback to indicate that the mouse has moved away from this component.
  32972. This gets called when the user moves the mouse out of this component while dragging
  32973. the files.
  32974. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32975. as a signal to repaint it in its normal state.
  32976. @param files the set of (absolute) pathnames of the files that the user is dragging
  32977. */
  32978. virtual void fileDragExit (const StringArray& files);
  32979. /** Callback to indicate that the user has dropped the files onto this component.
  32980. When the user drops the files, this get called, and you can use the files in whatever
  32981. way is appropriate.
  32982. Note that after this is called, the fileDragExit method may not be called, so you should
  32983. clean up in here if there's anything you need to do when the drag finishes.
  32984. @param files the set of (absolute) pathnames of the files that the user is dragging
  32985. @param x the mouse x position, relative to this component
  32986. @param y the mouse y position, relative to this component
  32987. */
  32988. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32989. };
  32990. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32991. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32992. class TreeView;
  32993. /**
  32994. An item in a treeview.
  32995. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  32996. own sub-items.
  32997. To implement an item that contains sub-items, override the itemOpennessChanged()
  32998. method so that when it is opened, it adds the new sub-items to itself using the
  32999. addSubItem method. Depending on the nature of the item it might choose to only
  33000. do this the first time it's opened, or it might want to refresh itself each time.
  33001. It also has the option of deleting its sub-items when it is closed, or leaving them
  33002. in place.
  33003. */
  33004. class JUCE_API TreeViewItem
  33005. {
  33006. public:
  33007. /** Constructor. */
  33008. TreeViewItem();
  33009. /** Destructor. */
  33010. virtual ~TreeViewItem();
  33011. /** Returns the number of sub-items that have been added to this item.
  33012. Note that this doesn't mean much if the node isn't open.
  33013. @see getSubItem, mightContainSubItems, addSubItem
  33014. */
  33015. int getNumSubItems() const throw();
  33016. /** Returns one of the item's sub-items.
  33017. Remember that the object returned might get deleted at any time when its parent
  33018. item is closed or refreshed, depending on the nature of the items you're using.
  33019. @see getNumSubItems
  33020. */
  33021. TreeViewItem* getSubItem (const int index) const throw();
  33022. /** Removes any sub-items. */
  33023. void clearSubItems();
  33024. /** Adds a sub-item.
  33025. @param newItem the object to add to the item's sub-item list. Once added, these can be
  33026. found using getSubItem(). When the items are later removed with
  33027. removeSubItem() (or when this item is deleted), they will be deleted.
  33028. @param insertPosition the index which the new item should have when it's added. If this
  33029. value is less than 0, the item will be added to the end of the list.
  33030. */
  33031. void addSubItem (TreeViewItem* const newItem,
  33032. const int insertPosition = -1);
  33033. /** Removes one of the sub-items.
  33034. @param index the item to remove
  33035. @param deleteItem if true, the item that is removed will also be deleted.
  33036. */
  33037. void removeSubItem (const int index,
  33038. const bool deleteItem = true);
  33039. /** Returns the TreeView to which this item belongs. */
  33040. TreeView* getOwnerView() const throw() { return ownerView; }
  33041. /** Returns the item within which this item is contained. */
  33042. TreeViewItem* getParentItem() const throw() { return parentItem; }
  33043. /** True if this item is currently open in the treeview. */
  33044. bool isOpen() const throw();
  33045. /** Opens or closes the item.
  33046. When opened or closed, the item's itemOpennessChanged() method will be called,
  33047. and a subclass should use this callback to create and add any sub-items that
  33048. it needs to.
  33049. @see itemOpennessChanged, mightContainSubItems
  33050. */
  33051. void setOpen (const bool shouldBeOpen);
  33052. /** True if this item is currently selected.
  33053. Use this when painting the node, to decide whether to draw it as selected or not.
  33054. */
  33055. bool isSelected() const throw();
  33056. /** Selects or deselects the item.
  33057. This will cause a callback to itemSelectionChanged()
  33058. */
  33059. void setSelected (const bool shouldBeSelected,
  33060. const bool deselectOtherItemsFirst);
  33061. /** Returns the rectangle that this item occupies.
  33062. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  33063. top-left of the TreeView comp, so this will depend on the scroll-position of
  33064. the tree. If false, it is relative to the top-left of the topmost item in the
  33065. tree (so this would be unaffected by scrolling the view).
  33066. */
  33067. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  33068. /** Sends a signal to the treeview to make it refresh itself.
  33069. Call this if your items have changed and you want the tree to update to reflect
  33070. this.
  33071. */
  33072. void treeHasChanged() const throw();
  33073. /** Sends a repaint message to redraw just this item.
  33074. Note that you should only call this if you want to repaint a superficial change. If
  33075. you're altering the tree's nodes, you should instead call treeHasChanged().
  33076. */
  33077. void repaintItem() const;
  33078. /** Returns the row number of this item in the tree.
  33079. The row number of an item will change according to which items are open.
  33080. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  33081. */
  33082. int getRowNumberInTree() const throw();
  33083. /** Returns true if all the item's parent nodes are open.
  33084. This is useful to check whether the item might actually be visible or not.
  33085. */
  33086. bool areAllParentsOpen() const throw();
  33087. /** Changes whether lines are drawn to connect any sub-items to this item.
  33088. By default, line-drawing is turned on.
  33089. */
  33090. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  33091. /** Tells the tree whether this item can potentially be opened.
  33092. If your item could contain sub-items, this should return true; if it returns
  33093. false then the tree will not try to open the item. This determines whether or
  33094. not the item will be drawn with a 'plus' button next to it.
  33095. */
  33096. virtual bool mightContainSubItems() = 0;
  33097. /** Returns a string to uniquely identify this item.
  33098. If you're planning on using the TreeView::getOpennessState() method, then
  33099. these strings will be used to identify which nodes are open. The string
  33100. should be unique amongst the item's sibling items, but it's ok for there
  33101. to be duplicates at other levels of the tree.
  33102. If you're not going to store the state, then it's ok not to bother implementing
  33103. this method.
  33104. */
  33105. virtual const String getUniqueName() const;
  33106. /** Called when an item is opened or closed.
  33107. When setOpen() is called and the item has specified that it might
  33108. have sub-items with the mightContainSubItems() method, this method
  33109. is called to let the item create or manage its sub-items.
  33110. So when this is called with isNowOpen set to true (i.e. when the item is being
  33111. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  33112. refresh its sub-item list.
  33113. When this is called with isNowOpen set to false, the subclass might want
  33114. to use clearSubItems() to save on space, or it might choose to leave them,
  33115. depending on the nature of the tree.
  33116. You could also use this callback as a trigger to start a background process
  33117. which asynchronously creates sub-items and adds them, if that's more
  33118. appropriate for the task in hand.
  33119. @see mightContainSubItems
  33120. */
  33121. virtual void itemOpennessChanged (bool isNowOpen);
  33122. /** Must return the width required by this item.
  33123. If your item needs to have a particular width in pixels, return that value; if
  33124. you'd rather have it just fill whatever space is available in the treeview,
  33125. return -1.
  33126. If all your items return -1, no horizontal scrollbar will be shown, but if any
  33127. items have fixed widths and extend beyond the width of the treeview, a
  33128. scrollbar will appear.
  33129. Each item can be a different width, but if they change width, you should call
  33130. treeHasChanged() to update the tree.
  33131. */
  33132. virtual int getItemWidth() const { return -1; }
  33133. /** Must return the height required by this item.
  33134. This is the height in pixels that the item will take up. Items in the tree
  33135. can be different heights, but if they change height, you should call
  33136. treeHasChanged() to update the tree.
  33137. */
  33138. virtual int getItemHeight() const { return 20; }
  33139. /** You can override this method to return false if you don't want to allow the
  33140. user to select this item.
  33141. */
  33142. virtual bool canBeSelected() const { return true; }
  33143. /** Creates a component that will be used to represent this item.
  33144. You don't have to implement this method - if it returns 0 then no component
  33145. will be used for the item, and you can just draw it using the paintItem()
  33146. callback. But if you do return a component, it will be positioned in the
  33147. treeview so that it can be used to represent this item.
  33148. The component returned will be managed by the treeview, so always return
  33149. a new component, and don't keep a reference to it, as the treeview will
  33150. delete it later when it goes off the screen or is no longer needed. Also
  33151. bear in mind that if the component keeps a reference to the item that
  33152. created it, that item could be deleted before the component. Its position
  33153. and size will be completely managed by the tree, so don't attempt to move it
  33154. around.
  33155. Something you may want to do with your component is to give it a pointer to
  33156. the TreeView that created it. This is perfectly safe, and there's no danger
  33157. of it becoming a dangling pointer because the TreeView will always delete
  33158. the component before it is itself deleted.
  33159. As long as you stick to these rules you can return whatever kind of
  33160. component you like. It's most useful if you're doing things like drag-and-drop
  33161. of items, or want to use a Label component to edit item names, etc.
  33162. */
  33163. virtual Component* createItemComponent() { return 0; }
  33164. /** Draws the item's contents.
  33165. You can choose to either implement this method and draw each item, or you
  33166. can use createItemComponent() to create a component that will represent the
  33167. item.
  33168. If all you need in your tree is to be able to draw the items and detect when
  33169. the user selects or double-clicks one of them, it's probably enough to
  33170. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  33171. complicated interactions, you may need to use createItemComponent() instead.
  33172. @param g the graphics context to draw into
  33173. @param width the width of the area available for drawing
  33174. @param height the height of the area available for drawing
  33175. */
  33176. virtual void paintItem (Graphics& g, int width, int height);
  33177. /** Draws the item's open/close button.
  33178. If you don't implement this method, the default behaviour is to
  33179. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  33180. it for custom effects.
  33181. */
  33182. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  33183. /** Called when the user clicks on this item.
  33184. If you're using createItemComponent() to create a custom component for the
  33185. item, the mouse-clicks might not make it through to the treeview, but this
  33186. is how you find out about clicks when just drawing each item individually.
  33187. The associated mouse-event details are passed in, so you can find out about
  33188. which button, where it was, etc.
  33189. @see itemDoubleClicked
  33190. */
  33191. virtual void itemClicked (const MouseEvent& e);
  33192. /** Called when the user double-clicks on this item.
  33193. If you're using createItemComponent() to create a custom component for the
  33194. item, the mouse-clicks might not make it through to the treeview, but this
  33195. is how you find out about clicks when just drawing each item individually.
  33196. The associated mouse-event details are passed in, so you can find out about
  33197. which button, where it was, etc.
  33198. If not overridden, the base class method here will open or close the item as
  33199. if the 'plus' button had been clicked.
  33200. @see itemClicked
  33201. */
  33202. virtual void itemDoubleClicked (const MouseEvent& e);
  33203. /** Called when the item is selected or deselected.
  33204. Use this if you want to do something special when the item's selectedness
  33205. changes. By default it'll get repainted when this happens.
  33206. */
  33207. virtual void itemSelectionChanged (bool isNowSelected);
  33208. /** The item can return a tool tip string here if it wants to.
  33209. @see TooltipClient
  33210. */
  33211. virtual const String getTooltip();
  33212. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  33213. If this returns a non-empty name then when the user drags an item, the treeview will
  33214. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  33215. a drag-and-drop operation, using this string as the source description, with the treeview
  33216. itself as the source component.
  33217. If you need more complex drag-and-drop behaviour, you can use custom components for
  33218. the items, and use those to trigger the drag.
  33219. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  33220. isInterestedInFileDrag(), etc.
  33221. @see DragAndDropContainer::startDragging
  33222. */
  33223. virtual const String getDragSourceDescription();
  33224. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  33225. method and return true.
  33226. If you return true and allow some files to be dropped, you'll also need to implement the
  33227. filesDropped() method to do something with them.
  33228. Note that this will be called often, so make your implementation very quick! There's
  33229. certainly no time to try opening the files and having a think about what's inside them!
  33230. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  33231. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  33232. */
  33233. virtual bool isInterestedInFileDrag (const StringArray& files);
  33234. /** When files are dropped into this item, this callback is invoked.
  33235. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  33236. The insertIndex value indicates where in the list of sub-items the files were dropped.
  33237. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  33238. */
  33239. virtual void filesDropped (const StringArray& files, int insertIndex);
  33240. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  33241. If you implement this method, you'll also need to implement itemDropped() in order to handle
  33242. the items when they are dropped.
  33243. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  33244. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  33245. */
  33246. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  33247. /** When a things are dropped into this item, this callback is invoked.
  33248. For this to work, you need to have also implemented isInterestedInDragSource().
  33249. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  33250. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  33251. */
  33252. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  33253. /** Sets a flag to indicate that the item wants to be allowed
  33254. to draw all the way across to the left edge of the treeview.
  33255. By default this is false, which means that when the paintItem()
  33256. method is called, its graphics context is clipped to only allow
  33257. drawing within the item's rectangle. If this flag is set to true,
  33258. then the graphics context isn't clipped on its left side, so it
  33259. can draw all the way across to the left margin. Note that the
  33260. context will still have its origin in the same place though, so
  33261. the coordinates of anything to its left will be negative. It's
  33262. mostly useful if you want to draw a wider bar behind the
  33263. highlighted item.
  33264. */
  33265. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  33266. /** Saves the current state of open/closed nodes so it can be restored later.
  33267. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  33268. and records it as XML. To identify node objects it uses the
  33269. TreeViewItem::getUniqueName() method to create named paths. This
  33270. means that the same state of open/closed nodes can be restored to a
  33271. completely different instance of the tree, as long as it contains nodes
  33272. whose unique names are the same.
  33273. You'd normally want to use TreeView::getOpennessState() rather than call it
  33274. for a specific item, but this can be handy if you need to briefly save the state
  33275. for a section of the tree.
  33276. The caller is responsible for deleting the object that is returned.
  33277. @see TreeView::getOpennessState, restoreOpennessState
  33278. */
  33279. XmlElement* getOpennessState() const throw();
  33280. /** Restores the openness of this item and all its sub-items from a saved state.
  33281. See TreeView::restoreOpennessState for more details.
  33282. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  33283. for a specific item, but this can be handy if you need to briefly save the state
  33284. for a section of the tree.
  33285. @see TreeView::restoreOpennessState, getOpennessState
  33286. */
  33287. void restoreOpennessState (const XmlElement& xml) throw();
  33288. /** Returns the index of this item in its parent's sub-items. */
  33289. int getIndexInParent() const throw();
  33290. /** Returns true if this item is the last of its parent's sub-itens. */
  33291. bool isLastOfSiblings() const throw();
  33292. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  33293. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  33294. The string takes the form of a path, constructed from the getUniqueName() of this
  33295. item and all its parents, so these must all be correctly implemented for it to work.
  33296. @see TreeView::findItemFromIdentifierString, getUniqueName
  33297. */
  33298. const String getItemIdentifierString() const;
  33299. juce_UseDebuggingNewOperator
  33300. private:
  33301. TreeView* ownerView;
  33302. TreeViewItem* parentItem;
  33303. OwnedArray <TreeViewItem> subItems;
  33304. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  33305. int uid;
  33306. bool selected : 1;
  33307. bool redrawNeeded : 1;
  33308. bool drawLinesInside : 1;
  33309. bool drawsInLeftMargin : 1;
  33310. unsigned int openness : 2;
  33311. friend class TreeView;
  33312. friend class TreeViewContentComponent;
  33313. void updatePositions (int newY);
  33314. int getIndentX() const throw();
  33315. void setOwnerView (TreeView* const newOwner) throw();
  33316. void paintRecursively (Graphics& g, int width);
  33317. TreeViewItem* getTopLevelItem() throw();
  33318. TreeViewItem* findItemRecursively (int y) throw();
  33319. TreeViewItem* getDeepestOpenParentItem() throw();
  33320. int getNumRows() const throw();
  33321. TreeViewItem* getItemOnRow (int index) throw();
  33322. void deselectAllRecursively();
  33323. int countSelectedItemsRecursively() const throw();
  33324. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  33325. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  33326. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  33327. TreeViewItem (const TreeViewItem&);
  33328. const TreeViewItem& operator= (const TreeViewItem&);
  33329. };
  33330. /**
  33331. A tree-view component.
  33332. Use one of these to hold and display a structure of TreeViewItem objects.
  33333. */
  33334. class JUCE_API TreeView : public Component,
  33335. public SettableTooltipClient,
  33336. public FileDragAndDropTarget,
  33337. public DragAndDropTarget,
  33338. private AsyncUpdater
  33339. {
  33340. public:
  33341. /** Creates an empty treeview.
  33342. Once you've got a treeview component, you'll need to give it something to
  33343. display, using the setRootItem() method.
  33344. */
  33345. TreeView (const String& componentName = String::empty);
  33346. /** Destructor. */
  33347. ~TreeView();
  33348. /** Sets the item that is displayed in the treeview.
  33349. A tree has a single root item which contains as many sub-items as it needs. If
  33350. you want the tree to contain a number of root items, you should still use a single
  33351. root item above these, but hide it using setRootItemVisible().
  33352. You can pass in 0 to this method to clear the tree and remove its current root item.
  33353. The object passed in will not be deleted by the treeview, it's up to the caller
  33354. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  33355. this item until you've removed it from the tree, either by calling setRootItem (0),
  33356. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  33357. to delete it.
  33358. */
  33359. void setRootItem (TreeViewItem* const newRootItem);
  33360. /** Returns the tree's root item.
  33361. This will be the last object passed to setRootItem(), or 0 if none has been set.
  33362. */
  33363. TreeViewItem* getRootItem() const throw() { return rootItem; }
  33364. /** This will remove and delete the current root item.
  33365. It's a convenient way of deleting the item and calling setRootItem (0).
  33366. */
  33367. void deleteRootItem();
  33368. /** Changes whether the tree's root item is shown or not.
  33369. If the root item is hidden, only its sub-items will be shown in the treeview - this
  33370. lets you make the tree look as if it's got many root items. If it's hidden, this call
  33371. will also make sure the root item is open (otherwise the treeview would look empty).
  33372. */
  33373. void setRootItemVisible (const bool shouldBeVisible);
  33374. /** Returns true if the root item is visible.
  33375. @see setRootItemVisible
  33376. */
  33377. bool isRootItemVisible() const throw() { return rootItemVisible; }
  33378. /** Sets whether items are open or closed by default.
  33379. Normally, items are closed until the user opens them, but you can use this
  33380. to make them default to being open until explicitly closed.
  33381. @see areItemsOpenByDefault
  33382. */
  33383. void setDefaultOpenness (const bool isOpenByDefault);
  33384. /** Returns true if the tree's items default to being open.
  33385. @see setDefaultOpenness
  33386. */
  33387. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  33388. /** This sets a flag to indicate that the tree can be used for multi-selection.
  33389. You can always select multiple items internally by calling the
  33390. TreeViewItem::setSelected() method, but this flag indicates whether the user
  33391. is allowed to multi-select by clicking on the tree.
  33392. By default it is disabled.
  33393. @see isMultiSelectEnabled
  33394. */
  33395. void setMultiSelectEnabled (const bool canMultiSelect);
  33396. /** Returns whether multi-select has been enabled for the tree.
  33397. @see setMultiSelectEnabled
  33398. */
  33399. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  33400. /** Sets a flag to indicate whether to hide the open/close buttons.
  33401. @see areOpenCloseButtonsVisible
  33402. */
  33403. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  33404. /** Returns whether open/close buttons are shown.
  33405. @see setOpenCloseButtonsVisible
  33406. */
  33407. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  33408. /** Deselects any items that are currently selected. */
  33409. void clearSelectedItems();
  33410. /** Returns the number of items that are currently selected.
  33411. @see getSelectedItem, clearSelectedItems
  33412. */
  33413. int getNumSelectedItems() const throw();
  33414. /** Returns one of the selected items in the tree.
  33415. @param index the index, 0 to (getNumSelectedItems() - 1)
  33416. */
  33417. TreeViewItem* getSelectedItem (const int index) const throw();
  33418. /** Returns the number of rows the tree is using.
  33419. This will depend on which items are open.
  33420. @see TreeViewItem::getRowNumberInTree()
  33421. */
  33422. int getNumRowsInTree() const;
  33423. /** Returns the item on a particular row of the tree.
  33424. If the index is out of range, this will return 0.
  33425. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  33426. */
  33427. TreeViewItem* getItemOnRow (int index) const;
  33428. /** Returns the item that contains a given y position.
  33429. The y is relative to the top of the TreeView component.
  33430. */
  33431. TreeViewItem* getItemAt (int yPosition) const throw();
  33432. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  33433. void scrollToKeepItemVisible (TreeViewItem* item);
  33434. /** Returns the treeview's Viewport object. */
  33435. Viewport* getViewport() const throw() { return viewport; }
  33436. /** Returns the number of pixels by which each nested level of the tree is indented.
  33437. @see setIndentSize
  33438. */
  33439. int getIndentSize() const throw() { return indentSize; }
  33440. /** Changes the distance by which each nested level of the tree is indented.
  33441. @see getIndentSize
  33442. */
  33443. void setIndentSize (const int newIndentSize);
  33444. /** Searches the tree for an item with the specified identifier.
  33445. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  33446. If no such item exists, this will return false. If the item is found, all of its items
  33447. will be automatically opened.
  33448. */
  33449. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  33450. /** Saves the current state of open/closed nodes so it can be restored later.
  33451. This takes a snapshot of which nodes have been explicitly opened or closed,
  33452. and records it as XML. To identify node objects it uses the
  33453. TreeViewItem::getUniqueName() method to create named paths. This
  33454. means that the same state of open/closed nodes can be restored to a
  33455. completely different instance of the tree, as long as it contains nodes
  33456. whose unique names are the same.
  33457. The caller is responsible for deleting the object that is returned.
  33458. @param alsoIncludeScrollPosition if this is true, the state will also
  33459. include information about where the
  33460. tree has been scrolled to vertically,
  33461. so this can also be restored
  33462. @see restoreOpennessState
  33463. */
  33464. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  33465. /** Restores a previously saved arrangement of open/closed nodes.
  33466. This will try to restore a snapshot of the tree's state that was created by
  33467. the getOpennessState() method. If any of the nodes named in the original
  33468. XML aren't present in this tree, they will be ignored.
  33469. @see getOpennessState
  33470. */
  33471. void restoreOpennessState (const XmlElement& newState);
  33472. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  33473. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33474. methods.
  33475. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33476. */
  33477. enum ColourIds
  33478. {
  33479. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  33480. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  33481. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  33482. };
  33483. /** @internal */
  33484. void paint (Graphics& g);
  33485. /** @internal */
  33486. void resized();
  33487. /** @internal */
  33488. bool keyPressed (const KeyPress& key);
  33489. /** @internal */
  33490. void colourChanged();
  33491. /** @internal */
  33492. void enablementChanged();
  33493. /** @internal */
  33494. bool isInterestedInFileDrag (const StringArray& files);
  33495. /** @internal */
  33496. void fileDragEnter (const StringArray& files, int x, int y);
  33497. /** @internal */
  33498. void fileDragMove (const StringArray& files, int x, int y);
  33499. /** @internal */
  33500. void fileDragExit (const StringArray& files);
  33501. /** @internal */
  33502. void filesDropped (const StringArray& files, int x, int y);
  33503. /** @internal */
  33504. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  33505. /** @internal */
  33506. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33507. /** @internal */
  33508. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33509. /** @internal */
  33510. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  33511. /** @internal */
  33512. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33513. juce_UseDebuggingNewOperator
  33514. private:
  33515. friend class TreeViewItem;
  33516. friend class TreeViewContentComponent;
  33517. Viewport* viewport;
  33518. CriticalSection nodeAlterationLock;
  33519. TreeViewItem* rootItem;
  33520. Component* dragInsertPointHighlight;
  33521. Component* dragTargetGroupHighlight;
  33522. int indentSize;
  33523. bool defaultOpenness : 1;
  33524. bool needsRecalculating : 1;
  33525. bool rootItemVisible : 1;
  33526. bool multiSelectEnabled : 1;
  33527. bool openCloseButtonsVisible : 1;
  33528. void itemsChanged() throw();
  33529. void handleAsyncUpdate();
  33530. void moveSelectedRow (int delta);
  33531. void updateButtonUnderMouse (const MouseEvent& e);
  33532. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  33533. void hideDragHighlight() throw();
  33534. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  33535. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  33536. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  33537. const StringArray& files, const String& sourceDescription,
  33538. Component* sourceComponent) const throw();
  33539. TreeView (const TreeView&);
  33540. const TreeView& operator= (const TreeView&);
  33541. };
  33542. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  33543. /********* End of inlined file: juce_TreeView.h *********/
  33544. /**
  33545. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  33546. object.
  33547. @see KeyPressMappingSet
  33548. */
  33549. class JUCE_API KeyMappingEditorComponent : public Component,
  33550. public TreeViewItem,
  33551. public ChangeListener,
  33552. private ButtonListener
  33553. {
  33554. public:
  33555. /** Creates a KeyMappingEditorComponent.
  33556. @param mappingSet this is the set of mappings to display and
  33557. edit. Make sure the mappings object is not
  33558. deleted before this component!
  33559. @param showResetToDefaultButton if true, then at the bottom of the
  33560. list, the component will include a 'reset to
  33561. defaults' button.
  33562. */
  33563. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  33564. const bool showResetToDefaultButton);
  33565. /** Destructor. */
  33566. virtual ~KeyMappingEditorComponent();
  33567. /** Sets up the colours to use for parts of the component.
  33568. @param mainBackground colour to use for most of the background
  33569. @param textColour colour to use for the text
  33570. */
  33571. void setColours (const Colour& mainBackground,
  33572. const Colour& textColour);
  33573. /** Returns the KeyPressMappingSet that this component is acting upon.
  33574. */
  33575. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  33576. /** Can be overridden if some commands need to be excluded from the list.
  33577. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  33578. method to decide what to return, but you can override it to handle special cases.
  33579. */
  33580. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  33581. /** Can be overridden to indicate that some commands are shown as read-only.
  33582. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  33583. method to decide what to return, but you can override it to handle special cases.
  33584. */
  33585. virtual bool isCommandReadOnly (const CommandID commandID);
  33586. /** This can be overridden to let you change the format of the string used
  33587. to describe a keypress.
  33588. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  33589. keys that are triggered by something else externally. If you override the
  33590. method, be sure to let the base class's method handle keys you're not
  33591. interested in.
  33592. */
  33593. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  33594. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  33595. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33596. methods.
  33597. To change the colours of the menu that pops up
  33598. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33599. */
  33600. enum ColourIds
  33601. {
  33602. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  33603. textColourId = 0x100ad01, /**< The colour for the text. */
  33604. };
  33605. /** @internal */
  33606. void parentHierarchyChanged();
  33607. /** @internal */
  33608. void resized();
  33609. /** @internal */
  33610. void changeListenerCallback (void*);
  33611. /** @internal */
  33612. bool mightContainSubItems();
  33613. /** @internal */
  33614. const String getUniqueName() const;
  33615. /** @internal */
  33616. void buttonClicked (Button* button);
  33617. juce_UseDebuggingNewOperator
  33618. private:
  33619. KeyPressMappingSet* mappings;
  33620. TreeView* tree;
  33621. friend class KeyMappingTreeViewItem;
  33622. friend class KeyCategoryTreeViewItem;
  33623. friend class KeyMappingItemComponent;
  33624. friend class KeyMappingChangeButton;
  33625. TextButton* resetButton;
  33626. void assignNewKey (const CommandID commandID, int index);
  33627. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  33628. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  33629. };
  33630. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  33631. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  33632. #endif
  33633. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33634. /********* Start of inlined file: juce_CodeEditorComponent.h *********/
  33635. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33636. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33637. /********* Start of inlined file: juce_CodeDocument.h *********/
  33638. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33639. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33640. class CodeDocumentLine;
  33641. /**
  33642. A class for storing and manipulating a source code file.
  33643. When using a CodeEditorComponent, it takes one of these as its source object.
  33644. The CodeDocument stores its content as an array of lines, which makes it
  33645. quick to insert and delete.
  33646. @see CodeEditorComponent
  33647. */
  33648. class JUCE_API CodeDocument
  33649. {
  33650. public:
  33651. /** Creates a new, empty document.
  33652. */
  33653. CodeDocument();
  33654. /** Destructor. */
  33655. ~CodeDocument();
  33656. /** A position in a code document.
  33657. Using this class you can find a position in a code document and quickly get its
  33658. character position, line, and index. By calling setPositionMaintained (true), the
  33659. position is automatically updated when text is inserted or deleted in the document,
  33660. so that it maintains its original place in the text.
  33661. */
  33662. class JUCE_API Position
  33663. {
  33664. public:
  33665. /** Creates an uninitialised postion.
  33666. Don't attempt to call any methods on this until you've given it an owner document
  33667. to refer to!
  33668. */
  33669. Position() throw();
  33670. /** Creates a position based on a line and index in a document.
  33671. Note that this index is NOT the column number, it's the number of characters from the
  33672. start of the line. The "column" number isn't quite the same, because if the line
  33673. contains any tab characters, the relationship of the index to its visual column depends on
  33674. the number of spaces per tab being used!
  33675. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33676. they will be adjusted to keep them within its limits.
  33677. */
  33678. Position (const CodeDocument* const ownerDocument,
  33679. const int line, const int indexInLine) throw();
  33680. /** Creates a position based on a character index in a document.
  33681. This position is placed at the specified number of characters from the start of the
  33682. document. The line and column are auto-calculated.
  33683. If the position is beyond the range of the document, it'll be adjusted to keep it
  33684. inside.
  33685. */
  33686. Position (const CodeDocument* const ownerDocument,
  33687. const int charactersFromStartOfDocument) throw();
  33688. /** Creates a copy of another position.
  33689. This will copy the position, but the new object will not be set to maintain its position,
  33690. even if the source object was set to do so.
  33691. */
  33692. Position (const Position& other) throw();
  33693. /** Destructor. */
  33694. ~Position() throw();
  33695. const Position& operator= (const Position& other) throw();
  33696. bool operator== (const Position& other) const throw();
  33697. bool operator!= (const Position& other) const throw();
  33698. /** Points this object at a new position within the document.
  33699. If the position is beyond the range of the document, it'll be adjusted to keep it
  33700. inside.
  33701. @see getPosition, setLineAndIndex
  33702. */
  33703. void setPosition (const int charactersFromStartOfDocument) throw();
  33704. /** Returns the position as the number of characters from the start of the document.
  33705. @see setPosition, getLineNumber, getIndexInLine
  33706. */
  33707. int getPosition() const throw() { return characterPos; }
  33708. /** Moves the position to a new line and index within the line.
  33709. Note that the index is NOT the column at which the position appears in an editor.
  33710. If the line contains any tab characters, the relationship of the index to its
  33711. visual position depends on the number of spaces per tab being used!
  33712. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33713. they will be adjusted to keep them within its limits.
  33714. */
  33715. void setLineAndIndex (const int newLine, const int newIndexInLine) throw();
  33716. /** Returns the line number of this position.
  33717. The first line in the document is numbered zero, not one!
  33718. */
  33719. int getLineNumber() const throw() { return line; }
  33720. /** Returns the number of characters from the start of the line.
  33721. Note that this value is NOT the column at which the position appears in an editor.
  33722. If the line contains any tab characters, the relationship of the index to its
  33723. visual position depends on the number of spaces per tab being used!
  33724. */
  33725. int getIndexInLine() const throw() { return indexInLine; }
  33726. /** Allows the position to be automatically updated when the document changes.
  33727. If this is set to true, the positon will register with its document so that
  33728. when the document has text inserted or deleted, this position will be automatically
  33729. moved to keep it at the same position in the text.
  33730. */
  33731. void setPositionMaintained (const bool isMaintained) throw();
  33732. /** Moves the position forwards or backwards by the specified number of characters.
  33733. @see movedBy
  33734. */
  33735. void moveBy (int characterDelta) throw();
  33736. /** Returns a position which is the same as this one, moved by the specified number of
  33737. characters.
  33738. @see moveBy
  33739. */
  33740. const Position movedBy (const int characterDelta) const throw();
  33741. /** Returns a position which is the same as this one, moved up or down by the specified
  33742. number of lines.
  33743. @see movedBy
  33744. */
  33745. const Position movedByLines (const int deltaLines) const throw();
  33746. /** Returns the character in the document at this position.
  33747. @see getLineText
  33748. */
  33749. const tchar getCharacter() const throw();
  33750. /** Returns the line from the document that this position is within.
  33751. @see getCharacter, getLineNumber
  33752. */
  33753. const String getLineText() const throw();
  33754. private:
  33755. CodeDocument* owner;
  33756. int characterPos, line, indexInLine;
  33757. bool positionMaintained;
  33758. };
  33759. /** Returns the full text of the document. */
  33760. const String getAllContent() const throw();
  33761. /** Returns a section of the document's text. */
  33762. const String getTextBetween (const Position& start, const Position& end) const throw();
  33763. /** Returns a line from the document. */
  33764. const String getLine (const int lineIndex) const throw();
  33765. /** Returns the number of characters in the document. */
  33766. int getNumCharacters() const throw();
  33767. /** Returns the number of lines in the document. */
  33768. int getNumLines() const throw() { return lines.size(); }
  33769. /** Returns the number of characters in the longest line of the document. */
  33770. int getMaximumLineLength() throw();
  33771. /** Deletes a section of the text.
  33772. This operation is undoable.
  33773. */
  33774. void deleteSection (const Position& startPosition, const Position& endPosition);
  33775. /** Inserts some text into the document at a given position.
  33776. This operation is undoable.
  33777. */
  33778. void insertText (const Position& position, const String& text);
  33779. /** Clears the document and replaces it with some new text.
  33780. This operation is undoable - if you're trying to completely reset the document, you
  33781. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33782. */
  33783. void replaceAllContent (const String& newContent);
  33784. /** Returns the preferred new-line characters for the document.
  33785. This will be either "\n", "\r\n", or (rarely) "\r".
  33786. @see setNewLineCharacters
  33787. */
  33788. const String getNewLineCharacters() const throw() { return newLineChars; }
  33789. /** Sets the new-line characters that the document should use.
  33790. The string must be either "\n", "\r\n", or (rarely) "\r".
  33791. @see getNewLineCharacters
  33792. */
  33793. void setNewLineCharacters (const String& newLine) throw();
  33794. /** Begins a new undo transaction.
  33795. The document itself will not call this internally, so relies on whatever is using the
  33796. document to periodically call this to break up the undo sequence into sensible chunks.
  33797. @see UndoManager::beginNewTransaction
  33798. */
  33799. void newTransaction();
  33800. /** Undo the last operation.
  33801. @see UndoManager::undo
  33802. */
  33803. void undo();
  33804. /** Redo the last operation.
  33805. @see UndoManager::redo
  33806. */
  33807. void redo();
  33808. /** Clears the undo history.
  33809. @see UndoManager::clearUndoHistory
  33810. */
  33811. void clearUndoHistory();
  33812. /** Returns the document's UndoManager */
  33813. UndoManager& getUndoManager() throw() { return undoManager; }
  33814. /** Makes a note that the document's current state matches the one that is saved.
  33815. After this has been called, hasChangedSinceSavePoint() will return false until
  33816. the document has been altered, and then it'll start returning true. If the document is
  33817. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33818. will again return false.
  33819. @see hasChangedSinceSavePoint
  33820. */
  33821. void setSavePoint() throw();
  33822. /** Returns true if the state of the document differs from the state it was in when
  33823. setSavePoint() was last called.
  33824. @see setSavePoint
  33825. */
  33826. bool hasChangedSinceSavePoint() const throw();
  33827. /** Searches for a word-break. */
  33828. const Position findWordBreakAfter (const Position& position) const throw();
  33829. /** Searches for a word-break. */
  33830. const Position findWordBreakBefore (const Position& position) const throw();
  33831. /** An object that receives callbacks from the CodeDocument when its text changes.
  33832. @see CodeDocument::addListener, CodeDocument::removeListener
  33833. */
  33834. class JUCE_API Listener
  33835. {
  33836. public:
  33837. Listener() {}
  33838. virtual ~Listener() {}
  33839. /** Called by a CodeDocument when it is altered.
  33840. */
  33841. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33842. const Position& affectedTextEnd) = 0;
  33843. };
  33844. /** Registers a listener object to receive callbacks when the document changes.
  33845. If the listener is already registered, this method has no effect.
  33846. @see removeListener
  33847. */
  33848. void addListener (Listener* const listener) throw();
  33849. /** Deregisters a listener.
  33850. @see addListener
  33851. */
  33852. void removeListener (Listener* const listener) throw();
  33853. /** Iterates the text in a CodeDocument.
  33854. This class lets you read characters from a CodeDocument. It's designed to be used
  33855. by a SyntaxAnalyser object.
  33856. @see CodeDocument, SyntaxAnalyser
  33857. */
  33858. class Iterator
  33859. {
  33860. public:
  33861. Iterator (CodeDocument* const document) throw();
  33862. Iterator (const Iterator& other);
  33863. const Iterator& operator= (const Iterator& other) throw();
  33864. ~Iterator() throw();
  33865. /** Reads the next character and returns it.
  33866. @see peekNextChar
  33867. */
  33868. juce_wchar nextChar() throw();
  33869. /** Reads the next character without advancing the current position. */
  33870. juce_wchar peekNextChar() const throw();
  33871. /** Advances the position by one character. */
  33872. void skip() throw();
  33873. /** Returns the position of the next character as its position within the
  33874. whole document.
  33875. */
  33876. int getPosition() const throw() { return position; }
  33877. /** Skips over any whitespace characters until the next character is non-whitespace. */
  33878. void skipWhitespace();
  33879. /** Skips forward until the next character will be the first character on the next line */
  33880. void skipToEndOfLine();
  33881. /** Returns the line number of the next character. */
  33882. int getLine() const throw() { return line; }
  33883. /** Returns true if the iterator has reached the end of the document. */
  33884. bool isEOF() const throw();
  33885. private:
  33886. CodeDocument* document;
  33887. int line, position;
  33888. };
  33889. juce_UseDebuggingNewOperator
  33890. private:
  33891. friend class CodeDocumentInsertAction;
  33892. friend class CodeDocumentDeleteAction;
  33893. friend class Iterator;
  33894. friend class Position;
  33895. OwnedArray <CodeDocumentLine> lines;
  33896. Array <Position*> positionsToMaintain;
  33897. UndoManager undoManager;
  33898. int currentActionIndex, indexOfSavedState;
  33899. int maximumLineLength;
  33900. VoidArray listeners;
  33901. String newLineChars;
  33902. void sendListenerChangeMessage (const int startLine, const int endLine);
  33903. void insert (const String& text, const int insertPos, const bool undoable);
  33904. void remove (const int startPos, const int endPos, const bool undoable);
  33905. CodeDocument (const CodeDocument&);
  33906. const CodeDocument& operator= (const CodeDocument&);
  33907. };
  33908. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  33909. /********* End of inlined file: juce_CodeDocument.h *********/
  33910. /********* Start of inlined file: juce_CodeTokeniser.h *********/
  33911. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33912. #define __JUCE_CODETOKENISER_JUCEHEADER__
  33913. /**
  33914. A base class for tokenising code so that the syntax can be displayed in a
  33915. code editor.
  33916. @see CodeDocument, CodeEditorComponent
  33917. */
  33918. class JUCE_API CodeTokeniser
  33919. {
  33920. public:
  33921. CodeTokeniser() {}
  33922. virtual ~CodeTokeniser() {}
  33923. /** Reads the next token from the source and returns its token type.
  33924. This must leave the source pointing to the first character in the
  33925. next token.
  33926. */
  33927. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  33928. /** Returns a list of the names of the token types this analyser uses.
  33929. The index in this list must match the token type numbers that are
  33930. returned by readNextToken().
  33931. */
  33932. virtual const StringArray getTokenTypes() = 0;
  33933. /** Returns a suggested syntax highlighting colour for a specified
  33934. token type.
  33935. */
  33936. virtual const Colour getDefaultColour (const int tokenType) = 0;
  33937. juce_UseDebuggingNewOperator
  33938. };
  33939. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  33940. /********* End of inlined file: juce_CodeTokeniser.h *********/
  33941. class CodeEditorLine;
  33942. /**
  33943. A text editor component designed specifically for source code.
  33944. This is designed to handle syntax highlighting and fast editing of very large
  33945. files.
  33946. */
  33947. class JUCE_API CodeEditorComponent : public Component,
  33948. public Timer,
  33949. public ScrollBarListener,
  33950. public CodeDocument::Listener,
  33951. public AsyncUpdater
  33952. {
  33953. public:
  33954. /** Creates an editor for a document.
  33955. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  33956. The object that you pass in is not owned or deleted by the editor - you must
  33957. make sure that it doesn't get deleted while this component is still using it.
  33958. @see CodeDocument
  33959. */
  33960. CodeEditorComponent (CodeDocument& document,
  33961. CodeTokeniser* const codeTokeniser);
  33962. /** Destructor. */
  33963. ~CodeEditorComponent();
  33964. /** Returns the code document that this component is editing. */
  33965. CodeDocument& getDocument() const throw() { return document; }
  33966. /** Loads the given content into the document.
  33967. This will completely reset the CodeDocument object, clear its undo history,
  33968. and fill it with this text.
  33969. */
  33970. void loadContent (const String& newContent);
  33971. /** Returns the standard character width. */
  33972. float getCharWidth() const throw() { return charWidth; }
  33973. /** Returns the height of a line of text, in pixels. */
  33974. int getLineHeight() const throw() { return lineHeight; }
  33975. /** Returns the number of whole lines visible on the screen,
  33976. This doesn't include a cut-off line that might be visible at the bottom if the
  33977. component's height isn't an exact multiple of the line-height.
  33978. */
  33979. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  33980. /** Returns the number of whole columns visible on the screen.
  33981. This doesn't include any cut-off columns at the right-hand edge.
  33982. */
  33983. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  33984. /** Returns the current caret position. */
  33985. const CodeDocument::Position getCaretPos() const { return caretPos; }
  33986. /** Moves the caret.
  33987. If selecting is true, the section of the document between the current
  33988. caret position and the new one will become selected. If false, any currently
  33989. selected region will be deselected.
  33990. */
  33991. void moveCaretTo (const CodeDocument::Position& newPos, const bool selecting);
  33992. /** Returns the on-screen position of a character in the document.
  33993. The rectangle returned is relative to this component's top-left origin.
  33994. */
  33995. const Rectangle getCharacterBounds (const CodeDocument::Position& pos) const throw();
  33996. /** Finds the character at a given on-screen position.
  33997. The co-ordinates are relative to this component's top-left origin.
  33998. */
  33999. const CodeDocument::Position getPositionAt (int x, int y);
  34000. void cursorLeft (const bool moveInWholeWordSteps, const bool selecting);
  34001. void cursorRight (const bool moveInWholeWordSteps, const bool selecting);
  34002. void cursorDown (const bool selecting);
  34003. void cursorUp (const bool selecting);
  34004. void pageDown (const bool selecting);
  34005. void pageUp (const bool selecting);
  34006. void scrollDown();
  34007. void scrollUp();
  34008. void scrollToLine (int newFirstLineOnScreen);
  34009. void scrollBy (int deltaLines);
  34010. void scrollToColumn (int newFirstColumnOnScreen);
  34011. void scrollToKeepCaretOnScreen();
  34012. void goToStartOfDocument (const bool selecting);
  34013. void goToStartOfLine (const bool selecting);
  34014. void goToEndOfDocument (const bool selecting);
  34015. void goToEndOfLine (const bool selecting);
  34016. void deselectAll();
  34017. void selectAll();
  34018. void insertTextAtCaret (const String& textToInsert);
  34019. void insertTabAtCaret();
  34020. void cut();
  34021. void copy();
  34022. void copyThenCut();
  34023. void paste();
  34024. void backspace (const bool moveInWholeWordSteps);
  34025. void deleteForward (const bool moveInWholeWordSteps);
  34026. void undo();
  34027. void redo();
  34028. /** Changes the current tab settings.
  34029. This lets you change the tab size and whether pressing the tab key inserts a
  34030. tab character, or its equivalent number of spaces.
  34031. */
  34032. void setTabSize (const int numSpacesPerTab,
  34033. const bool insertSpacesInsteadOfTabCharacters) throw();
  34034. /** Returns the current number of spaces per tab.
  34035. @see setTabSize
  34036. */
  34037. int getTabSize() const throw() { return spacesPerTab; }
  34038. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  34039. @see setTabSize
  34040. */
  34041. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  34042. /** Changes the font.
  34043. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  34044. */
  34045. void setFont (const Font& newFont);
  34046. /** Resets the syntax highlighting colours to the default ones provided by the
  34047. code tokeniser.
  34048. @see CodeTokeniser::getDefaultColour
  34049. */
  34050. void resetToDefaultColours();
  34051. /** Changes one of the syntax highlighting colours.
  34052. The token type values are dependent on the tokeniser being used - use
  34053. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34054. @see getColourForTokenType
  34055. */
  34056. void setColourForTokenType (const int tokenType, const Colour& colour);
  34057. /** Returns one of the syntax highlighting colours.
  34058. The token type values are dependent on the tokeniser being used - use
  34059. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34060. @see setColourForTokenType
  34061. */
  34062. const Colour getColourForTokenType (const int tokenType) const throw();
  34063. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  34064. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34065. methods.
  34066. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34067. */
  34068. enum ColourIds
  34069. {
  34070. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  34071. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  34072. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  34073. selected text. */
  34074. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  34075. enabled. */
  34076. };
  34077. /** Changes the size of the scrollbars. */
  34078. void setScrollbarThickness (const int thickness) throw();
  34079. /** @internal */
  34080. void resized();
  34081. /** @internal */
  34082. void paint (Graphics& g);
  34083. /** @internal */
  34084. bool keyPressed (const KeyPress& key);
  34085. /** @internal */
  34086. void mouseDown (const MouseEvent& e);
  34087. /** @internal */
  34088. void mouseDrag (const MouseEvent& e);
  34089. /** @internal */
  34090. void mouseUp (const MouseEvent& e);
  34091. /** @internal */
  34092. void mouseDoubleClick (const MouseEvent& e);
  34093. /** @internal */
  34094. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34095. /** @internal */
  34096. void timerCallback();
  34097. /** @internal */
  34098. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  34099. /** @internal */
  34100. void handleAsyncUpdate();
  34101. /** @internal */
  34102. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  34103. const CodeDocument::Position& affectedTextEnd);
  34104. juce_UseDebuggingNewOperator
  34105. private:
  34106. CodeDocument& document;
  34107. Font font;
  34108. int firstLineOnScreen, gutter, spacesPerTab;
  34109. float charWidth;
  34110. int lineHeight, linesOnScreen, columnsOnScreen;
  34111. int scrollbarThickness;
  34112. bool useSpacesForTabs;
  34113. double xOffset;
  34114. CodeDocument::Position caretPos;
  34115. CodeDocument::Position selectionStart, selectionEnd;
  34116. Component* caret;
  34117. ScrollBar* verticalScrollBar;
  34118. ScrollBar* horizontalScrollBar;
  34119. enum DragType
  34120. {
  34121. notDragging,
  34122. draggingSelectionStart,
  34123. draggingSelectionEnd
  34124. };
  34125. DragType dragType;
  34126. CodeTokeniser* codeTokeniser;
  34127. Array <Colour> coloursForTokenCategories;
  34128. OwnedArray <CodeEditorLine> lines;
  34129. void rebuildLineTokens();
  34130. OwnedArray <CodeDocument::Iterator> cachedIterators;
  34131. void clearCachedIterators (const int firstLineToBeInvalid) throw();
  34132. void updateCachedIterators (int maxLineNum);
  34133. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  34134. void updateScrollBars();
  34135. void scrollToLineInternal (int line);
  34136. void scrollToColumnInternal (double column);
  34137. void newTransaction();
  34138. int indexToColumn (int line, int index) const throw();
  34139. int columnToIndex (int line, int column) const throw();
  34140. CodeEditorComponent (const CodeEditorComponent&);
  34141. const CodeEditorComponent& operator= (const CodeEditorComponent&);
  34142. };
  34143. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34144. /********* End of inlined file: juce_CodeEditorComponent.h *********/
  34145. #endif
  34146. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34147. /********* Start of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  34148. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34149. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34150. /**
  34151. A simple lexical analyser for syntax colouring of C++ code.
  34152. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  34153. */
  34154. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  34155. {
  34156. public:
  34157. CPlusPlusCodeTokeniser();
  34158. ~CPlusPlusCodeTokeniser();
  34159. enum TokenType
  34160. {
  34161. tokenType_error = 0,
  34162. tokenType_comment,
  34163. tokenType_builtInKeyword,
  34164. tokenType_identifier,
  34165. tokenType_integerLiteral,
  34166. tokenType_floatLiteral,
  34167. tokenType_stringLiteral,
  34168. tokenType_operator,
  34169. tokenType_bracket,
  34170. tokenType_punctuation,
  34171. tokenType_preprocessor
  34172. };
  34173. int readNextToken (CodeDocument::Iterator& source);
  34174. const StringArray getTokenTypes();
  34175. const Colour getDefaultColour (const int tokenType);
  34176. juce_UseDebuggingNewOperator
  34177. };
  34178. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34179. /********* End of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  34180. #endif
  34181. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  34182. #endif
  34183. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34184. #endif
  34185. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  34186. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  34187. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  34188. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  34189. /********* Start of inlined file: juce_MenuBarModel.h *********/
  34190. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  34191. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  34192. class MenuBarModel;
  34193. /**
  34194. A class to receive callbacks when a MenuBarModel changes.
  34195. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  34196. */
  34197. class JUCE_API MenuBarModelListener
  34198. {
  34199. public:
  34200. /** Destructor. */
  34201. virtual ~MenuBarModelListener() {}
  34202. /** This callback is made when items are changed in the menu bar model.
  34203. */
  34204. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  34205. /** This callback is made when an application command is invoked that
  34206. is represented by one of the items in the menu bar model.
  34207. */
  34208. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  34209. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  34210. };
  34211. /**
  34212. A class for controlling MenuBar components.
  34213. This class is used to tell a MenuBar what menus to show, and to respond
  34214. to a menu being selected.
  34215. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  34216. */
  34217. class JUCE_API MenuBarModel : private AsyncUpdater,
  34218. private ApplicationCommandManagerListener
  34219. {
  34220. public:
  34221. MenuBarModel() throw();
  34222. /** Destructor. */
  34223. virtual ~MenuBarModel();
  34224. /** Call this when some of your menu items have changed.
  34225. This method will cause a callback to any MenuBarListener objects that
  34226. are registered with this model.
  34227. If this model is displaying items from an ApplicationCommandManager, you
  34228. can use the setApplicationCommandManagerToWatch() method to cause
  34229. change messages to be sent automatically when the ApplicationCommandManager
  34230. is changed.
  34231. @see addListener, removeListener, MenuBarListener
  34232. */
  34233. void menuItemsChanged();
  34234. /** Tells the menu bar to listen to the specified command manager, and to update
  34235. itself when the commands change.
  34236. This will also allow it to flash a menu name when a command from that menu
  34237. is invoked using a keystroke.
  34238. */
  34239. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  34240. /** Registers a listener for callbacks when the menu items in this model change.
  34241. The listener object will get callbacks when this object's menuItemsChanged()
  34242. method is called.
  34243. @see removeListener
  34244. */
  34245. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  34246. /** Removes a listener.
  34247. @see addListener
  34248. */
  34249. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  34250. /** This method must return a list of the names of the menus. */
  34251. virtual const StringArray getMenuBarNames() = 0;
  34252. /** This should return the popup menu to display for a given top-level menu.
  34253. @param topLevelMenuIndex the index of the top-level menu to show
  34254. @param menuName the name of the top-level menu item to show
  34255. */
  34256. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  34257. const String& menuName) = 0;
  34258. /** This is called when a menu item has been clicked on.
  34259. @param menuItemID the item ID of the PopupMenu item that was selected
  34260. @param topLevelMenuIndex the index of the top-level menu from which the item was
  34261. chosen (just in case you've used duplicate ID numbers
  34262. on more than one of the popup menus)
  34263. */
  34264. virtual void menuItemSelected (int menuItemID,
  34265. int topLevelMenuIndex) = 0;
  34266. #if JUCE_MAC || DOXYGEN
  34267. /** MAC ONLY - Sets the model that is currently being shown as the main
  34268. menu bar at the top of the screen on the Mac.
  34269. You can pass 0 to stop the current model being displayed. Be careful
  34270. not to delete a model while it is being used.
  34271. An optional extra menu can be specified, containing items to add to the top of
  34272. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  34273. an apple, it's the one next to it, with your application's name at the top
  34274. and the services menu etc on it). When one of these items is selected, the
  34275. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  34276. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  34277. object then newMenuBarModel must be non-null.
  34278. */
  34279. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  34280. const PopupMenu* extraAppleMenuItems = 0) throw();
  34281. /** MAC ONLY - Returns the menu model that is currently being shown as
  34282. the main menu bar.
  34283. */
  34284. static MenuBarModel* getMacMainMenu() throw();
  34285. #endif
  34286. /** @internal */
  34287. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  34288. /** @internal */
  34289. void applicationCommandListChanged();
  34290. /** @internal */
  34291. void handleAsyncUpdate();
  34292. juce_UseDebuggingNewOperator
  34293. private:
  34294. ApplicationCommandManager* manager;
  34295. SortedSet <void*> listeners;
  34296. MenuBarModel (const MenuBarModel&);
  34297. const MenuBarModel& operator= (const MenuBarModel&);
  34298. };
  34299. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  34300. /********* End of inlined file: juce_MenuBarModel.h *********/
  34301. /**
  34302. A menu bar component.
  34303. @see MenuBarModel
  34304. */
  34305. class JUCE_API MenuBarComponent : public Component,
  34306. private MenuBarModelListener,
  34307. private Timer
  34308. {
  34309. public:
  34310. /** Creates a menu bar.
  34311. @param model the model object to use to control this bar. You can
  34312. pass 0 into this if you like, and set the model later
  34313. using the setModel() method
  34314. */
  34315. MenuBarComponent (MenuBarModel* const model);
  34316. /** Destructor. */
  34317. ~MenuBarComponent();
  34318. /** Changes the model object to use to control the bar.
  34319. This can be 0, in which case the bar will be empty. Don't delete the object
  34320. that is passed-in while it's still being used by this MenuBar.
  34321. */
  34322. void setModel (MenuBarModel* const newModel);
  34323. /** Pops up one of the menu items.
  34324. This lets you manually open one of the menus - it could be triggered by a
  34325. key shortcut, for example.
  34326. */
  34327. void showMenu (const int menuIndex);
  34328. /** @internal */
  34329. void paint (Graphics& g);
  34330. /** @internal */
  34331. void resized();
  34332. /** @internal */
  34333. void mouseEnter (const MouseEvent& e);
  34334. /** @internal */
  34335. void mouseExit (const MouseEvent& e);
  34336. /** @internal */
  34337. void mouseDown (const MouseEvent& e);
  34338. /** @internal */
  34339. void mouseDrag (const MouseEvent& e);
  34340. /** @internal */
  34341. void mouseUp (const MouseEvent& e);
  34342. /** @internal */
  34343. void mouseMove (const MouseEvent& e);
  34344. /** @internal */
  34345. void inputAttemptWhenModal();
  34346. /** @internal */
  34347. void handleCommandMessage (int commandId);
  34348. /** @internal */
  34349. bool keyPressed (const KeyPress& key);
  34350. /** @internal */
  34351. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  34352. /** @internal */
  34353. void menuCommandInvoked (MenuBarModel* menuBarModel,
  34354. const ApplicationCommandTarget::InvocationInfo& info);
  34355. juce_UseDebuggingNewOperator
  34356. private:
  34357. MenuBarModel* model;
  34358. StringArray menuNames;
  34359. Array <int> xPositions;
  34360. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  34361. int lastMouseX, lastMouseY;
  34362. bool inModalState;
  34363. Component* currentPopup;
  34364. int getItemAt (int x, int y);
  34365. void updateItemUnderMouse (const int x, const int y);
  34366. void hideCurrentMenu();
  34367. void timerCallback();
  34368. void repaintMenuItem (int index);
  34369. MenuBarComponent (const MenuBarComponent&);
  34370. const MenuBarComponent& operator= (const MenuBarComponent&);
  34371. };
  34372. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  34373. /********* End of inlined file: juce_MenuBarComponent.h *********/
  34374. #endif
  34375. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  34376. #endif
  34377. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  34378. #endif
  34379. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  34380. #endif
  34381. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34382. /********* Start of inlined file: juce_ComponentDragger.h *********/
  34383. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34384. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34385. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  34386. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34387. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34388. /**
  34389. A class that imposes restrictions on a Component's size or position.
  34390. This is used by classes such as ResizableCornerComponent,
  34391. ResizableBorderComponent and ResizableWindow.
  34392. The base class can impose some basic size and position limits, but you can
  34393. also subclass this for custom uses.
  34394. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  34395. */
  34396. class JUCE_API ComponentBoundsConstrainer
  34397. {
  34398. public:
  34399. /** When first created, the object will not impose any restrictions on the components. */
  34400. ComponentBoundsConstrainer() throw();
  34401. /** Destructor. */
  34402. virtual ~ComponentBoundsConstrainer();
  34403. /** Imposes a minimum width limit. */
  34404. void setMinimumWidth (const int minimumWidth) throw();
  34405. /** Returns the current minimum width. */
  34406. int getMinimumWidth() const throw() { return minW; }
  34407. /** Imposes a maximum width limit. */
  34408. void setMaximumWidth (const int maximumWidth) throw();
  34409. /** Returns the current maximum width. */
  34410. int getMaximumWidth() const throw() { return maxW; }
  34411. /** Imposes a minimum height limit. */
  34412. void setMinimumHeight (const int minimumHeight) throw();
  34413. /** Returns the current minimum height. */
  34414. int getMinimumHeight() const throw() { return minH; }
  34415. /** Imposes a maximum height limit. */
  34416. void setMaximumHeight (const int maximumHeight) throw();
  34417. /** Returns the current maximum height. */
  34418. int getMaximumHeight() const throw() { return maxH; }
  34419. /** Imposes a minimum width and height limit. */
  34420. void setMinimumSize (const int minimumWidth,
  34421. const int minimumHeight) throw();
  34422. /** Imposes a maximum width and height limit. */
  34423. void setMaximumSize (const int maximumWidth,
  34424. const int maximumHeight) throw();
  34425. /** Set all the maximum and minimum dimensions. */
  34426. void setSizeLimits (const int minimumWidth,
  34427. const int minimumHeight,
  34428. const int maximumWidth,
  34429. const int maximumHeight) throw();
  34430. /** Sets the amount by which the component is allowed to go off-screen.
  34431. The values indicate how many pixels must remain on-screen when dragged off
  34432. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  34433. when the component goes off the top of the screen, its y-position will be
  34434. clipped so that there are always at least 10 pixels on-screen. In other words,
  34435. the lowest y-position it can take would be (10 - the component's height).
  34436. If you pass 0 or less for one of these amounts, the component is allowed
  34437. to move beyond that edge completely, with no restrictions at all.
  34438. If you pass a very large number (i.e. larger that the dimensions of the
  34439. component itself), then the component won't be allowed to overlap that
  34440. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  34441. the component will bump into the left side of the screen and go no further.
  34442. */
  34443. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  34444. const int minimumWhenOffTheLeft,
  34445. const int minimumWhenOffTheBottom,
  34446. const int minimumWhenOffTheRight) throw();
  34447. /** Specifies a width-to-height ratio that the resizer should always maintain.
  34448. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  34449. will always be maintained as this multiple of the height.
  34450. @see setResizeLimits
  34451. */
  34452. void setFixedAspectRatio (const double widthOverHeight) throw();
  34453. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  34454. If no aspect ratio is being enforced, this will return 0.
  34455. */
  34456. double getFixedAspectRatio() const throw();
  34457. /** This callback changes the given co-ordinates to impose whatever the current
  34458. constraints are set to be.
  34459. @param x the x position that should be examined and adjusted
  34460. @param y the y position that should be examined and adjusted
  34461. @param w the width that should be examined and adjusted
  34462. @param h the height that should be examined and adjusted
  34463. @param previousBounds the component's current size
  34464. @param limits the region in which the component can be positioned
  34465. @param isStretchingTop whether the top edge of the component is being resized
  34466. @param isStretchingLeft whether the left edge of the component is being resized
  34467. @param isStretchingBottom whether the bottom edge of the component is being resized
  34468. @param isStretchingRight whether the right edge of the component is being resized
  34469. */
  34470. virtual void checkBounds (int& x, int& y, int& w, int& h,
  34471. const Rectangle& previousBounds,
  34472. const Rectangle& limits,
  34473. const bool isStretchingTop,
  34474. const bool isStretchingLeft,
  34475. const bool isStretchingBottom,
  34476. const bool isStretchingRight);
  34477. /** This callback happens when the resizer is about to start dragging. */
  34478. virtual void resizeStart();
  34479. /** This callback happens when the resizer has finished dragging. */
  34480. virtual void resizeEnd();
  34481. /** Checks the given bounds, and then sets the component to the corrected size. */
  34482. void setBoundsForComponent (Component* const component,
  34483. int x, int y, int w, int h,
  34484. const bool isStretchingTop,
  34485. const bool isStretchingLeft,
  34486. const bool isStretchingBottom,
  34487. const bool isStretchingRight);
  34488. /** Performs a check on the current size of a component, and moves or resizes
  34489. it if it fails the constraints.
  34490. */
  34491. void checkComponentBounds (Component* component);
  34492. /** Called by setBoundsForComponent() to apply a new constrained size to a
  34493. component.
  34494. By default this just calls setBounds(), but it virtual in case it's needed for
  34495. extremely cunning purposes.
  34496. */
  34497. virtual void applyBoundsToComponent (Component* component,
  34498. int x, int y, int w, int h);
  34499. juce_UseDebuggingNewOperator
  34500. private:
  34501. int minW, maxW, minH, maxH;
  34502. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  34503. double aspectRatio;
  34504. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  34505. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  34506. };
  34507. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34508. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  34509. /**
  34510. An object to take care of the logic for dragging components around with the mouse.
  34511. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  34512. then in your mouseDrag() callback, call dragComponent().
  34513. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  34514. to limit the component's position and keep it on-screen.
  34515. e.g. @code
  34516. class MyDraggableComp
  34517. {
  34518. ComponentDragger myDragger;
  34519. void mouseDown (const MouseEvent& e)
  34520. {
  34521. myDragger.startDraggingComponent (this, 0);
  34522. }
  34523. void mouseDrag (const MouseEvent& e)
  34524. {
  34525. myDragger.dragComponent (this, e);
  34526. }
  34527. };
  34528. @endcode
  34529. */
  34530. class JUCE_API ComponentDragger
  34531. {
  34532. public:
  34533. /** Creates a ComponentDragger. */
  34534. ComponentDragger();
  34535. /** Destructor. */
  34536. virtual ~ComponentDragger();
  34537. /** Call this from your component's mouseDown() method, to prepare for dragging.
  34538. @param componentToDrag the component that you want to drag
  34539. @param constrainer a constrainer object to use to keep the component
  34540. from going offscreen
  34541. @see dragComponent
  34542. */
  34543. void startDraggingComponent (Component* const componentToDrag,
  34544. ComponentBoundsConstrainer* constrainer);
  34545. /** Call this from your mouseDrag() callback to move the component.
  34546. This will move the component, but will first check the validity of the
  34547. component's new position using the checkPosition() method, which you
  34548. can override if you need to enforce special positioning limits on the
  34549. component.
  34550. @param componentToDrag the component that you want to drag
  34551. @param e the current mouse-drag event
  34552. @see dragComponent
  34553. */
  34554. void dragComponent (Component* const componentToDrag,
  34555. const MouseEvent& e);
  34556. juce_UseDebuggingNewOperator
  34557. private:
  34558. ComponentBoundsConstrainer* constrainer;
  34559. int originalX, originalY;
  34560. };
  34561. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34562. /********* End of inlined file: juce_ComponentDragger.h *********/
  34563. #endif
  34564. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  34565. #endif
  34566. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34567. #endif
  34568. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34569. /********* Start of inlined file: juce_LassoComponent.h *********/
  34570. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34571. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34572. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  34573. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  34574. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  34575. /** Manages a list of selectable items.
  34576. Use one of these to keep a track of things that the user has highlighted, like
  34577. icons or things in a list.
  34578. The class is templated so that you can use it to hold either a set of pointers
  34579. to objects, or a set of ID numbers or handles, for cases where each item may
  34580. not always have a corresponding object.
  34581. To be informed when items are selected/deselected, register a ChangeListener with
  34582. this object.
  34583. @see SelectableObject
  34584. */
  34585. template <class SelectableItemType>
  34586. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  34587. {
  34588. public:
  34589. /** Creates an empty set. */
  34590. SelectedItemSet()
  34591. {
  34592. }
  34593. /** Creates a set based on an array of items. */
  34594. SelectedItemSet (const Array <SelectableItemType>& items)
  34595. : selectedItems (items)
  34596. {
  34597. }
  34598. /** Creates a copy of another set. */
  34599. SelectedItemSet (const SelectedItemSet& other)
  34600. : selectedItems (other.selectedItems)
  34601. {
  34602. }
  34603. /** Creates a copy of another set. */
  34604. const SelectedItemSet& operator= (const SelectedItemSet& other)
  34605. {
  34606. if (selectedItems != other.selectedItems)
  34607. {
  34608. selectedItems = other.selectedItems;
  34609. changed();
  34610. }
  34611. return *this;
  34612. }
  34613. /** Destructor. */
  34614. ~SelectedItemSet()
  34615. {
  34616. }
  34617. /** Clears any other currently selected items, and selects this item.
  34618. If this item is already the only thing selected, no change notification
  34619. will be sent out.
  34620. @see addToSelection, addToSelectionBasedOnModifiers
  34621. */
  34622. void selectOnly (SelectableItemType item)
  34623. {
  34624. if (isSelected (item))
  34625. {
  34626. for (int i = selectedItems.size(); --i >= 0;)
  34627. {
  34628. if (selectedItems.getUnchecked(i) != item)
  34629. {
  34630. deselect (selectedItems.getUnchecked(i));
  34631. i = jmin (i, selectedItems.size());
  34632. }
  34633. }
  34634. }
  34635. else
  34636. {
  34637. deselectAll();
  34638. changed();
  34639. selectedItems.add (item);
  34640. itemSelected (item);
  34641. }
  34642. }
  34643. /** Selects an item.
  34644. If the item is already selected, no change notification will be sent out.
  34645. @see selectOnly, addToSelectionBasedOnModifiers
  34646. */
  34647. void addToSelection (SelectableItemType item)
  34648. {
  34649. if (! isSelected (item))
  34650. {
  34651. changed();
  34652. selectedItems.add (item);
  34653. itemSelected (item);
  34654. }
  34655. }
  34656. /** Selects or deselects an item.
  34657. This will use the modifier keys to decide whether to deselect other items
  34658. first.
  34659. So if the shift key is held down, the item will be added without deselecting
  34660. anything (same as calling addToSelection() )
  34661. If no modifiers are down, the current selection will be cleared first (same
  34662. as calling selectOnly() )
  34663. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  34664. so it'll be added to the set unless it's already there, in which case it'll be
  34665. deselected.
  34666. If the items that you're selecting can also be dragged, you may need to use the
  34667. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  34668. subtleties of this kind of usage.
  34669. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  34670. */
  34671. void addToSelectionBasedOnModifiers (SelectableItemType item,
  34672. const ModifierKeys& modifiers)
  34673. {
  34674. if (modifiers.isShiftDown())
  34675. {
  34676. addToSelection (item);
  34677. }
  34678. else if (modifiers.isCommandDown())
  34679. {
  34680. if (isSelected (item))
  34681. deselect (item);
  34682. else
  34683. addToSelection (item);
  34684. }
  34685. else
  34686. {
  34687. selectOnly (item);
  34688. }
  34689. }
  34690. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  34691. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  34692. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  34693. makes it easy to handle multiple-selection of sets of objects that can also
  34694. be dragged.
  34695. For example, if you have several items already selected, and you click on
  34696. one of them (without dragging), then you'd expect this to deselect the other, and
  34697. just select the item you clicked on. But if you had clicked on this item and
  34698. dragged it, you'd have expected them all to stay selected.
  34699. When you call this method, you'll need to store the boolean result, because the
  34700. addToSelectionOnMouseUp() method will need to be know this value.
  34701. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  34702. */
  34703. bool addToSelectionOnMouseDown (SelectableItemType item,
  34704. const ModifierKeys& modifiers)
  34705. {
  34706. if (isSelected (item))
  34707. {
  34708. return ! modifiers.isPopupMenu();
  34709. }
  34710. else
  34711. {
  34712. addToSelectionBasedOnModifiers (item, modifiers);
  34713. return false;
  34714. }
  34715. }
  34716. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  34717. Call this during a mouseUp callback, when you have previously called the
  34718. addToSelectionOnMouseDown() method during your mouseDown event.
  34719. See addToSelectionOnMouseDown() for more info
  34720. @param item the item to select (or deselect)
  34721. @param modifiers the modifiers from the mouse-up event
  34722. @param wasItemDragged true if your item was dragged during the mouse click
  34723. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  34724. back from the addToSelectionOnMouseDown() call that you
  34725. should have made during the matching mouseDown event
  34726. */
  34727. void addToSelectionOnMouseUp (SelectableItemType item,
  34728. const ModifierKeys& modifiers,
  34729. const bool wasItemDragged,
  34730. const bool resultOfMouseDownSelectMethod)
  34731. {
  34732. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  34733. addToSelectionBasedOnModifiers (item, modifiers);
  34734. }
  34735. /** Deselects an item. */
  34736. void deselect (SelectableItemType item)
  34737. {
  34738. const int i = selectedItems.indexOf (item);
  34739. if (i >= 0)
  34740. {
  34741. changed();
  34742. itemDeselected (selectedItems.remove (i));
  34743. }
  34744. }
  34745. /** Deselects all items. */
  34746. void deselectAll()
  34747. {
  34748. if (selectedItems.size() > 0)
  34749. {
  34750. changed();
  34751. for (int i = selectedItems.size(); --i >= 0;)
  34752. {
  34753. itemDeselected (selectedItems.remove (i));
  34754. i = jmin (i, selectedItems.size());
  34755. }
  34756. }
  34757. }
  34758. /** Returns the number of currently selected items.
  34759. @see getSelectedItem
  34760. */
  34761. int getNumSelected() const throw()
  34762. {
  34763. return selectedItems.size();
  34764. }
  34765. /** Returns one of the currently selected items.
  34766. Returns 0 if the index is out-of-range.
  34767. @see getNumSelected
  34768. */
  34769. SelectableItemType getSelectedItem (const int index) const throw()
  34770. {
  34771. return selectedItems [index];
  34772. }
  34773. /** True if this item is currently selected. */
  34774. bool isSelected (const SelectableItemType item) const throw()
  34775. {
  34776. return selectedItems.contains (item);
  34777. }
  34778. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  34779. /** Can be overridden to do special handling when an item is selected.
  34780. For example, if the item is an object, you might want to call it and tell
  34781. it that it's being selected.
  34782. */
  34783. virtual void itemSelected (SelectableItemType item) {}
  34784. /** Can be overridden to do special handling when an item is deselected.
  34785. For example, if the item is an object, you might want to call it and tell
  34786. it that it's being deselected.
  34787. */
  34788. virtual void itemDeselected (SelectableItemType item) {}
  34789. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  34790. */
  34791. void changed (const bool synchronous = false)
  34792. {
  34793. if (synchronous)
  34794. sendSynchronousChangeMessage (this);
  34795. else
  34796. sendChangeMessage (this);
  34797. }
  34798. juce_UseDebuggingNewOperator
  34799. private:
  34800. Array <SelectableItemType> selectedItems;
  34801. };
  34802. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  34803. /********* End of inlined file: juce_SelectedItemSet.h *********/
  34804. /**
  34805. A class used by the LassoComponent to manage the things that it selects.
  34806. This allows the LassoComponent to find out which items are within the lasso,
  34807. and to change the list of selected items.
  34808. @see LassoComponent, SelectedItemSet
  34809. */
  34810. template <class SelectableItemType>
  34811. class LassoSource
  34812. {
  34813. public:
  34814. /** Destructor. */
  34815. virtual ~LassoSource() {}
  34816. /** Returns the set of items that lie within a given lassoable region.
  34817. Your implementation of this method must find all the relevent items that lie
  34818. within the given rectangle. and add them to the itemsFound array.
  34819. The co-ordinates are relative to the top-left of the lasso component's parent
  34820. component. (i.e. they are the same as the size and position of the lasso
  34821. component itself).
  34822. */
  34823. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  34824. int x, int y, int width, int height) = 0;
  34825. /** Returns the SelectedItemSet that the lasso should update.
  34826. This set will be continuously updated by the LassoComponent as it gets
  34827. dragged around, so make sure that you've got a ChangeListener attached to
  34828. the set so that your UI objects will know when the selection changes and
  34829. be able to update themselves appropriately.
  34830. */
  34831. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  34832. };
  34833. /**
  34834. A component that acts as a rectangular selection region, which you drag with
  34835. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  34836. To use one of these:
  34837. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  34838. component, and call its beginLasso() method, giving it a
  34839. suitable LassoSource object that it can use to find out which items are in
  34840. the active area.
  34841. - Each time your parent component gets a mouseDrag event, call dragLasso()
  34842. to update the lasso's position - it will use its LassoSource to calculate and
  34843. update the current selection.
  34844. - After the drag has finished and you get a mouseUp callback, you should call
  34845. endLasso() to clean up. This will make the lasso component invisible, and you
  34846. can remove it from the parent component, or delete it.
  34847. The class takes into account the modifier keys that are being held down while
  34848. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  34849. be added to the original selection; if ctrl or command is pressed, they will be
  34850. xor'ed with any previously selected items.
  34851. @see LassoSource, SelectedItemSet
  34852. */
  34853. template <class SelectableItemType>
  34854. class LassoComponent : public Component
  34855. {
  34856. public:
  34857. /** Creates a Lasso component.
  34858. The fill colour is used to fill the lasso'ed rectangle, and the outline
  34859. colour is used to draw a line around its edge.
  34860. */
  34861. LassoComponent (const int outlineThickness_ = 1)
  34862. : source (0),
  34863. outlineThickness (outlineThickness_)
  34864. {
  34865. }
  34866. /** Destructor. */
  34867. ~LassoComponent()
  34868. {
  34869. }
  34870. /** Call this in your mouseDown event, to initialise a drag.
  34871. Pass in a suitable LassoSource object which the lasso will use to find
  34872. the items and change the selection.
  34873. After using this method to initialise the lasso, repeatedly call dragLasso()
  34874. in your component's mouseDrag callback.
  34875. @see dragLasso, endLasso, LassoSource
  34876. */
  34877. void beginLasso (const MouseEvent& e,
  34878. LassoSource <SelectableItemType>* const lassoSource)
  34879. {
  34880. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  34881. jassert (lassoSource != 0); // the source can't be null!
  34882. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  34883. source = lassoSource;
  34884. if (lassoSource != 0)
  34885. originalSelection = lassoSource->getLassoSelection().getItemArray();
  34886. setSize (0, 0);
  34887. }
  34888. /** Call this in your mouseDrag event, to update the lasso's position.
  34889. This must be repeatedly calling when the mouse is dragged, after you've
  34890. first initialised the lasso with beginLasso().
  34891. This method takes into account the modifier keys that are being held down, so
  34892. if shift is pressed, then the lassoed items will be added to any that were
  34893. previously selected; if ctrl or command is pressed, then they will be xor'ed
  34894. with previously selected items.
  34895. @see beginLasso, endLasso
  34896. */
  34897. void dragLasso (const MouseEvent& e)
  34898. {
  34899. if (source != 0)
  34900. {
  34901. const int x1 = e.getMouseDownX();
  34902. const int y1 = e.getMouseDownY();
  34903. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  34904. setVisible (true);
  34905. Array <SelectableItemType> itemsInLasso;
  34906. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  34907. if (e.mods.isShiftDown())
  34908. {
  34909. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  34910. itemsInLasso.addArray (originalSelection);
  34911. }
  34912. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  34913. {
  34914. Array <SelectableItemType> originalMinusNew (originalSelection);
  34915. originalMinusNew.removeValuesIn (itemsInLasso);
  34916. itemsInLasso.removeValuesIn (originalSelection);
  34917. itemsInLasso.addArray (originalMinusNew);
  34918. }
  34919. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  34920. }
  34921. }
  34922. /** Call this in your mouseUp event, after the lasso has been dragged.
  34923. @see beginLasso, dragLasso
  34924. */
  34925. void endLasso()
  34926. {
  34927. source = 0;
  34928. originalSelection.clear();
  34929. setVisible (false);
  34930. }
  34931. /** A set of colour IDs to use to change the colour of various aspects of the label.
  34932. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34933. methods.
  34934. Note that you can also use the constants from TextEditor::ColourIds to change the
  34935. colour of the text editor that is opened when a label is editable.
  34936. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34937. */
  34938. enum ColourIds
  34939. {
  34940. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  34941. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  34942. };
  34943. /** @internal */
  34944. void paint (Graphics& g)
  34945. {
  34946. g.fillAll (findColour (lassoFillColourId));
  34947. g.setColour (findColour (lassoOutlineColourId));
  34948. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  34949. // this suggests that you've left a lasso comp lying around after the
  34950. // mouse drag has finished.. Be careful to call endLasso() when you get a
  34951. // mouse-up event.
  34952. jassert (isMouseButtonDownAnywhere());
  34953. }
  34954. /** @internal */
  34955. bool hitTest (int x, int y) { return false; }
  34956. juce_UseDebuggingNewOperator
  34957. private:
  34958. Array <SelectableItemType> originalSelection;
  34959. LassoSource <SelectableItemType>* source;
  34960. int outlineThickness;
  34961. };
  34962. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34963. /********* End of inlined file: juce_LassoComponent.h *********/
  34964. #endif
  34965. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  34966. #endif
  34967. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  34968. #endif
  34969. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34970. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  34971. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34972. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34973. /**
  34974. Monitors a component for mouse activity, and triggers a callback
  34975. when the mouse hovers in one place for a specified length of time.
  34976. To use a hover-detector, just create one and call its setHoverComponent()
  34977. method to start it watching a component. You can call setHoverComponent (0)
  34978. to make it inactive.
  34979. (Be careful not to delete a component that's being monitored without first
  34980. stopping or deleting the hover detector).
  34981. */
  34982. class JUCE_API MouseHoverDetector
  34983. {
  34984. public:
  34985. /** Creates a hover detector.
  34986. Initially the object is inactive, and you need to tell it which component
  34987. to monitor, using the setHoverComponent() method.
  34988. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  34989. needs to stay still before the mouseHovered() method
  34990. is invoked. You can change this setting later with
  34991. the setHoverTimeMillisecs() method
  34992. */
  34993. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  34994. /** Destructor. */
  34995. virtual ~MouseHoverDetector();
  34996. /** Changes the time for which the mouse has to stay still before it's considered
  34997. to be hovering.
  34998. */
  34999. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  35000. /** Changes the component that's being monitored for hovering.
  35001. Be careful not to delete a component that's being monitored without first
  35002. stopping or deleting the hover detector.
  35003. */
  35004. void setHoverComponent (Component* const newSourceComponent);
  35005. protected:
  35006. /** Called back when the mouse hovers.
  35007. After the mouse has stayed still over the component for the length of time
  35008. specified by setHoverTimeMillisecs(), this method will be invoked.
  35009. When the mouse is first moved after this callback has occurred, the
  35010. mouseMovedAfterHover() method will be called.
  35011. @param mouseX the mouse's X position relative to the component being monitored
  35012. @param mouseY the mouse's Y position relative to the component being monitored
  35013. */
  35014. virtual void mouseHovered (int mouseX,
  35015. int mouseY) = 0;
  35016. /** Called when the mouse is moved away after just having hovered. */
  35017. virtual void mouseMovedAfterHover() = 0;
  35018. private:
  35019. class JUCE_API HoverDetectorInternal : public MouseListener,
  35020. public Timer
  35021. {
  35022. public:
  35023. MouseHoverDetector* owner;
  35024. int lastX, lastY;
  35025. void timerCallback();
  35026. void mouseEnter (const MouseEvent&);
  35027. void mouseExit (const MouseEvent&);
  35028. void mouseDown (const MouseEvent&);
  35029. void mouseUp (const MouseEvent&);
  35030. void mouseMove (const MouseEvent&);
  35031. void mouseWheelMove (const MouseEvent&, float, float);
  35032. } internalTimer;
  35033. friend class HoverDetectorInternal;
  35034. Component* source;
  35035. int hoverTimeMillisecs;
  35036. bool hasJustHovered;
  35037. void hoverTimerCallback();
  35038. void checkJustHoveredCallback();
  35039. };
  35040. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  35041. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  35042. #endif
  35043. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  35044. #endif
  35045. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  35046. #endif
  35047. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  35048. #endif
  35049. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  35050. #endif
  35051. #ifndef __JUCE_LABEL_JUCEHEADER__
  35052. #endif
  35053. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  35054. /********* Start of inlined file: juce_ProgressBar.h *********/
  35055. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  35056. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  35057. /**
  35058. A progress bar component.
  35059. To use this, just create one and make it visible. It'll run its own timer
  35060. to keep an eye on a variable that you give it, and will automatically
  35061. redraw itself when the variable changes.
  35062. For an easy way of running a background task with a dialog box showing its
  35063. progress, see the ThreadWithProgressWindow class.
  35064. @see ThreadWithProgressWindow
  35065. */
  35066. class JUCE_API ProgressBar : public Component,
  35067. public SettableTooltipClient,
  35068. private Timer
  35069. {
  35070. public:
  35071. /** Creates a ProgressBar.
  35072. @param progress pass in a reference to a double that you're going to
  35073. update with your task's progress. The ProgressBar will
  35074. monitor the value of this variable and will redraw itself
  35075. when the value changes. The range is from 0 to 1.0. Obviously
  35076. you'd better be careful not to delete this variable while the
  35077. ProgressBar still exists!
  35078. */
  35079. ProgressBar (double& progress);
  35080. /** Destructor. */
  35081. ~ProgressBar();
  35082. /** Turns the percentage display on or off.
  35083. By default this is on, and the progress bar will display a text string showing
  35084. its current percentage.
  35085. */
  35086. void setPercentageDisplay (const bool shouldDisplayPercentage);
  35087. /** Gives the progress bar a string to display inside it.
  35088. If you call this, it will turn off the percentage display.
  35089. @see setPercentageDisplay
  35090. */
  35091. void setTextToDisplay (const String& text);
  35092. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  35093. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35094. methods.
  35095. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35096. */
  35097. enum ColourIds
  35098. {
  35099. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  35100. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  35101. classes will probably use variations on this colour. */
  35102. };
  35103. juce_UseDebuggingNewOperator
  35104. protected:
  35105. /** @internal */
  35106. void paint (Graphics& g);
  35107. /** @internal */
  35108. void lookAndFeelChanged();
  35109. /** @internal */
  35110. void visibilityChanged();
  35111. /** @internal */
  35112. void colourChanged();
  35113. private:
  35114. double& progress;
  35115. double currentValue;
  35116. bool displayPercentage;
  35117. String displayedMessage, currentMessage;
  35118. uint32 lastCallbackTime;
  35119. void timerCallback();
  35120. ProgressBar (const ProgressBar&);
  35121. const ProgressBar& operator= (const ProgressBar&);
  35122. };
  35123. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  35124. /********* End of inlined file: juce_ProgressBar.h *********/
  35125. #endif
  35126. #ifndef __JUCE_SLIDER_JUCEHEADER__
  35127. /********* Start of inlined file: juce_Slider.h *********/
  35128. #ifndef __JUCE_SLIDER_JUCEHEADER__
  35129. #define __JUCE_SLIDER_JUCEHEADER__
  35130. /********* Start of inlined file: juce_SliderListener.h *********/
  35131. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  35132. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  35133. class Slider;
  35134. /**
  35135. A class for receiving callbacks from a Slider.
  35136. To be told when a slider's value changes, you can register a SliderListener
  35137. object using Slider::addListener().
  35138. @see Slider::addListener, Slider::removeListener
  35139. */
  35140. class JUCE_API SliderListener
  35141. {
  35142. public:
  35143. /** Destructor. */
  35144. virtual ~SliderListener() {}
  35145. /** Called when the slider's value is changed.
  35146. This may be caused by dragging it, or by typing in its text entry box,
  35147. or by a call to Slider::setValue().
  35148. You can find out the new value using Slider::getValue().
  35149. @see Slider::valueChanged
  35150. */
  35151. virtual void sliderValueChanged (Slider* slider) = 0;
  35152. /** Called when the slider is about to be dragged.
  35153. This is called when a drag begins, then it's followed by multiple calls
  35154. to sliderValueChanged(), and then sliderDragEnded() is called after the
  35155. user lets go.
  35156. @see sliderDragEnded, Slider::startedDragging
  35157. */
  35158. virtual void sliderDragStarted (Slider* slider);
  35159. /** Called after a drag operation has finished.
  35160. @see sliderDragStarted, Slider::stoppedDragging
  35161. */
  35162. virtual void sliderDragEnded (Slider* slider);
  35163. };
  35164. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  35165. /********* End of inlined file: juce_SliderListener.h *********/
  35166. /**
  35167. A slider control for changing a value.
  35168. The slider can be horizontal, vertical, or rotary, and can optionally have
  35169. a text-box inside it to show an editable display of the current value.
  35170. To use it, create a Slider object and use the setSliderStyle() method
  35171. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  35172. To define the values that it can be set to, see the setRange() and setValue() methods.
  35173. There are also lots of custom tweaks you can do by subclassing and overriding
  35174. some of the virtual methods, such as changing the scaling, changing the format of
  35175. the text display, custom ways of limiting the values, etc.
  35176. You can register SliderListeners with a slider, which will be informed when the value
  35177. changes, or a subclass can override valueChanged() to be informed synchronously.
  35178. @see SliderListener
  35179. */
  35180. class JUCE_API Slider : public Component,
  35181. public SettableTooltipClient,
  35182. private AsyncUpdater,
  35183. private ButtonListener,
  35184. private LabelListener
  35185. {
  35186. public:
  35187. /** Creates a slider.
  35188. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  35189. setRange(), etc.
  35190. */
  35191. Slider (const String& componentName);
  35192. /** Destructor. */
  35193. ~Slider();
  35194. /** The types of slider available.
  35195. @see setSliderStyle, setRotaryParameters
  35196. */
  35197. enum SliderStyle
  35198. {
  35199. LinearHorizontal, /**< A traditional horizontal slider. */
  35200. LinearVertical, /**< A traditional vertical slider. */
  35201. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  35202. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  35203. @see setRotaryParameters */
  35204. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  35205. @see setRotaryParameters */
  35206. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  35207. @see setRotaryParameters */
  35208. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  35209. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  35210. @see setMinValue, setMaxValue */
  35211. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  35212. @see setMinValue, setMaxValue */
  35213. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  35214. value, with the current value being somewhere between them.
  35215. @see setMinValue, setMaxValue */
  35216. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  35217. value, with the current value being somewhere between them.
  35218. @see setMinValue, setMaxValue */
  35219. };
  35220. /** Changes the type of slider interface being used.
  35221. @param newStyle the type of interface
  35222. @see setRotaryParameters, setVelocityBasedMode,
  35223. */
  35224. void setSliderStyle (const SliderStyle newStyle);
  35225. /** Returns the slider's current style.
  35226. @see setSliderStyle
  35227. */
  35228. SliderStyle getSliderStyle() const throw() { return style; }
  35229. /** Changes the properties of a rotary slider.
  35230. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  35231. the slider's minimum value is represented
  35232. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  35233. the slider's maximum value is represented. This must be
  35234. greater than startAngleRadians
  35235. @param stopAtEnd if true, then when the slider is dragged around past the
  35236. minimum or maximum, it'll stop there; if false, it'll wrap
  35237. back to the opposite value
  35238. */
  35239. void setRotaryParameters (const float startAngleRadians,
  35240. const float endAngleRadians,
  35241. const bool stopAtEnd);
  35242. /** Sets the distance the mouse has to move to drag the slider across
  35243. the full extent of its range.
  35244. This only applies when in modes like RotaryHorizontalDrag, where it's using
  35245. relative mouse movements to adjust the slider.
  35246. */
  35247. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  35248. /** Changes the way the the mouse is used when dragging the slider.
  35249. If true, this will turn on velocity-sensitive dragging, so that
  35250. the faster the mouse moves, the bigger the movement to the slider. This
  35251. helps when making accurate adjustments if the slider's range is quite large.
  35252. If false, the slider will just try to snap to wherever the mouse is.
  35253. */
  35254. void setVelocityBasedMode (const bool isVelocityBased) throw();
  35255. /** Returns true if velocity-based mode is active.
  35256. @see setVelocityBasedMode
  35257. */
  35258. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  35259. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  35260. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  35261. or if you're holding down ctrl.
  35262. @param sensitivity higher values than 1.0 increase the range of acceleration used
  35263. @param threshold the minimum number of pixels that the mouse needs to move for it
  35264. to be treated as a movement
  35265. @param offset values greater than 0.0 increase the minimum speed that will be used when
  35266. the threshold is reached
  35267. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  35268. key to toggle velocity-sensitive mode
  35269. */
  35270. void setVelocityModeParameters (const double sensitivity = 1.0,
  35271. const int threshold = 1,
  35272. const double offset = 0.0,
  35273. const bool userCanPressKeyToSwapMode = true) throw();
  35274. /** Returns the velocity sensitivity setting.
  35275. @see setVelocityModeParameters
  35276. */
  35277. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  35278. /** Returns the velocity threshold setting.
  35279. @see setVelocityModeParameters
  35280. */
  35281. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  35282. /** Returns the velocity offset setting.
  35283. @see setVelocityModeParameters
  35284. */
  35285. double getVelocityOffset() const throw() { return velocityModeOffset; }
  35286. /** Returns the velocity user key setting.
  35287. @see setVelocityModeParameters
  35288. */
  35289. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  35290. /** Sets up a skew factor to alter the way values are distributed.
  35291. You may want to use a range of values on the slider where more accuracy
  35292. is required towards one end of the range, so this will logarithmically
  35293. spread the values across the length of the slider.
  35294. If the factor is < 1.0, the lower end of the range will fill more of the
  35295. slider's length; if the factor is > 1.0, the upper end of the range
  35296. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  35297. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  35298. method instead.
  35299. @see getSkewFactor, setSkewFactorFromMidPoint
  35300. */
  35301. void setSkewFactor (const double factor) throw();
  35302. /** Sets up a skew factor to alter the way values are distributed.
  35303. This allows you to specify the slider value that should appear in the
  35304. centre of the slider's visible range.
  35305. @see setSkewFactor, getSkewFactor
  35306. */
  35307. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  35308. /** Returns the current skew factor.
  35309. See setSkewFactor for more info.
  35310. @see setSkewFactor, setSkewFactorFromMidPoint
  35311. */
  35312. double getSkewFactor() const throw() { return skewFactor; }
  35313. /** Used by setIncDecButtonsMode().
  35314. */
  35315. enum IncDecButtonMode
  35316. {
  35317. incDecButtonsNotDraggable,
  35318. incDecButtonsDraggable_AutoDirection,
  35319. incDecButtonsDraggable_Horizontal,
  35320. incDecButtonsDraggable_Vertical
  35321. };
  35322. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  35323. can be dragged on the buttons to drag the values.
  35324. By default this is turned off. When enabled, clicking on the buttons still works
  35325. them as normal, but by holding down the mouse on a button and dragging it a little
  35326. distance, it flips into a mode where the value can be dragged. The drag direction can
  35327. either be set explicitly to be vertical or horizontal, or can be set to
  35328. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  35329. are side-by-side or above each other.
  35330. */
  35331. void setIncDecButtonsMode (const IncDecButtonMode mode);
  35332. /** The position of the slider's text-entry box.
  35333. @see setTextBoxStyle
  35334. */
  35335. enum TextEntryBoxPosition
  35336. {
  35337. NoTextBox, /**< Doesn't display a text box. */
  35338. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  35339. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  35340. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  35341. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  35342. };
  35343. /** Changes the location and properties of the text-entry box.
  35344. @param newPosition where it should go (or NoTextBox to not have one at all)
  35345. @param isReadOnly if true, it's a read-only display
  35346. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  35347. room for the slider as well!
  35348. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  35349. room for the slider as well!
  35350. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  35351. */
  35352. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  35353. const bool isReadOnly,
  35354. const int textEntryBoxWidth,
  35355. const int textEntryBoxHeight);
  35356. /** Returns the status of the text-box.
  35357. @see setTextBoxStyle
  35358. */
  35359. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  35360. /** Returns the width used for the text-box.
  35361. @see setTextBoxStyle
  35362. */
  35363. int getTextBoxWidth() const throw() { return textBoxWidth; }
  35364. /** Returns the height used for the text-box.
  35365. @see setTextBoxStyle
  35366. */
  35367. int getTextBoxHeight() const throw() { return textBoxHeight; }
  35368. /** Makes the text-box editable.
  35369. By default this is true, and the user can enter values into the textbox,
  35370. but it can be turned off if that's not suitable.
  35371. @see setTextBoxStyle, getValueFromText, getTextFromValue
  35372. */
  35373. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  35374. /** Returns true if the text-box is read-only.
  35375. @see setTextBoxStyle
  35376. */
  35377. bool isTextBoxEditable() const throw() { return editableText; }
  35378. /** If the text-box is editable, this will give it the focus so that the user can
  35379. type directly into it.
  35380. This is basically the effect as the user clicking on it.
  35381. */
  35382. void showTextBox();
  35383. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  35384. focus away from it.
  35385. @param discardCurrentEditorContents if true, the slider's value will be left
  35386. unchanged; if false, the current contents of the
  35387. text editor will be used to set the slider position
  35388. before it is hidden.
  35389. */
  35390. void hideTextBox (const bool discardCurrentEditorContents);
  35391. /** Changes the slider's current value.
  35392. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  35393. that are registered, and will synchronously call the valueChanged() method in case subclasses
  35394. want to handle it.
  35395. @param newValue the new value to set - this will be restricted by the
  35396. minimum and maximum range, and will be snapped to the
  35397. nearest interval if one has been set
  35398. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  35399. any SliderListeners or the valueChanged() method
  35400. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  35401. synchronously; if false, it will be asynchronous
  35402. */
  35403. void setValue (double newValue,
  35404. const bool sendUpdateMessage = true,
  35405. const bool sendMessageSynchronously = false);
  35406. /** Returns the slider's current value. */
  35407. double getValue() const throw();
  35408. /** Sets the limits that the slider's value can take.
  35409. @param newMinimum the lowest value allowed
  35410. @param newMaximum the highest value allowed
  35411. @param newInterval the steps in which the value is allowed to increase - if this
  35412. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  35413. */
  35414. void setRange (const double newMinimum,
  35415. const double newMaximum,
  35416. const double newInterval = 0);
  35417. /** Returns the current maximum value.
  35418. @see setRange
  35419. */
  35420. double getMaximum() const throw() { return maximum; }
  35421. /** Returns the current minimum value.
  35422. @see setRange
  35423. */
  35424. double getMinimum() const throw() { return minimum; }
  35425. /** Returns the current step-size for values.
  35426. @see setRange
  35427. */
  35428. double getInterval() const throw() { return interval; }
  35429. /** For a slider with two or three thumbs, this returns the lower of its values.
  35430. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  35431. A slider with three values also uses the normal getValue() and setValue() methods to
  35432. control the middle value.
  35433. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  35434. */
  35435. double getMinValue() const throw();
  35436. /** For a slider with two or three thumbs, this sets the lower of its values.
  35437. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  35438. that are registered, and will synchronously call the valueChanged() method in case subclasses
  35439. want to handle it.
  35440. @param newValue the new value to set - this will be restricted by the
  35441. minimum and maximum range, and will be snapped to the nearest
  35442. interval if one has been set.
  35443. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  35444. any SliderListeners or the valueChanged() method
  35445. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  35446. synchronously; if false, it will be asynchronous
  35447. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  35448. max value (in a two-value slider) or the mid value (in a three-value
  35449. slider). If false, then if this value goes beyond those values,
  35450. it will push them along with it.
  35451. @see getMinValue, setMaxValue, setValue
  35452. */
  35453. void setMinValue (double newValue,
  35454. const bool sendUpdateMessage = true,
  35455. const bool sendMessageSynchronously = false,
  35456. const bool allowNudgingOfOtherValues = false);
  35457. /** For a slider with two or three thumbs, this returns the higher of its values.
  35458. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  35459. A slider with three values also uses the normal getValue() and setValue() methods to
  35460. control the middle value.
  35461. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  35462. */
  35463. double getMaxValue() const throw();
  35464. /** For a slider with two or three thumbs, this sets the lower of its values.
  35465. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  35466. that are registered, and will synchronously call the valueChanged() method in case subclasses
  35467. want to handle it.
  35468. @param newValue the new value to set - this will be restricted by the
  35469. minimum and maximum range, and will be snapped to the nearest
  35470. interval if one has been set.
  35471. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  35472. any SliderListeners or the valueChanged() method
  35473. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  35474. synchronously; if false, it will be asynchronous
  35475. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  35476. min value (in a two-value slider) or the mid value (in a three-value
  35477. slider). If false, then if this value goes beyond those values,
  35478. it will push them along with it.
  35479. @see getMaxValue, setMinValue, setValue
  35480. */
  35481. void setMaxValue (double newValue,
  35482. const bool sendUpdateMessage = true,
  35483. const bool sendMessageSynchronously = false,
  35484. const bool allowNudgingOfOtherValues = false);
  35485. /** Adds a listener to be called when this slider's value changes. */
  35486. void addListener (SliderListener* const listener) throw();
  35487. /** Removes a previously-registered listener. */
  35488. void removeListener (SliderListener* const listener) throw();
  35489. /** This lets you choose whether double-clicking moves the slider to a given position.
  35490. By default this is turned off, but it's handy if you want a double-click to act
  35491. as a quick way of resetting a slider. Just pass in the value you want it to
  35492. go to when double-clicked.
  35493. @see getDoubleClickReturnValue
  35494. */
  35495. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  35496. const double valueToSetOnDoubleClick) throw();
  35497. /** Returns the values last set by setDoubleClickReturnValue() method.
  35498. Sets isEnabled to true if double-click is enabled, and returns the value
  35499. that was set.
  35500. @see setDoubleClickReturnValue
  35501. */
  35502. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  35503. /** Tells the slider whether to keep sending change messages while the user
  35504. is dragging the slider.
  35505. If set to true, a change message will only be sent when the user has
  35506. dragged the slider and let go. If set to false (the default), then messages
  35507. will be continuously sent as they drag it while the mouse button is still
  35508. held down.
  35509. */
  35510. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  35511. /** This lets you change whether the slider thumb jumps to the mouse position
  35512. when you click.
  35513. By default, this is true. If it's false, then the slider moves with relative
  35514. motion when you drag it.
  35515. This only applies to linear bars, and won't affect two- or three- value
  35516. sliders.
  35517. */
  35518. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  35519. /** If enabled, this gives the slider a pop-up bubble which appears while the
  35520. slider is being dragged.
  35521. This can be handy if your slider doesn't have a text-box, so that users can
  35522. see the value just when they're changing it.
  35523. If you pass a component as the parentComponentToUse parameter, the pop-up
  35524. bubble will be added as a child of that component when it's needed. If you
  35525. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  35526. transparent window, so if you're using an OS that can't do transparent windows
  35527. you'll have to add it to a parent component instead).
  35528. */
  35529. void setPopupDisplayEnabled (const bool isEnabled,
  35530. Component* const parentComponentToUse) throw();
  35531. /** If this is set to true, then right-clicking on the slider will pop-up
  35532. a menu to let the user change the way it works.
  35533. By default this is turned off, but when turned on, the menu will include
  35534. things like velocity sensitivity, and for rotary sliders, whether they
  35535. use a linear or rotary mouse-drag to move them.
  35536. */
  35537. void setPopupMenuEnabled (const bool menuEnabled) throw();
  35538. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  35539. By default it's enabled.
  35540. */
  35541. void setScrollWheelEnabled (const bool enabled) throw();
  35542. /** Returns a number to indicate which thumb is currently being dragged by the
  35543. mouse.
  35544. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  35545. the maximum-value thumb, or -1 if none is currently down.
  35546. */
  35547. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  35548. /** Callback to indicate that the user is about to start dragging the slider.
  35549. @see SliderListener::sliderDragStarted
  35550. */
  35551. virtual void startedDragging();
  35552. /** Callback to indicate that the user has just stopped dragging the slider.
  35553. @see SliderListener::sliderDragEnded
  35554. */
  35555. virtual void stoppedDragging();
  35556. /** Callback to indicate that the user has just moved the slider.
  35557. @see SliderListener::sliderValueChanged
  35558. */
  35559. virtual void valueChanged();
  35560. /** Callback to indicate that the user has just moved the slider.
  35561. Note - the valueChanged() method has changed its format and now no longer has
  35562. any parameters. Update your code to use the new version.
  35563. This version has been left here with an int as its return value to cause
  35564. a syntax error if you've got existing code that uses the old version.
  35565. */
  35566. virtual int valueChanged (double) { jassertfalse; return 0; }
  35567. /** Subclasses can override this to convert a text string to a value.
  35568. When the user enters something into the text-entry box, this method is
  35569. called to convert it to a value.
  35570. The default routine just tries to convert it to a double.
  35571. @see getTextFromValue
  35572. */
  35573. virtual double getValueFromText (const String& text);
  35574. /** Turns the slider's current value into a text string.
  35575. Subclasses can override this to customise the formatting of the text-entry box.
  35576. The default implementation just turns the value into a string, using
  35577. a number of decimal places based on the range interval. If a suffix string
  35578. has been set using setTextValueSuffix(), this will be appended to the text.
  35579. @see getValueFromText
  35580. */
  35581. virtual const String getTextFromValue (double value);
  35582. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  35583. a string.
  35584. This is used by the default implementation of getTextFromValue(), and is just
  35585. appended to the numeric value. For more advanced formatting, you can override
  35586. getTextFromValue() and do something else.
  35587. */
  35588. void setTextValueSuffix (const String& suffix);
  35589. /** Allows a user-defined mapping of distance along the slider to its value.
  35590. The default implementation for this performs the skewing operation that
  35591. can be set up in the setSkewFactor() method. Override it if you need
  35592. some kind of custom mapping instead, but make sure you also implement the
  35593. inverse function in valueToProportionOfLength().
  35594. @param proportion a value 0 to 1.0, indicating a distance along the slider
  35595. @returns the slider value that is represented by this position
  35596. @see valueToProportionOfLength
  35597. */
  35598. virtual double proportionOfLengthToValue (double proportion);
  35599. /** Allows a user-defined mapping of value to the position of the slider along its length.
  35600. The default implementation for this performs the skewing operation that
  35601. can be set up in the setSkewFactor() method. Override it if you need
  35602. some kind of custom mapping instead, but make sure you also implement the
  35603. inverse function in proportionOfLengthToValue().
  35604. @param value a valid slider value, between the range of values specified in
  35605. setRange()
  35606. @returns a value 0 to 1.0 indicating the distance along the slider that
  35607. represents this value
  35608. @see proportionOfLengthToValue
  35609. */
  35610. virtual double valueToProportionOfLength (double value);
  35611. /** Returns the X or Y coordinate of a value along the slider's length.
  35612. If the slider is horizontal, this will be the X coordinate of the given
  35613. value, relative to the left of the slider. If it's vertical, then this will
  35614. be the Y coordinate, relative to the top of the slider.
  35615. If the slider is rotary, this will throw an assertion and return 0. If the
  35616. value is out-of-range, it will be constrained to the length of the slider.
  35617. */
  35618. float getPositionOfValue (const double value);
  35619. /** This can be overridden to allow the slider to snap to user-definable values.
  35620. If overridden, it will be called when the user tries to move the slider to
  35621. a given position, and allows a subclass to sanity-check this value, possibly
  35622. returning a different value to use instead.
  35623. @param attemptedValue the value the user is trying to enter
  35624. @param userIsDragging true if the user is dragging with the mouse; false if
  35625. they are entering the value using the text box
  35626. @returns the value to use instead
  35627. */
  35628. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  35629. /** This can be called to force the text box to update its contents.
  35630. (Not normally needed, as this is done automatically).
  35631. */
  35632. void updateText();
  35633. /** True if the slider moves horizontally. */
  35634. bool isHorizontal() const throw();
  35635. /** True if the slider moves vertically. */
  35636. bool isVertical() const throw();
  35637. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  35638. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35639. methods.
  35640. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35641. */
  35642. enum ColourIds
  35643. {
  35644. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  35645. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  35646. and feel class how this is used. */
  35647. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  35648. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  35649. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  35650. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  35651. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  35652. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  35653. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  35654. };
  35655. juce_UseDebuggingNewOperator
  35656. protected:
  35657. /** @internal */
  35658. void labelTextChanged (Label*);
  35659. /** @internal */
  35660. void paint (Graphics& g);
  35661. /** @internal */
  35662. void resized();
  35663. /** @internal */
  35664. void mouseDown (const MouseEvent& e);
  35665. /** @internal */
  35666. void mouseUp (const MouseEvent& e);
  35667. /** @internal */
  35668. void mouseDrag (const MouseEvent& e);
  35669. /** @internal */
  35670. void mouseDoubleClick (const MouseEvent& e);
  35671. /** @internal */
  35672. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35673. /** @internal */
  35674. void modifierKeysChanged (const ModifierKeys& modifiers);
  35675. /** @internal */
  35676. void buttonClicked (Button* button);
  35677. /** @internal */
  35678. void lookAndFeelChanged();
  35679. /** @internal */
  35680. void enablementChanged();
  35681. /** @internal */
  35682. void focusOfChildComponentChanged (FocusChangeType cause);
  35683. /** @internal */
  35684. void handleAsyncUpdate();
  35685. /** @internal */
  35686. void colourChanged();
  35687. private:
  35688. SortedSet <void*> listeners;
  35689. double currentValue, valueMin, valueMax;
  35690. double minimum, maximum, interval, doubleClickReturnValue;
  35691. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  35692. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  35693. int velocityModeThreshold;
  35694. float rotaryStart, rotaryEnd;
  35695. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  35696. int mouseDragStartX, mouseDragStartY;
  35697. int sliderRegionStart, sliderRegionSize;
  35698. int sliderBeingDragged;
  35699. int pixelsForFullDragExtent;
  35700. Rectangle sliderRect;
  35701. String textSuffix;
  35702. SliderStyle style;
  35703. TextEntryBoxPosition textBoxPos;
  35704. int textBoxWidth, textBoxHeight;
  35705. IncDecButtonMode incDecButtonMode;
  35706. bool editableText : 1, doubleClickToValue : 1;
  35707. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  35708. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  35709. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  35710. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  35711. Font font;
  35712. Label* valueBox;
  35713. Button* incButton;
  35714. Button* decButton;
  35715. Component* popupDisplay;
  35716. Component* parentForPopupDisplay;
  35717. float getLinearSliderPos (const double value);
  35718. void restoreMouseIfHidden();
  35719. void sendDragStart();
  35720. void sendDragEnd();
  35721. double constrainedValue (double value) const throw();
  35722. void triggerChangeMessage (const bool synchronous);
  35723. bool incDecDragDirectionIsHorizontal() const throw();
  35724. Slider (const Slider&);
  35725. const Slider& operator= (const Slider&);
  35726. };
  35727. #endif // __JUCE_SLIDER_JUCEHEADER__
  35728. /********* End of inlined file: juce_Slider.h *********/
  35729. #endif
  35730. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  35731. #endif
  35732. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35733. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  35734. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35735. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35736. class TableHeaderComponent;
  35737. /**
  35738. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  35739. You can register one of these objects for table events using TableHeaderComponent::addListener()
  35740. and TableHeaderComponent::removeListener().
  35741. @see TableHeaderComponent
  35742. */
  35743. class JUCE_API TableHeaderListener
  35744. {
  35745. public:
  35746. TableHeaderListener() {}
  35747. /** Destructor. */
  35748. virtual ~TableHeaderListener() {}
  35749. /** This is called when some of the table's columns are added, removed, hidden,
  35750. or rearranged.
  35751. */
  35752. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  35753. /** This is called when one or more of the table's columns are resized.
  35754. */
  35755. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  35756. /** This is called when the column by which the table should be sorted is changed.
  35757. */
  35758. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  35759. /** This is called when the user begins or ends dragging one of the columns around.
  35760. When the user starts dragging a column, this is called with the ID of that
  35761. column. When they finish dragging, it is called again with 0 as the ID.
  35762. */
  35763. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  35764. int columnIdNowBeingDragged);
  35765. };
  35766. /**
  35767. A component that displays a strip of column headings for a table, and allows these
  35768. to be resized, dragged around, etc.
  35769. This is just the component that goes at the top of a table. You can use it
  35770. directly for custom components, or to create a simple table, use the
  35771. TableListBox class.
  35772. To use one of these, create it and use addColumn() to add all the columns that you need.
  35773. Each column must be given a unique ID number that's used to refer to it.
  35774. @see TableListBox, TableHeaderListener
  35775. */
  35776. class JUCE_API TableHeaderComponent : public Component,
  35777. private AsyncUpdater
  35778. {
  35779. public:
  35780. /** Creates an empty table header.
  35781. */
  35782. TableHeaderComponent();
  35783. /** Destructor. */
  35784. ~TableHeaderComponent();
  35785. /** A combination of these flags are passed into the addColumn() method to specify
  35786. the properties of a column.
  35787. */
  35788. enum ColumnPropertyFlags
  35789. {
  35790. 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. */
  35791. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  35792. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  35793. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  35794. 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. */
  35795. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  35796. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  35797. /** This set of default flags is used as the default parameter value in addColumn(). */
  35798. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  35799. /** A quick way of combining flags for a column that's not resizable. */
  35800. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  35801. /** A quick way of combining flags for a column that's not resizable or sortable. */
  35802. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  35803. /** A quick way of combining flags for a column that's not sortable. */
  35804. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  35805. };
  35806. /** Adds a column to the table.
  35807. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  35808. registered listeners.
  35809. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  35810. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  35811. a unique ID. This is used to identify the column later on, after the user may have
  35812. changed the order that they appear in
  35813. @param width the initial width of the column, in pixels
  35814. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  35815. if the 'resizable' flag is specified for this column
  35816. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  35817. if the 'resizable' flag is specified for this column
  35818. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  35819. properties of this column
  35820. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  35821. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  35822. all columns, not just the index amongst those that are currently visible
  35823. */
  35824. void addColumn (const String& columnName,
  35825. const int columnId,
  35826. const int width,
  35827. const int minimumWidth = 30,
  35828. const int maximumWidth = -1,
  35829. const int propertyFlags = defaultFlags,
  35830. const int insertIndex = -1);
  35831. /** Removes a column with the given ID.
  35832. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  35833. registered listeners.
  35834. */
  35835. void removeColumn (const int columnIdToRemove);
  35836. /** Deletes all columns from the table.
  35837. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  35838. registered listeners.
  35839. */
  35840. void removeAllColumns();
  35841. /** Returns the number of columns in the table.
  35842. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  35843. return the total number of columns, including hidden ones.
  35844. @see isColumnVisible
  35845. */
  35846. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  35847. /** Returns the name for a column.
  35848. @see setColumnName
  35849. */
  35850. const String getColumnName (const int columnId) const throw();
  35851. /** Changes the name of a column. */
  35852. void setColumnName (const int columnId, const String& newName);
  35853. /** Moves a column to a different index in the table.
  35854. @param columnId the column to move
  35855. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  35856. */
  35857. void moveColumn (const int columnId, int newVisibleIndex);
  35858. /** Returns the width of one of the columns.
  35859. */
  35860. int getColumnWidth (const int columnId) const throw();
  35861. /** Changes the width of a column.
  35862. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  35863. */
  35864. void setColumnWidth (const int columnId, const int newWidth);
  35865. /** Shows or hides a column.
  35866. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  35867. @see isColumnVisible
  35868. */
  35869. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  35870. /** Returns true if this column is currently visible.
  35871. @see setColumnVisible
  35872. */
  35873. bool isColumnVisible (const int columnId) const;
  35874. /** Changes the column which is the sort column.
  35875. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  35876. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  35877. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  35878. @see getSortColumnId, isSortedForwards, reSortTable
  35879. */
  35880. void setSortColumnId (const int columnId, const bool sortForwards);
  35881. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  35882. @see setSortColumnId, isSortedForwards
  35883. */
  35884. int getSortColumnId() const throw();
  35885. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  35886. @see setSortColumnId
  35887. */
  35888. bool isSortedForwards() const throw();
  35889. /** Triggers a re-sort of the table according to the current sort-column.
  35890. If you modifiy the table's contents, you can call this to signal that the table needs
  35891. to be re-sorted.
  35892. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  35893. tableSortOrderChanged() method of any listeners).
  35894. */
  35895. void reSortTable();
  35896. /** Returns the total width of all the visible columns in the table.
  35897. */
  35898. int getTotalWidth() const throw();
  35899. /** Returns the index of a given column.
  35900. If there's no such column ID, this will return -1.
  35901. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  35902. otherwise it'll return the index amongst all the columns, including any hidden ones.
  35903. */
  35904. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  35905. /** Returns the ID of the column at a given index.
  35906. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  35907. otherwise it'll count it amongst all the columns, including any hidden ones.
  35908. If the index is out-of-range, it'll return 0.
  35909. */
  35910. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  35911. /** Returns the rectangle containing of one of the columns.
  35912. The index is an index from 0 to the number of columns that are currently visible (hidden
  35913. ones are not counted). It returns a rectangle showing the position of the column relative
  35914. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  35915. */
  35916. const Rectangle getColumnPosition (const int index) const throw();
  35917. /** Finds the column ID at a given x-position in the component.
  35918. If there is a column at this point this returns its ID, or if not, it will return 0.
  35919. */
  35920. int getColumnIdAtX (const int xToFind) const throw();
  35921. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  35922. entire width of the component.
  35923. By default this is disabled. Turning it on also means that when resizing a column, those
  35924. on the right will be squashed to fit.
  35925. */
  35926. void setStretchToFitActive (const bool shouldStretchToFit);
  35927. /** Returns true if stretch-to-fit has been enabled.
  35928. @see setStretchToFitActive
  35929. */
  35930. bool isStretchToFitActive() const throw();
  35931. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  35932. specified width, keeping their relative proportions the same.
  35933. If the minimum widths of the columns are too wide to fit into this space, it may
  35934. actually end up wider.
  35935. */
  35936. void resizeAllColumnsToFit (int targetTotalWidth);
  35937. /** Enables or disables the pop-up menu.
  35938. The default menu allows the user to show or hide columns. You can add custom
  35939. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  35940. By default the menu is enabled.
  35941. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  35942. */
  35943. void setPopupMenuActive (const bool hasMenu);
  35944. /** Returns true if the pop-up menu is enabled.
  35945. @see setPopupMenuActive
  35946. */
  35947. bool isPopupMenuActive() const throw();
  35948. /** Returns a string that encapsulates the table's current layout.
  35949. This can be restored later using restoreFromString(). It saves the order of
  35950. the columns, the currently-sorted column, and the widths.
  35951. @see restoreFromString
  35952. */
  35953. const String toString() const;
  35954. /** Restores the state of the table, based on a string previously created with
  35955. toString().
  35956. @see toString
  35957. */
  35958. void restoreFromString (const String& storedVersion);
  35959. /** Adds a listener to be informed about things that happen to the header. */
  35960. void addListener (TableHeaderListener* const newListener) throw();
  35961. /** Removes a previously-registered listener. */
  35962. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  35963. /** This can be overridden to handle a mouse-click on one of the column headers.
  35964. The default implementation will use this click to call getSortColumnId() and
  35965. change the sort order.
  35966. */
  35967. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  35968. /** This can be overridden to add custom items to the pop-up menu.
  35969. If you override this, you should call the superclass's method to add its
  35970. column show/hide items, if you want them on the menu as well.
  35971. Then to handle the result, override reactToMenuItem().
  35972. @see reactToMenuItem
  35973. */
  35974. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  35975. /** Override this to handle any custom items that you have added to the
  35976. pop-up menu with an addMenuItems() override.
  35977. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35978. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35979. handle the items that it had added.
  35980. @see addMenuItems
  35981. */
  35982. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  35983. /** @internal */
  35984. void paint (Graphics& g);
  35985. /** @internal */
  35986. void resized();
  35987. /** @internal */
  35988. void mouseMove (const MouseEvent&);
  35989. /** @internal */
  35990. void mouseEnter (const MouseEvent&);
  35991. /** @internal */
  35992. void mouseExit (const MouseEvent&);
  35993. /** @internal */
  35994. void mouseDown (const MouseEvent&);
  35995. /** @internal */
  35996. void mouseDrag (const MouseEvent&);
  35997. /** @internal */
  35998. void mouseUp (const MouseEvent&);
  35999. /** @internal */
  36000. const MouseCursor getMouseCursor();
  36001. /** Can be overridden for more control over the pop-up menu behaviour. */
  36002. virtual void showColumnChooserMenu (const int columnIdClicked);
  36003. juce_UseDebuggingNewOperator
  36004. private:
  36005. struct ColumnInfo
  36006. {
  36007. String name;
  36008. int id, propertyFlags, width, minimumWidth, maximumWidth;
  36009. double lastDeliberateWidth;
  36010. bool isVisible() const throw();
  36011. };
  36012. OwnedArray <ColumnInfo> columns;
  36013. Array <TableHeaderListener*> listeners;
  36014. Component* dragOverlayComp;
  36015. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  36016. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  36017. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  36018. ColumnInfo* getInfoForId (const int columnId) const throw();
  36019. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  36020. void sendColumnsChanged();
  36021. void handleAsyncUpdate();
  36022. void beginDrag (const MouseEvent&);
  36023. void endDrag (const int finalIndex);
  36024. int getResizeDraggerAt (const int mouseX) const throw();
  36025. void updateColumnUnderMouse (int x, int y);
  36026. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  36027. TableHeaderComponent (const TableHeaderComponent&);
  36028. const TableHeaderComponent operator= (const TableHeaderComponent&);
  36029. };
  36030. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  36031. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  36032. #endif
  36033. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  36034. /********* Start of inlined file: juce_TableListBox.h *********/
  36035. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  36036. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  36037. /**
  36038. One of these is used by a TableListBox as the data model for the table's contents.
  36039. The virtual methods that you override in this class take care of drawing the
  36040. table cells, and reacting to events.
  36041. @see TableListBox
  36042. */
  36043. class JUCE_API TableListBoxModel
  36044. {
  36045. public:
  36046. TableListBoxModel() {}
  36047. /** Destructor. */
  36048. virtual ~TableListBoxModel() {}
  36049. /** This must return the number of rows currently in the table.
  36050. If the number of rows changes, you must call TableListBox::updateContent() to
  36051. cause it to refresh the list.
  36052. */
  36053. virtual int getNumRows() = 0;
  36054. /** This must draw the background behind one of the rows in the table.
  36055. The graphics context has its origin at the row's top-left, and your method
  36056. should fill the area specified by the width and height parameters.
  36057. */
  36058. virtual void paintRowBackground (Graphics& g,
  36059. int rowNumber,
  36060. int width, int height,
  36061. bool rowIsSelected) = 0;
  36062. /** This must draw one of the cells.
  36063. The graphics context's origin will already be set to the top-left of the cell,
  36064. whose size is specified by (width, height).
  36065. */
  36066. virtual void paintCell (Graphics& g,
  36067. int rowNumber,
  36068. int columnId,
  36069. int width, int height,
  36070. bool rowIsSelected) = 0;
  36071. /** This is used to create or update a custom component to go in a cell.
  36072. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  36073. and handle mouse clicks with cellClicked().
  36074. This method will be called whenever a custom component might need to be updated - e.g.
  36075. when the table is changed, or TableListBox::updateContent() is called.
  36076. If you don't need a custom component for the specified cell, then return 0.
  36077. If you do want a custom component, and the existingComponentToUpdate is null, then
  36078. this method must create a new component suitable for the cell, and return it.
  36079. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  36080. by this method. In this case, the method must either update it to make sure it's correctly representing
  36081. the given cell (which may be different from the one that the component was created for), or it can
  36082. delete this component and return a new one.
  36083. */
  36084. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  36085. Component* existingComponentToUpdate);
  36086. /** This callback is made when the user clicks on one of the cells in the table.
  36087. The mouse event's coordinates will be relative to the entire table row.
  36088. @see cellDoubleClicked, backgroundClicked
  36089. */
  36090. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  36091. /** This callback is made when the user clicks on one of the cells in the table.
  36092. The mouse event's coordinates will be relative to the entire table row.
  36093. @see cellClicked, backgroundClicked
  36094. */
  36095. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  36096. /** This can be overridden to react to the user double-clicking on a part of the list where
  36097. there are no rows.
  36098. @see cellClicked
  36099. */
  36100. virtual void backgroundClicked();
  36101. /** This callback is made when the table's sort order is changed.
  36102. This could be because the user has clicked a column header, or because the
  36103. TableHeaderComponent::setSortColumnId() method was called.
  36104. If you implement this, your method should re-sort the table using the given
  36105. column as the key.
  36106. */
  36107. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  36108. /** Returns the best width for one of the columns.
  36109. If you implement this method, you should measure the width of all the items
  36110. in this column, and return the best size.
  36111. Returning 0 means that the column shouldn't be changed.
  36112. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  36113. */
  36114. virtual int getColumnAutoSizeWidth (int columnId);
  36115. /** Returns a tooltip for a particular cell in the table.
  36116. */
  36117. virtual const String getCellTooltip (int rowNumber, int columnId);
  36118. /** Override this to be informed when rows are selected or deselected.
  36119. @see ListBox::selectedRowsChanged()
  36120. */
  36121. virtual void selectedRowsChanged (int lastRowSelected);
  36122. /** Override this to be informed when the delete key is pressed.
  36123. @see ListBox::deleteKeyPressed()
  36124. */
  36125. virtual void deleteKeyPressed (int lastRowSelected);
  36126. /** Override this to be informed when the return key is pressed.
  36127. @see ListBox::returnKeyPressed()
  36128. */
  36129. virtual void returnKeyPressed (int lastRowSelected);
  36130. /** Override this to be informed when the list is scrolled.
  36131. This might be caused by the user moving the scrollbar, or by programmatic changes
  36132. to the list position.
  36133. */
  36134. virtual void listWasScrolled();
  36135. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  36136. If this returns a non-empty name then when the user drags a row, the table will try to
  36137. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  36138. drag-and-drop operation, using this string as the source description, and the listbox
  36139. itself as the source component.
  36140. @see DragAndDropContainer::startDragging
  36141. */
  36142. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  36143. };
  36144. /**
  36145. A table of cells, using a TableHeaderComponent as its header.
  36146. This component makes it easy to create a table by providing a TableListBoxModel as
  36147. the data source.
  36148. @see TableListBoxModel, TableHeaderComponent
  36149. */
  36150. class JUCE_API TableListBox : public ListBox,
  36151. private ListBoxModel,
  36152. private TableHeaderListener
  36153. {
  36154. public:
  36155. /** Creates a TableListBox.
  36156. The model pointer passed-in can be null, in which case you can set it later
  36157. with setModel().
  36158. */
  36159. TableListBox (const String& componentName,
  36160. TableListBoxModel* const model);
  36161. /** Destructor. */
  36162. ~TableListBox();
  36163. /** Changes the TableListBoxModel that is being used for this table.
  36164. */
  36165. void setModel (TableListBoxModel* const newModel);
  36166. /** Returns the model currently in use. */
  36167. TableListBoxModel* getModel() const throw() { return model; }
  36168. /** Returns the header component being used in this table. */
  36169. TableHeaderComponent* getHeader() const throw() { return header; }
  36170. /** Changes the height of the table header component.
  36171. @see getHeaderHeight
  36172. */
  36173. void setHeaderHeight (const int newHeight);
  36174. /** Returns the height of the table header.
  36175. @see setHeaderHeight
  36176. */
  36177. int getHeaderHeight() const throw();
  36178. /** Resizes a column to fit its contents.
  36179. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  36180. and applies that to the column.
  36181. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  36182. */
  36183. void autoSizeColumn (const int columnId);
  36184. /** Calls autoSizeColumn() for all columns in the table. */
  36185. void autoSizeAllColumns();
  36186. /** Enables or disables the auto size options on the popup menu.
  36187. By default, these are enabled.
  36188. */
  36189. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  36190. /** True if the auto-size options should be shown on the menu.
  36191. @see setAutoSizeMenuOptionsShown
  36192. */
  36193. bool isAutoSizeMenuOptionShown() const throw();
  36194. /** Returns the position of one of the cells in the table.
  36195. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  36196. the table component's top-left. The row number isn't checked to see if it's
  36197. in-range, but the column ID must exist or this will return an empty rectangle.
  36198. If relativeToComponentTopLeft is false, the co-ords are relative to the
  36199. top-left of the table's top-left cell.
  36200. */
  36201. const Rectangle getCellPosition (const int columnId,
  36202. const int rowNumber,
  36203. const bool relativeToComponentTopLeft) const;
  36204. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  36205. @see ListBox::scrollToEnsureRowIsOnscreen
  36206. */
  36207. void scrollToEnsureColumnIsOnscreen (const int columnId);
  36208. /** @internal */
  36209. int getNumRows();
  36210. /** @internal */
  36211. void paintListBoxItem (int, Graphics&, int, int, bool);
  36212. /** @internal */
  36213. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  36214. /** @internal */
  36215. void selectedRowsChanged (int lastRowSelected);
  36216. /** @internal */
  36217. void deleteKeyPressed (int currentSelectedRow);
  36218. /** @internal */
  36219. void returnKeyPressed (int currentSelectedRow);
  36220. /** @internal */
  36221. void backgroundClicked();
  36222. /** @internal */
  36223. void listWasScrolled();
  36224. /** @internal */
  36225. void tableColumnsChanged (TableHeaderComponent*);
  36226. /** @internal */
  36227. void tableColumnsResized (TableHeaderComponent*);
  36228. /** @internal */
  36229. void tableSortOrderChanged (TableHeaderComponent*);
  36230. /** @internal */
  36231. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  36232. /** @internal */
  36233. void resized();
  36234. juce_UseDebuggingNewOperator
  36235. private:
  36236. TableHeaderComponent* header;
  36237. TableListBoxModel* model;
  36238. int columnIdNowBeingDragged;
  36239. bool autoSizeOptionsShown;
  36240. void updateColumnComponents() const;
  36241. TableListBox (const TableListBox&);
  36242. const TableListBox& operator= (const TableListBox&);
  36243. };
  36244. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  36245. /********* End of inlined file: juce_TableListBox.h *********/
  36246. #endif
  36247. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  36248. #endif
  36249. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  36250. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  36251. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  36252. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  36253. /**
  36254. A factory object which can create ToolbarItemComponent objects.
  36255. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  36256. that it can create.
  36257. Each type of item is identified by a unique ID, and multiple instances of an
  36258. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  36259. bars).
  36260. @see Toolbar, ToolbarItemComponent, ToolbarButton
  36261. */
  36262. class JUCE_API ToolbarItemFactory
  36263. {
  36264. public:
  36265. ToolbarItemFactory();
  36266. /** Destructor. */
  36267. virtual ~ToolbarItemFactory();
  36268. /** A set of reserved item ID values, used for the built-in item types.
  36269. */
  36270. enum SpecialItemIds
  36271. {
  36272. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  36273. can be placed between sets of items to break them into groups. */
  36274. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  36275. items.*/
  36276. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  36277. either side of it, filling any available space. */
  36278. };
  36279. /** Must return a list of the IDs for all the item types that this factory can create.
  36280. The ids should be added to the array that is passed-in.
  36281. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  36282. and the predefined IDs in the SpecialItemIds enum.
  36283. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  36284. to this list if you want your toolbar to be able to contain those items.
  36285. The list returned here is used by the ToolbarItemPalette class to obtain its list
  36286. of available items, and their order on the palette will reflect the order in which
  36287. they appear on this list.
  36288. @see ToolbarItemPalette
  36289. */
  36290. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  36291. /** Must return the set of items that should be added to a toolbar as its default set.
  36292. This method is used by Toolbar::addDefaultItems() to determine which items to
  36293. create.
  36294. The items that your method adds to the array that is passed-in will be added to the
  36295. toolbar in the same order. Items can appear in the list more than once.
  36296. */
  36297. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  36298. /** Must create an instance of one of the items that the factory lists in its
  36299. getAllToolbarItemIds() method.
  36300. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  36301. method, except for the built-in item types from the SpecialItemIds enum, which
  36302. are created internally by the toolbar code.
  36303. Try not to keep a pointer to the object that is returned, as it will be deleted
  36304. automatically by the toolbar, and remember that multiple instances of the same
  36305. item type are likely to exist at the same time.
  36306. */
  36307. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  36308. };
  36309. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  36310. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  36311. #endif
  36312. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  36313. #endif
  36314. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  36315. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  36316. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  36317. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  36318. /**
  36319. A component containing a list of toolbar items, which the user can drag onto
  36320. a toolbar to add them.
  36321. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  36322. which automatically shows one of these in a dialog box with lots of extra controls.
  36323. @see Toolbar
  36324. */
  36325. class JUCE_API ToolbarItemPalette : public Component,
  36326. public DragAndDropContainer
  36327. {
  36328. public:
  36329. /** Creates a palette of items for a given factory, with the aim of adding them
  36330. to the specified toolbar.
  36331. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  36332. set of items that are shown in this palette.
  36333. The toolbar and factory must not be deleted while this object exists.
  36334. */
  36335. ToolbarItemPalette (ToolbarItemFactory& factory,
  36336. Toolbar* const toolbar);
  36337. /** Destructor. */
  36338. ~ToolbarItemPalette();
  36339. /** @internal */
  36340. void resized();
  36341. juce_UseDebuggingNewOperator
  36342. private:
  36343. ToolbarItemFactory& factory;
  36344. Toolbar* toolbar;
  36345. Viewport* viewport;
  36346. friend class Toolbar;
  36347. void replaceComponent (ToolbarItemComponent* const comp);
  36348. ToolbarItemPalette (const ToolbarItemPalette&);
  36349. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  36350. };
  36351. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  36352. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  36353. #endif
  36354. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  36355. #endif
  36356. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  36357. #endif
  36358. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  36359. #endif
  36360. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  36361. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  36362. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  36363. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  36364. /**
  36365. A PropertyComponent that contains an on/off toggle button.
  36366. This type of property component can be used if you have a boolean value to
  36367. toggle on/off.
  36368. @see PropertyComponent
  36369. */
  36370. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  36371. private ButtonListener
  36372. {
  36373. public:
  36374. /** Creates a button component.
  36375. @param propertyName the property name to be passed to the PropertyComponent
  36376. @param buttonTextWhenTrue the text shown in the button when the value is true
  36377. @param buttonTextWhenFalse the text shown in the button when the value is false
  36378. */
  36379. BooleanPropertyComponent (const String& propertyName,
  36380. const String& buttonTextWhenTrue,
  36381. const String& buttonTextWhenFalse);
  36382. /** Destructor. */
  36383. ~BooleanPropertyComponent();
  36384. /** Called to change the state of the boolean value. */
  36385. virtual void setState (const bool newState) = 0;
  36386. /** Must return the current value of the property. */
  36387. virtual bool getState() const = 0;
  36388. /** @internal */
  36389. void paint (Graphics& g);
  36390. /** @internal */
  36391. void refresh();
  36392. /** @internal */
  36393. void buttonClicked (Button*);
  36394. juce_UseDebuggingNewOperator
  36395. private:
  36396. ToggleButton* button;
  36397. String onText, offText;
  36398. };
  36399. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  36400. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  36401. #endif
  36402. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  36403. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  36404. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  36405. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  36406. /**
  36407. A PropertyComponent that contains a button.
  36408. This type of property component can be used if you need a button to trigger some
  36409. kind of action.
  36410. @see PropertyComponent
  36411. */
  36412. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  36413. private ButtonListener
  36414. {
  36415. public:
  36416. /** Creates a button component.
  36417. @param propertyName the property name to be passed to the PropertyComponent
  36418. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  36419. */
  36420. ButtonPropertyComponent (const String& propertyName,
  36421. const bool triggerOnMouseDown);
  36422. /** Destructor. */
  36423. ~ButtonPropertyComponent();
  36424. /** Called when the user clicks the button.
  36425. */
  36426. virtual void buttonClicked() = 0;
  36427. /** Returns the string that should be displayed in the button.
  36428. If you need to change this string, call refresh() to update the component.
  36429. */
  36430. virtual const String getButtonText() const = 0;
  36431. /** @internal */
  36432. void refresh();
  36433. /** @internal */
  36434. void buttonClicked (Button*);
  36435. juce_UseDebuggingNewOperator
  36436. private:
  36437. TextButton* button;
  36438. };
  36439. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  36440. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  36441. #endif
  36442. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  36443. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  36444. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  36445. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  36446. /**
  36447. A PropertyComponent that shows its value as a combo box.
  36448. This type of property component contains a list of options and has a
  36449. combo box to choose one.
  36450. Your subclass's constructor must add some strings to the choices StringArray
  36451. and these are shown in the list.
  36452. The getIndex() method will be called to find out which option is the currently
  36453. selected one. If you call refresh() it will call getIndex() to check whether
  36454. the value has changed, and will update the combo box if needed.
  36455. If the user selects a different item from the list, setIndex() will be
  36456. called to let your class process this.
  36457. @see PropertyComponent, PropertyPanel
  36458. */
  36459. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  36460. private ComboBoxListener
  36461. {
  36462. public:
  36463. /** Creates the component.
  36464. Your subclass's constructor must add a list of options to the choices
  36465. member variable.
  36466. */
  36467. ChoicePropertyComponent (const String& propertyName);
  36468. /** Destructor. */
  36469. ~ChoicePropertyComponent();
  36470. /** Called when the user selects an item from the combo box.
  36471. Your subclass must use this callback to update the value that this component
  36472. represents. The index is the index of the chosen item in the choices
  36473. StringArray.
  36474. */
  36475. virtual void setIndex (const int newIndex) = 0;
  36476. /** Returns the index of the item that should currently be shown.
  36477. This is the index of the item in the choices StringArray that will be
  36478. shown.
  36479. */
  36480. virtual int getIndex() const = 0;
  36481. /** Returns the list of options. */
  36482. const StringArray& getChoices() const throw();
  36483. /** @internal */
  36484. void refresh();
  36485. /** @internal */
  36486. void comboBoxChanged (ComboBox*);
  36487. juce_UseDebuggingNewOperator
  36488. protected:
  36489. /** The list of options that will be shown in the combo box.
  36490. Your subclass must populate this array in its constructor. If any empty
  36491. strings are added, these will be replaced with horizontal separators (see
  36492. ComboBox::addSeparator() for more info).
  36493. */
  36494. StringArray choices;
  36495. private:
  36496. ComboBox* comboBox;
  36497. };
  36498. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  36499. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  36500. #endif
  36501. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  36502. #endif
  36503. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36504. #endif
  36505. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36506. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  36507. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36508. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36509. /**
  36510. A PropertyComponent that shows its value as a slider.
  36511. @see PropertyComponent, Slider
  36512. */
  36513. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  36514. private SliderListener
  36515. {
  36516. public:
  36517. /** Creates the property component.
  36518. The ranges, interval and skew factor are passed to the Slider component.
  36519. If you need to customise the slider in other ways, your constructor can
  36520. access the slider member variable and change it directly.
  36521. */
  36522. SliderPropertyComponent (const String& propertyName,
  36523. const double rangeMin,
  36524. const double rangeMax,
  36525. const double interval,
  36526. const double skewFactor = 1.0);
  36527. /** Destructor. */
  36528. ~SliderPropertyComponent();
  36529. /** Called when the user moves the slider to change its value.
  36530. Your subclass must use this method to update whatever item this property
  36531. represents.
  36532. */
  36533. virtual void setValue (const double newValue) = 0;
  36534. /** Returns the value that the slider should show. */
  36535. virtual const double getValue() const = 0;
  36536. /** @internal */
  36537. void refresh();
  36538. /** @internal */
  36539. void changeListenerCallback (void*);
  36540. /** @internal */
  36541. void sliderValueChanged (Slider*);
  36542. juce_UseDebuggingNewOperator
  36543. protected:
  36544. /** The slider component being used in this component.
  36545. Your subclass has access to this in case it needs to customise it in some way.
  36546. */
  36547. Slider* slider;
  36548. };
  36549. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  36550. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  36551. #endif
  36552. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36553. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  36554. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36555. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36556. /**
  36557. A PropertyComponent that shows its value as editable text.
  36558. @see PropertyComponent
  36559. */
  36560. class JUCE_API TextPropertyComponent : public PropertyComponent
  36561. {
  36562. public:
  36563. /** Creates a text property component.
  36564. The maxNumChars is used to set the length of string allowable, and isMultiLine
  36565. sets whether the text editor allows carriage returns.
  36566. @see TextEditor
  36567. */
  36568. TextPropertyComponent (const String& propertyName,
  36569. const int maxNumChars,
  36570. const bool isMultiLine);
  36571. /** Destructor. */
  36572. ~TextPropertyComponent();
  36573. /** Called when the user edits the text.
  36574. Your subclass must use this callback to change the value of whatever item
  36575. this property component represents.
  36576. */
  36577. virtual void setText (const String& newText) = 0;
  36578. /** Returns the text that should be shown in the text editor.
  36579. */
  36580. virtual const String getText() const = 0;
  36581. /** @internal */
  36582. void refresh();
  36583. /** @internal */
  36584. void textWasEdited();
  36585. juce_UseDebuggingNewOperator
  36586. private:
  36587. Label* textEditor;
  36588. };
  36589. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  36590. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  36591. #endif
  36592. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  36593. #endif
  36594. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36595. #endif
  36596. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36597. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  36598. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36599. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36600. /** An object that watches for any movement of a component or any of its parent components.
  36601. This makes it easy to check when a component is moved relative to its top-level
  36602. peer window. The normal Component::moved() method is only called when a component
  36603. moves relative to its immediate parent, and sometimes you want to know if any of
  36604. components higher up the tree have moved (which of course will affect the overall
  36605. position of all their sub-components).
  36606. It also includes a callback that lets you know when the top-level peer is changed.
  36607. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  36608. because they need to keep their custom windows in the right place and respond to
  36609. changes in the peer.
  36610. */
  36611. class JUCE_API ComponentMovementWatcher : public ComponentListener
  36612. {
  36613. public:
  36614. /** Creates a ComponentMovementWatcher to watch a given target component. */
  36615. ComponentMovementWatcher (Component* const component);
  36616. /** Destructor. */
  36617. ~ComponentMovementWatcher();
  36618. /** This callback happens when the component that is being watched is moved
  36619. relative to its top-level peer window, or when it is resized.
  36620. */
  36621. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  36622. /** This callback happens when the component's top-level peer is changed.
  36623. */
  36624. virtual void componentPeerChanged() = 0;
  36625. juce_UseDebuggingNewOperator
  36626. /** @internal */
  36627. void componentParentHierarchyChanged (Component& component);
  36628. /** @internal */
  36629. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36630. private:
  36631. Component* const component;
  36632. ComponentPeer* lastPeer;
  36633. VoidArray registeredParentComps;
  36634. bool reentrant;
  36635. int lastX, lastY, lastWidth, lastHeight;
  36636. #ifdef JUCE_DEBUG
  36637. ComponentDeletionWatcher* deletionWatcher;
  36638. #endif
  36639. void unregister() throw();
  36640. void registerWithParentComps() throw();
  36641. ComponentMovementWatcher (const ComponentMovementWatcher&);
  36642. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  36643. };
  36644. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36645. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  36646. #endif
  36647. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36648. /********* Start of inlined file: juce_GroupComponent.h *********/
  36649. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36650. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36651. /**
  36652. A component that draws an outline around itself and has an optional title at
  36653. the top, for drawing an outline around a group of controls.
  36654. */
  36655. class JUCE_API GroupComponent : public Component
  36656. {
  36657. public:
  36658. /** Creates a GroupComponent.
  36659. @param componentName the name to give the component
  36660. @param labelText the text to show at the top of the outline
  36661. */
  36662. GroupComponent (const String& componentName,
  36663. const String& labelText);
  36664. /** Destructor. */
  36665. ~GroupComponent();
  36666. /** Changes the text that's shown at the top of the component. */
  36667. void setText (const String& newText) throw();
  36668. /** Returns the currently displayed text label. */
  36669. const String getText() const throw();
  36670. /** Sets the positioning of the text label.
  36671. (The default is Justification::left)
  36672. @see getTextLabelPosition
  36673. */
  36674. void setTextLabelPosition (const Justification& justification);
  36675. /** Returns the current text label position.
  36676. @see setTextLabelPosition
  36677. */
  36678. const Justification getTextLabelPosition() const throw() { return justification; }
  36679. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36680. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36681. methods.
  36682. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36683. */
  36684. enum ColourIds
  36685. {
  36686. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  36687. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  36688. };
  36689. /** @internal */
  36690. void paint (Graphics& g);
  36691. /** @internal */
  36692. void enablementChanged();
  36693. /** @internal */
  36694. void colourChanged();
  36695. private:
  36696. String text;
  36697. Justification justification;
  36698. GroupComponent (const GroupComponent&);
  36699. const GroupComponent& operator= (const GroupComponent&);
  36700. };
  36701. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36702. /********* End of inlined file: juce_GroupComponent.h *********/
  36703. #endif
  36704. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36705. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  36706. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36707. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36708. /********* Start of inlined file: juce_TabbedComponent.h *********/
  36709. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36710. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36711. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  36712. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36713. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36714. class TabbedButtonBar;
  36715. /** In a TabbedButtonBar, this component is used for each of the buttons.
  36716. If you want to create a TabbedButtonBar with custom tab components, derive
  36717. your component from this class, and override the TabbedButtonBar::createTabButton()
  36718. method to create it instead of the default one.
  36719. @see TabbedButtonBar
  36720. */
  36721. class JUCE_API TabBarButton : public Button
  36722. {
  36723. public:
  36724. /** Creates the tab button. */
  36725. TabBarButton (const String& name,
  36726. TabbedButtonBar* const ownerBar,
  36727. const int tabIndex);
  36728. /** Destructor. */
  36729. ~TabBarButton();
  36730. /** Chooses the best length for the tab, given the specified depth.
  36731. If the tab is horizontal, this should return its width, and the depth
  36732. specifies its height. If it's vertical, it should return the height, and
  36733. the depth is actually its width.
  36734. */
  36735. virtual int getBestTabLength (const int depth);
  36736. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  36737. void clicked (const ModifierKeys& mods);
  36738. bool hitTest (int x, int y);
  36739. juce_UseDebuggingNewOperator
  36740. protected:
  36741. friend class TabbedButtonBar;
  36742. TabbedButtonBar* const owner;
  36743. int tabIndex, overlapPixels;
  36744. DropShadowEffect shadow;
  36745. /** Returns an area of the component that's safe to draw in.
  36746. This deals with the orientation of the tabs, which affects which side is
  36747. touching the tabbed box's content component.
  36748. */
  36749. void getActiveArea (int& x, int& y, int& w, int& h);
  36750. private:
  36751. TabBarButton (const TabBarButton&);
  36752. const TabBarButton& operator= (const TabBarButton&);
  36753. };
  36754. /**
  36755. A vertical or horizontal bar containing tabs that you can select.
  36756. You can use one of these to generate things like a dialog box that has
  36757. tabbed pages you can flip between. Attach a ChangeListener to the
  36758. button bar to be told when the user changes the page.
  36759. An easier method than doing this is to use a TabbedComponent, which
  36760. contains its own TabbedButtonBar and which takes care of the layout
  36761. and other housekeeping.
  36762. @see TabbedComponent
  36763. */
  36764. class JUCE_API TabbedButtonBar : public Component,
  36765. public ChangeBroadcaster,
  36766. public ButtonListener
  36767. {
  36768. public:
  36769. /** The placement of the tab-bar
  36770. @see setOrientation, getOrientation
  36771. */
  36772. enum Orientation
  36773. {
  36774. TabsAtTop,
  36775. TabsAtBottom,
  36776. TabsAtLeft,
  36777. TabsAtRight
  36778. };
  36779. /** Creates a TabbedButtonBar with a given placement.
  36780. You can change the orientation later if you need to.
  36781. */
  36782. TabbedButtonBar (const Orientation orientation);
  36783. /** Destructor. */
  36784. ~TabbedButtonBar();
  36785. /** Changes the bar's orientation.
  36786. This won't change the bar's actual size - you'll need to do that yourself,
  36787. but this determines which direction the tabs go in, and which side they're
  36788. stuck to.
  36789. */
  36790. void setOrientation (const Orientation orientation);
  36791. /** Returns the current orientation.
  36792. @see setOrientation
  36793. */
  36794. Orientation getOrientation() const throw() { return orientation; }
  36795. /** Deletes all the tabs from the bar.
  36796. @see addTab
  36797. */
  36798. void clearTabs();
  36799. /** Adds a tab to the bar.
  36800. Tabs are added in left-to-right reading order.
  36801. If this is the first tab added, it'll also be automatically selected.
  36802. */
  36803. void addTab (const String& tabName,
  36804. const Colour& tabBackgroundColour,
  36805. int insertIndex = -1);
  36806. /** Changes the name of one of the tabs. */
  36807. void setTabName (const int tabIndex,
  36808. const String& newName);
  36809. /** Gets rid of one of the tabs. */
  36810. void removeTab (const int tabIndex);
  36811. /** Moves a tab to a new index in the list.
  36812. Pass -1 as the index to move it to the end of the list.
  36813. */
  36814. void moveTab (const int currentIndex,
  36815. const int newIndex);
  36816. /** Returns the number of tabs in the bar. */
  36817. int getNumTabs() const;
  36818. /** Returns a list of all the tab names in the bar. */
  36819. const StringArray getTabNames() const;
  36820. /** Changes the currently selected tab.
  36821. This will send a change message and cause a synchronous callback to
  36822. the currentTabChanged() method. (But if the given tab is already selected,
  36823. nothing will be done).
  36824. To deselect all the tabs, use an index of -1.
  36825. */
  36826. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  36827. /** Returns the name of the currently selected tab.
  36828. This could be an empty string if none are selected.
  36829. */
  36830. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  36831. /** Returns the index of the currently selected tab.
  36832. This could return -1 if none are selected.
  36833. */
  36834. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  36835. /** Returns the button for a specific tab.
  36836. The button that is returned may be deleted later by this component, so don't hang
  36837. on to the pointer that is returned. A null pointer may be returned if the index is
  36838. out of range.
  36839. */
  36840. TabBarButton* getTabButton (const int index) const;
  36841. /** Callback method to indicate the selected tab has been changed.
  36842. @see setCurrentTabIndex
  36843. */
  36844. virtual void currentTabChanged (const int newCurrentTabIndex,
  36845. const String& newCurrentTabName);
  36846. /** Callback method to indicate that the user has right-clicked on a tab.
  36847. (Or ctrl-clicked on the Mac)
  36848. */
  36849. virtual void popupMenuClickOnTab (const int tabIndex,
  36850. const String& tabName);
  36851. /** Returns the colour of a tab.
  36852. This is the colour that was specified in addTab().
  36853. */
  36854. const Colour getTabBackgroundColour (const int tabIndex);
  36855. /** Changes the background colour of a tab.
  36856. @see addTab, getTabBackgroundColour
  36857. */
  36858. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36859. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36860. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36861. methods.
  36862. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36863. */
  36864. enum ColourIds
  36865. {
  36866. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  36867. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  36868. the look and feel will choose an appropriate colour. */
  36869. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  36870. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  36871. this isn't specified, the look and feel will choose an appropriate
  36872. colour. */
  36873. };
  36874. /** @internal */
  36875. void resized();
  36876. /** @internal */
  36877. void buttonClicked (Button* button);
  36878. /** @internal */
  36879. void lookAndFeelChanged();
  36880. juce_UseDebuggingNewOperator
  36881. protected:
  36882. /** This creates one of the tabs.
  36883. If you need to use custom tab components, you can override this method and
  36884. return your own class instead of the default.
  36885. */
  36886. virtual TabBarButton* createTabButton (const String& tabName,
  36887. const int tabIndex);
  36888. private:
  36889. Orientation orientation;
  36890. StringArray tabs;
  36891. Array <Colour> tabColours;
  36892. int currentTabIndex;
  36893. Component* behindFrontTab;
  36894. Button* extraTabsButton;
  36895. TabbedButtonBar (const TabbedButtonBar&);
  36896. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  36897. };
  36898. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36899. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  36900. /**
  36901. A component with a TabbedButtonBar along one of its sides.
  36902. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  36903. with addTab(), and this will take care of showing the pages for you when the
  36904. user clicks on a different tab.
  36905. @see TabbedButtonBar
  36906. */
  36907. class JUCE_API TabbedComponent : public Component
  36908. {
  36909. public:
  36910. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  36911. Once created, add some tabs with the addTab() method.
  36912. */
  36913. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  36914. /** Destructor. */
  36915. ~TabbedComponent();
  36916. /** Changes the placement of the tabs.
  36917. This will rearrange the layout to place the tabs along the appropriate
  36918. side of this component, and will shift the content component accordingly.
  36919. @see TabbedButtonBar::setOrientation
  36920. */
  36921. void setOrientation (const TabbedButtonBar::Orientation orientation);
  36922. /** Returns the current tab placement.
  36923. @see setOrientation, TabbedButtonBar::getOrientation
  36924. */
  36925. TabbedButtonBar::Orientation getOrientation() const throw();
  36926. /** Specifies how many pixels wide or high the tab-bar should be.
  36927. If the tabs are placed along the top or bottom, this specified the height
  36928. of the bar; if they're along the left or right edges, it'll be the width
  36929. of the bar.
  36930. */
  36931. void setTabBarDepth (const int newDepth);
  36932. /** Returns the current thickness of the tab bar.
  36933. @see setTabBarDepth
  36934. */
  36935. int getTabBarDepth() const throw() { return tabDepth; }
  36936. /** Specifies the thickness of an outline that should be drawn around the content component.
  36937. If this thickness is > 0, a line will be drawn around the three sides of the content
  36938. component which don't touch the tab-bar, and the content component will be inset by this amount.
  36939. To set the colour of the line, use setColour (outlineColourId, ...).
  36940. */
  36941. void setOutline (const int newThickness);
  36942. /** Specifies a gap to leave around the edge of the content component.
  36943. Each edge of the content component will be indented by the given number of pixels.
  36944. */
  36945. void setIndent (const int indentThickness);
  36946. /** Removes all the tabs from the bar.
  36947. @see TabbedButtonBar::clearTabs
  36948. */
  36949. void clearTabs();
  36950. /** Adds a tab to the tab-bar.
  36951. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  36952. is true, it will be deleted when the tab is removed or when this object is
  36953. deleted.
  36954. @see TabbedButtonBar::addTab
  36955. */
  36956. void addTab (const String& tabName,
  36957. const Colour& tabBackgroundColour,
  36958. Component* const contentComponent,
  36959. const bool deleteComponentWhenNotNeeded,
  36960. const int insertIndex = -1);
  36961. /** Changes the name of one of the tabs. */
  36962. void setTabName (const int tabIndex,
  36963. const String& newName);
  36964. /** Gets rid of one of the tabs. */
  36965. void removeTab (const int tabIndex);
  36966. /** Returns the number of tabs in the bar. */
  36967. int getNumTabs() const;
  36968. /** Returns a list of all the tab names in the bar. */
  36969. const StringArray getTabNames() const;
  36970. /** Returns the content component that was added for the given index.
  36971. Be sure not to use or delete the components that are returned, as this may interfere
  36972. with the TabbedComponent's use of them.
  36973. */
  36974. Component* getTabContentComponent (const int tabIndex) const throw();
  36975. /** Returns the colour of one of the tabs. */
  36976. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  36977. /** Changes the background colour of one of the tabs. */
  36978. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36979. /** Changes the currently-selected tab.
  36980. To deselect all the tabs, pass -1 as the index.
  36981. @see TabbedButtonBar::setCurrentTabIndex
  36982. */
  36983. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  36984. /** Returns the index of the currently selected tab.
  36985. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  36986. */
  36987. int getCurrentTabIndex() const;
  36988. /** Returns the name of the currently selected tab.
  36989. @see addTab, TabbedButtonBar::getCurrentTabName()
  36990. */
  36991. const String& getCurrentTabName() const;
  36992. /** Returns the current component that's filling the panel.
  36993. This will return 0 if there isn't one.
  36994. */
  36995. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  36996. /** Callback method to indicate the selected tab has been changed.
  36997. @see setCurrentTabIndex
  36998. */
  36999. virtual void currentTabChanged (const int newCurrentTabIndex,
  37000. const String& newCurrentTabName);
  37001. /** Callback method to indicate that the user has right-clicked on a tab.
  37002. (Or ctrl-clicked on the Mac)
  37003. */
  37004. virtual void popupMenuClickOnTab (const int tabIndex,
  37005. const String& tabName);
  37006. /** Returns the tab button bar component that is being used.
  37007. */
  37008. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  37009. /** A set of colour IDs to use to change the colour of various aspects of the component.
  37010. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37011. methods.
  37012. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37013. */
  37014. enum ColourIds
  37015. {
  37016. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  37017. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  37018. (See setOutline) */
  37019. };
  37020. /** @internal */
  37021. void paint (Graphics& g);
  37022. /** @internal */
  37023. void resized();
  37024. /** @internal */
  37025. void lookAndFeelChanged();
  37026. juce_UseDebuggingNewOperator
  37027. protected:
  37028. TabbedButtonBar* tabs;
  37029. /** This creates one of the tab buttons.
  37030. If you need to use custom tab components, you can override this method and
  37031. return your own class instead of the default.
  37032. */
  37033. virtual TabBarButton* createTabButton (const String& tabName,
  37034. const int tabIndex);
  37035. private:
  37036. Array <Component*> contentComponents;
  37037. Component* panelComponent;
  37038. int tabDepth;
  37039. int outlineThickness, edgeIndent;
  37040. friend class TabCompButtonBar;
  37041. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  37042. TabbedComponent (const TabbedComponent&);
  37043. const TabbedComponent& operator= (const TabbedComponent&);
  37044. };
  37045. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  37046. /********* End of inlined file: juce_TabbedComponent.h *********/
  37047. /********* Start of inlined file: juce_DocumentWindow.h *********/
  37048. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37049. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37050. /********* Start of inlined file: juce_ResizableWindow.h *********/
  37051. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37052. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37053. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  37054. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37055. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37056. /********* Start of inlined file: juce_DropShadower.h *********/
  37057. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  37058. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  37059. /**
  37060. Adds a drop-shadow to a component.
  37061. This object creates and manages a set of components which sit around a
  37062. component, creating a gaussian shadow around it. The components will track
  37063. the position of the component and if it's brought to the front they'll also
  37064. follow this.
  37065. For desktop windows you don't need to use this class directly - just
  37066. set the Component::windowHasDropShadow flag when calling
  37067. Component::addToDesktop(), and the system will create one of these if it's
  37068. needed (which it obviously isn't on the Mac, for example).
  37069. */
  37070. class JUCE_API DropShadower : public ComponentListener
  37071. {
  37072. public:
  37073. /** Creates a DropShadower.
  37074. @param alpha the opacity of the shadows, from 0 to 1.0
  37075. @param xOffset the horizontal displacement of the shadow, in pixels
  37076. @param yOffset the vertical displacement of the shadow, in pixels
  37077. @param blurRadius the radius of the blur to use for creating the shadow
  37078. */
  37079. DropShadower (const float alpha = 0.5f,
  37080. const int xOffset = 1,
  37081. const int yOffset = 5,
  37082. const float blurRadius = 10.0f);
  37083. /** Destructor. */
  37084. virtual ~DropShadower();
  37085. /** Attaches the DropShadower to the component you want to shadow. */
  37086. void setOwner (Component* componentToFollow);
  37087. /** @internal */
  37088. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  37089. /** @internal */
  37090. void componentBroughtToFront (Component& component);
  37091. /** @internal */
  37092. void componentChildrenChanged (Component& component);
  37093. /** @internal */
  37094. void componentParentHierarchyChanged (Component& component);
  37095. /** @internal */
  37096. void componentVisibilityChanged (Component& component);
  37097. juce_UseDebuggingNewOperator
  37098. private:
  37099. Component* owner;
  37100. int numShadows;
  37101. Component* shadowWindows[4];
  37102. Image* shadowImageSections[12];
  37103. const int shadowEdge, xOffset, yOffset;
  37104. const float alpha, blurRadius;
  37105. bool inDestructor, reentrant;
  37106. void updateShadows();
  37107. void setShadowImage (Image* const src,
  37108. const int num,
  37109. const int w, const int h,
  37110. const int sx, const int sy) throw();
  37111. void bringShadowWindowsToFront();
  37112. void deleteShadowWindows();
  37113. DropShadower (const DropShadower&);
  37114. const DropShadower& operator= (const DropShadower&);
  37115. };
  37116. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  37117. /********* End of inlined file: juce_DropShadower.h *********/
  37118. /**
  37119. A base class for top-level windows.
  37120. This class is used for components that are considered a major part of your
  37121. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  37122. etc. Things like menus that pop up briefly aren't derived from it.
  37123. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  37124. could itself be the child of another component.
  37125. The class manages a list of all instances of top-level windows that are in use,
  37126. and each one is also given the concept of being "active". The active window is
  37127. one that is actively being used by the user. This isn't quite the same as the
  37128. component with the keyboard focus, because there may be a popup menu or other
  37129. temporary window which gets keyboard focus while the active top level window is
  37130. unchanged.
  37131. A top-level window also has an optional drop-shadow.
  37132. @see ResizableWindow, DocumentWindow, DialogWindow
  37133. */
  37134. class JUCE_API TopLevelWindow : public Component
  37135. {
  37136. public:
  37137. /** Creates a TopLevelWindow.
  37138. @param name the name to give the component
  37139. @param addToDesktop if true, the window will be automatically added to the
  37140. desktop; if false, you can use it as a child component
  37141. */
  37142. TopLevelWindow (const String& name,
  37143. const bool addToDesktop);
  37144. /** Destructor. */
  37145. ~TopLevelWindow();
  37146. /** True if this is currently the TopLevelWindow that is actively being used.
  37147. This isn't quite the same as having keyboard focus, because the focus may be
  37148. on a child component or a temporary pop-up menu, etc, while this window is
  37149. still considered to be active.
  37150. @see activeWindowStatusChanged
  37151. */
  37152. bool isActiveWindow() const throw() { return windowIsActive_; }
  37153. /** This will set the bounds of the window so that it's centred in front of another
  37154. window.
  37155. If your app has a few windows open and want to pop up a dialog box for one of
  37156. them, you can use this to show it in front of the relevent parent window, which
  37157. is a bit neater than just having it appear in the middle of the screen.
  37158. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  37159. be used instead. If no window is focused, it'll just default to the middle of the
  37160. screen.
  37161. */
  37162. void centreAroundComponent (Component* componentToCentreAround,
  37163. const int width, const int height);
  37164. /** Turns the drop-shadow on and off. */
  37165. void setDropShadowEnabled (const bool useShadow);
  37166. /** Sets whether an OS-native title bar will be used, or a Juce one.
  37167. @see isUsingNativeTitleBar
  37168. */
  37169. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  37170. /** Returns true if the window is currently using an OS-native title bar.
  37171. @see setUsingNativeTitleBar
  37172. */
  37173. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  37174. /** Returns the number of TopLevelWindow objects currently in use.
  37175. @see getTopLevelWindow
  37176. */
  37177. static int getNumTopLevelWindows() throw();
  37178. /** Returns one of the TopLevelWindow objects currently in use.
  37179. The index is 0 to (getNumTopLevelWindows() - 1).
  37180. */
  37181. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  37182. /** Returns the currently-active top level window.
  37183. There might not be one, of course, so this can return 0.
  37184. */
  37185. static TopLevelWindow* getActiveTopLevelWindow() throw();
  37186. juce_UseDebuggingNewOperator
  37187. /** @internal */
  37188. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  37189. protected:
  37190. /** This callback happens when this window becomes active or inactive.
  37191. @see isActiveWindow
  37192. */
  37193. virtual void activeWindowStatusChanged();
  37194. /** @internal */
  37195. void focusOfChildComponentChanged (FocusChangeType cause);
  37196. /** @internal */
  37197. void parentHierarchyChanged();
  37198. /** @internal */
  37199. void visibilityChanged();
  37200. /** @internal */
  37201. virtual int getDesktopWindowStyleFlags() const;
  37202. /** @internal */
  37203. void recreateDesktopWindow();
  37204. private:
  37205. friend class TopLevelWindowManager;
  37206. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  37207. DropShadower* shadower;
  37208. void setWindowActive (const bool isNowActive) throw();
  37209. TopLevelWindow (const TopLevelWindow&);
  37210. const TopLevelWindow& operator= (const TopLevelWindow&);
  37211. };
  37212. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37213. /********* End of inlined file: juce_TopLevelWindow.h *********/
  37214. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  37215. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37216. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37217. /**
  37218. A component that resizes its parent window when dragged.
  37219. This component forms a frame around the edge of a component, allowing it to
  37220. be dragged by the edges or corners to resize it - like the way windows are
  37221. resized in MSWindows or Linux.
  37222. To use it, just add it to your component, making it fill the entire parent component
  37223. (there's a mouse hit-test that only traps mouse-events which land around the
  37224. edge of the component, so it's even ok to put it on top of any other components
  37225. you're using). Make sure you rescale the resizer component to fill the parent
  37226. each time the parent's size changes.
  37227. @see ResizableCornerComponent
  37228. */
  37229. class JUCE_API ResizableBorderComponent : public Component
  37230. {
  37231. public:
  37232. /** Creates a resizer.
  37233. Pass in the target component which you want to be resized when this one is
  37234. dragged.
  37235. The target component will usually be a parent of the resizer component, but this
  37236. isn't mandatory.
  37237. Remember that when the target component is resized, it'll need to move and
  37238. resize this component to keep it in place, as this won't happen automatically.
  37239. If the constrainer parameter is non-zero, then this object will be used to enforce
  37240. limits on the size and position that the component can be stretched to. Make sure
  37241. that the constrainer isn't deleted while still in use by this object.
  37242. @see ComponentBoundsConstrainer
  37243. */
  37244. ResizableBorderComponent (Component* const componentToResize,
  37245. ComponentBoundsConstrainer* const constrainer);
  37246. /** Destructor. */
  37247. ~ResizableBorderComponent();
  37248. /** Specifies how many pixels wide the draggable edges of this component are.
  37249. @see getBorderThickness
  37250. */
  37251. void setBorderThickness (const BorderSize& newBorderSize) throw();
  37252. /** Returns the number of pixels wide that the draggable edges of this component are.
  37253. @see setBorderThickness
  37254. */
  37255. const BorderSize getBorderThickness() const throw();
  37256. juce_UseDebuggingNewOperator
  37257. protected:
  37258. /** @internal */
  37259. void paint (Graphics& g);
  37260. /** @internal */
  37261. void mouseEnter (const MouseEvent& e);
  37262. /** @internal */
  37263. void mouseMove (const MouseEvent& e);
  37264. /** @internal */
  37265. void mouseDown (const MouseEvent& e);
  37266. /** @internal */
  37267. void mouseDrag (const MouseEvent& e);
  37268. /** @internal */
  37269. void mouseUp (const MouseEvent& e);
  37270. /** @internal */
  37271. bool hitTest (int x, int y);
  37272. private:
  37273. Component* const component;
  37274. ComponentBoundsConstrainer* constrainer;
  37275. BorderSize borderSize;
  37276. int originalX, originalY, originalW, originalH;
  37277. int mouseZone;
  37278. void updateMouseZone (const MouseEvent& e) throw();
  37279. ResizableBorderComponent (const ResizableBorderComponent&);
  37280. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  37281. };
  37282. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37283. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  37284. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  37285. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37286. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37287. /** A component that resizes a parent window when dragged.
  37288. This is the small triangular stripey resizer component you get in the bottom-right
  37289. of windows (more commonly on the Mac than Windows). Put one in the corner of
  37290. a larger component and it will automatically resize its parent when it gets dragged
  37291. around.
  37292. @see ResizableFrameComponent
  37293. */
  37294. class JUCE_API ResizableCornerComponent : public Component
  37295. {
  37296. public:
  37297. /** Creates a resizer.
  37298. Pass in the target component which you want to be resized when this one is
  37299. dragged.
  37300. The target component will usually be a parent of the resizer component, but this
  37301. isn't mandatory.
  37302. Remember that when the target component is resized, it'll need to move and
  37303. resize this component to keep it in place, as this won't happen automatically.
  37304. If the constrainer parameter is non-zero, then this object will be used to enforce
  37305. limits on the size and position that the component can be stretched to. Make sure
  37306. that the constrainer isn't deleted while still in use by this object. If you
  37307. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  37308. @see ComponentBoundsConstrainer
  37309. */
  37310. ResizableCornerComponent (Component* const componentToResize,
  37311. ComponentBoundsConstrainer* const constrainer);
  37312. /** Destructor. */
  37313. ~ResizableCornerComponent();
  37314. juce_UseDebuggingNewOperator
  37315. protected:
  37316. /** @internal */
  37317. void paint (Graphics& g);
  37318. /** @internal */
  37319. void mouseDown (const MouseEvent& e);
  37320. /** @internal */
  37321. void mouseDrag (const MouseEvent& e);
  37322. /** @internal */
  37323. void mouseUp (const MouseEvent& e);
  37324. /** @internal */
  37325. bool hitTest (int x, int y);
  37326. private:
  37327. Component* const component;
  37328. ComponentBoundsConstrainer* constrainer;
  37329. int originalX, originalY, originalW, originalH;
  37330. ResizableCornerComponent (const ResizableCornerComponent&);
  37331. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  37332. };
  37333. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37334. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  37335. /**
  37336. A base class for top-level windows that can be dragged around and resized.
  37337. To add content to the window, use its setContentComponent() method to
  37338. give it a component that will remain positioned inside it (leaving a gap around
  37339. the edges for a border).
  37340. It's not advisable to add child components directly to a ResizableWindow: put them
  37341. inside your content component instead. And overriding methods like resized(), moved(), etc
  37342. is also not recommended - instead override these methods for your content component.
  37343. (If for some obscure reason you do need to override these methods, always remember to
  37344. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37345. decorations correctly).
  37346. By default resizing isn't enabled - use the setResizable() method to enable it and
  37347. to choose the style of resizing to use.
  37348. @see TopLevelWindow
  37349. */
  37350. class JUCE_API ResizableWindow : public TopLevelWindow
  37351. {
  37352. public:
  37353. /** Creates a ResizableWindow.
  37354. This constructor doesn't specify a background colour, so the LookAndFeel's default
  37355. background colour will be used.
  37356. @param name the name to give the component
  37357. @param addToDesktop if true, the window will be automatically added to the
  37358. desktop; if false, you can use it as a child component
  37359. */
  37360. ResizableWindow (const String& name,
  37361. const bool addToDesktop);
  37362. /** Creates a ResizableWindow.
  37363. @param name the name to give the component
  37364. @param backgroundColour the colour to use for filling the window's background.
  37365. @param addToDesktop if true, the window will be automatically added to the
  37366. desktop; if false, you can use it as a child component
  37367. */
  37368. ResizableWindow (const String& name,
  37369. const Colour& backgroundColour,
  37370. const bool addToDesktop);
  37371. /** Destructor.
  37372. If a content component has been set with setContentComponent(), it
  37373. will be deleted.
  37374. */
  37375. ~ResizableWindow();
  37376. /** Returns the colour currently being used for the window's background.
  37377. As a convenience the window will fill itself with this colour, but you
  37378. can override the paint() method if you need more customised behaviour.
  37379. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  37380. @see setBackgroundColour
  37381. */
  37382. const Colour getBackgroundColour() const throw();
  37383. /** Changes the colour currently being used for the window's background.
  37384. As a convenience the window will fill itself with this colour, but you
  37385. can override the paint() method if you need more customised behaviour.
  37386. Note that the opaque state of this window is altered by this call to reflect
  37387. the opacity of the colour passed-in. On window systems which can't support
  37388. semi-transparent windows this might cause problems, (though it's unlikely you'll
  37389. be using this class as a base for a semi-transparent component anyway).
  37390. You can also use the ResizableWindow::backgroundColourId colour id to set
  37391. this colour.
  37392. @see getBackgroundColour
  37393. */
  37394. void setBackgroundColour (const Colour& newColour);
  37395. /** Make the window resizable or fixed.
  37396. @param shouldBeResizable whether it's resizable at all
  37397. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  37398. bottom-right; if false, it'll use a ResizableBorderComponent
  37399. around the edge
  37400. @see setResizeLimits, isResizable
  37401. */
  37402. void setResizable (const bool shouldBeResizable,
  37403. const bool useBottomRightCornerResizer);
  37404. /** True if resizing is enabled.
  37405. @see setResizable
  37406. */
  37407. bool isResizable() const throw();
  37408. /** This sets the maximum and minimum sizes for the window.
  37409. If the window's current size is outside these limits, it will be resized to
  37410. make sure it's within them.
  37411. Calling setBounds() on the component will bypass any size checking - it's only when
  37412. the window is being resized by the user that these values are enforced.
  37413. @see setResizable, setFixedAspectRatio
  37414. */
  37415. void setResizeLimits (const int newMinimumWidth,
  37416. const int newMinimumHeight,
  37417. const int newMaximumWidth,
  37418. const int newMaximumHeight) throw();
  37419. /** Returns the bounds constrainer object that this window is using.
  37420. You can access this to change its properties.
  37421. */
  37422. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  37423. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  37424. A pointer to the object you pass in will be kept, but it won't be deleted
  37425. by this object, so it's the caller's responsiblity to manage it.
  37426. If you pass 0, then no contraints will be placed on the positioning of the window.
  37427. */
  37428. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  37429. /** Calls the window's setBounds method, after first checking these bounds
  37430. with the current constrainer.
  37431. @see setConstrainer
  37432. */
  37433. void setBoundsConstrained (int x, int y, int width, int height);
  37434. /** Returns true if the window is currently in full-screen mode.
  37435. @see setFullScreen
  37436. */
  37437. bool isFullScreen() const;
  37438. /** Puts the window into full-screen mode, or restores it to its normal size.
  37439. If true, the window will become full-screen; if false, it will return to the
  37440. last size it was before being made full-screen.
  37441. @see isFullScreen
  37442. */
  37443. void setFullScreen (const bool shouldBeFullScreen);
  37444. /** Returns true if the window is currently minimised.
  37445. @see setMinimised
  37446. */
  37447. bool isMinimised() const;
  37448. /** Minimises the window, or restores it to its previous position and size.
  37449. When being un-minimised, it'll return to the last position and size it
  37450. was in before being minimised.
  37451. @see isMinimised
  37452. */
  37453. void setMinimised (const bool shouldMinimise);
  37454. /** Returns a string which encodes the window's current size and position.
  37455. This string will encapsulate the window's size, position, and whether it's
  37456. in full-screen mode. It's intended for letting your application save and
  37457. restore a window's position.
  37458. Use the restoreWindowStateFromString() to restore from a saved state.
  37459. @see restoreWindowStateFromString
  37460. */
  37461. const String getWindowStateAsString();
  37462. /** Restores the window to a previously-saved size and position.
  37463. This restores the window's size, positon and full-screen status from an
  37464. string that was previously created with the getWindowStateAsString()
  37465. method.
  37466. @returns false if the string wasn't a valid window state
  37467. @see getWindowStateAsString
  37468. */
  37469. bool restoreWindowStateFromString (const String& previousState);
  37470. /** Returns the current content component.
  37471. This will be the component set by setContentComponent(), or 0 if none
  37472. has yet been specified.
  37473. @see setContentComponent
  37474. */
  37475. Component* getContentComponent() const throw() { return contentComponent; }
  37476. /** Changes the current content component.
  37477. This sets a component that will be placed in the centre of the ResizableWindow,
  37478. (leaving a space around the edge for the border).
  37479. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37480. with addChildComponent(). Instead, add them to the content component.
  37481. @param newContentComponent the new component to use (or null to not use one) - this
  37482. component will be deleted either when replaced by another call
  37483. to this method, or when the ResizableWindow is deleted.
  37484. To remove a content component without deleting it, use
  37485. setContentComponent (0, false).
  37486. @param deleteOldOne if true, the previous content component will be deleted; if
  37487. false, the previous component will just be removed without
  37488. deleting it.
  37489. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37490. it always fits around the size of the content component. If false, the
  37491. new content will be resized to fit the current space available.
  37492. */
  37493. void setContentComponent (Component* const newContentComponent,
  37494. const bool deleteOldOne = true,
  37495. const bool resizeToFit = false);
  37496. /** Changes the window so that the content component ends up with the specified size.
  37497. This is basically a setSize call on the window, but which adds on the borders,
  37498. so you can specify the content component's target size.
  37499. */
  37500. void setContentComponentSize (int width, int height);
  37501. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37502. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37503. methods.
  37504. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37505. */
  37506. enum ColourIds
  37507. {
  37508. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37509. };
  37510. juce_UseDebuggingNewOperator
  37511. protected:
  37512. /** @internal */
  37513. void paint (Graphics& g);
  37514. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37515. void moved();
  37516. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37517. void resized();
  37518. /** @internal */
  37519. void mouseDown (const MouseEvent& e);
  37520. /** @internal */
  37521. void mouseDrag (const MouseEvent& e);
  37522. /** @internal */
  37523. void lookAndFeelChanged();
  37524. /** @internal */
  37525. void childBoundsChanged (Component* child);
  37526. /** @internal */
  37527. void parentSizeChanged();
  37528. /** @internal */
  37529. void visibilityChanged();
  37530. /** @internal */
  37531. void activeWindowStatusChanged();
  37532. /** @internal */
  37533. int getDesktopWindowStyleFlags() const;
  37534. /** Returns the width of the border to use around the window.
  37535. @see getContentComponentBorder
  37536. */
  37537. virtual const BorderSize getBorderThickness();
  37538. /** Returns the insets to use when positioning the content component.
  37539. @see getBorderThickness
  37540. */
  37541. virtual const BorderSize getContentComponentBorder();
  37542. #ifdef JUCE_DEBUG
  37543. /** Overridden to warn people about adding components directly to this component
  37544. instead of using setContentComponent().
  37545. If you know what you're doing and are sure you really want to add a component, specify
  37546. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37547. */
  37548. void addChildComponent (Component* const child, int zOrder = -1);
  37549. /** Overridden to warn people about adding components directly to this component
  37550. instead of using setContentComponent().
  37551. If you know what you're doing and are sure you really want to add a component, specify
  37552. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37553. */
  37554. void addAndMakeVisible (Component* const child, int zOrder = -1);
  37555. #endif
  37556. ResizableCornerComponent* resizableCorner;
  37557. ResizableBorderComponent* resizableBorder;
  37558. private:
  37559. Component* contentComponent;
  37560. bool resizeToFitContent, fullscreen;
  37561. ComponentDragger dragger;
  37562. Rectangle lastNonFullScreenPos;
  37563. ComponentBoundsConstrainer defaultConstrainer;
  37564. ComponentBoundsConstrainer* constrainer;
  37565. #ifdef JUCE_DEBUG
  37566. bool hasBeenResized;
  37567. #endif
  37568. void updateLastPos();
  37569. ResizableWindow (const ResizableWindow&);
  37570. const ResizableWindow& operator= (const ResizableWindow&);
  37571. // (xxx remove these eventually)
  37572. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37573. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37574. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37575. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37576. };
  37577. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37578. /********* End of inlined file: juce_ResizableWindow.h *********/
  37579. /**
  37580. A resizable window with a title bar and maximise, minimise and close buttons.
  37581. This subclass of ResizableWindow creates a fairly standard type of window with
  37582. a title bar and various buttons. The name of the component is shown in the
  37583. title bar, and an icon can optionally be specified with setIcon().
  37584. All the methods available to a ResizableWindow are also available to this,
  37585. so it can easily be made resizable, minimised, maximised, etc.
  37586. It's not advisable to add child components directly to a DocumentWindow: put them
  37587. inside your content component instead. And overriding methods like resized(), moved(), etc
  37588. is also not recommended - instead override these methods for your content component.
  37589. (If for some obscure reason you do need to override these methods, always remember to
  37590. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37591. decorations correctly).
  37592. You can also automatically add a menu bar to the window, using the setMenuBar()
  37593. method.
  37594. @see ResizableWindow, DialogWindow
  37595. */
  37596. class JUCE_API DocumentWindow : public ResizableWindow
  37597. {
  37598. public:
  37599. /** The set of available button-types that can be put on the title bar.
  37600. @see setTitleBarButtonsRequired
  37601. */
  37602. enum TitleBarButtons
  37603. {
  37604. minimiseButton = 1,
  37605. maximiseButton = 2,
  37606. closeButton = 4,
  37607. /** A combination of all the buttons above. */
  37608. allButtons = 7
  37609. };
  37610. /** Creates a DocumentWindow.
  37611. @param name the name to give the component - this is also
  37612. the title shown at the top of the window. To change
  37613. this later, use setName()
  37614. @param backgroundColour the colour to use for filling the window's background.
  37615. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  37616. should be shown on the title bar. This value is a bitwise
  37617. combination of values from the TitleBarButtons enum. Note
  37618. that it can be "allButtons" to get them all. You
  37619. can change this later with the setTitleBarButtonsRequired()
  37620. method, which can also specify where they are positioned.
  37621. @param addToDesktop if true, the window will be automatically added to the
  37622. desktop; if false, you can use it as a child component
  37623. @see TitleBarButtons
  37624. */
  37625. DocumentWindow (const String& name,
  37626. const Colour& backgroundColour,
  37627. const int requiredButtons,
  37628. const bool addToDesktop = true);
  37629. /** Destructor.
  37630. If a content component has been set with setContentComponent(), it
  37631. will be deleted.
  37632. */
  37633. ~DocumentWindow();
  37634. /** Changes the component's name.
  37635. (This is overridden from Component::setName() to cause a repaint, as
  37636. the name is what gets drawn across the window's title bar).
  37637. */
  37638. void setName (const String& newName);
  37639. /** Sets an icon to show in the title bar, next to the title.
  37640. A copy is made internally of the image, so the caller can delete the
  37641. image after calling this. If 0 is passed-in, any existing icon will be
  37642. removed.
  37643. */
  37644. void setIcon (const Image* imageToUse);
  37645. /** Changes the height of the title-bar. */
  37646. void setTitleBarHeight (const int newHeight);
  37647. /** Returns the current title bar height. */
  37648. int getTitleBarHeight() const;
  37649. /** Changes the set of title-bar buttons being shown.
  37650. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  37651. should be shown on the title bar. This value is a bitwise
  37652. combination of values from the TitleBarButtons enum. Note
  37653. that it can be "allButtons" to get them all.
  37654. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  37655. left side of the bar; if false, they'll be placed at the right
  37656. */
  37657. void setTitleBarButtonsRequired (const int requiredButtons,
  37658. const bool positionTitleBarButtonsOnLeft);
  37659. /** Sets whether the title should be centred within the window.
  37660. If true, the title text is shown in the middle of the title-bar; if false,
  37661. it'll be shown at the left of the bar.
  37662. */
  37663. void setTitleBarTextCentred (const bool textShouldBeCentred);
  37664. /** Creates a menu inside this window.
  37665. @param menuBarModel this specifies a MenuBarModel that should be used to
  37666. generate the contents of a menu bar that will be placed
  37667. just below the title bar, and just above any content
  37668. component. If this value is zero, any existing menu bar
  37669. will be removed from the component; if non-zero, one will
  37670. be added if it's required.
  37671. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  37672. or less to use the look-and-feel's default size.
  37673. */
  37674. void setMenuBar (MenuBarModel* menuBarModel,
  37675. const int menuBarHeight = 0);
  37676. /** This method is called when the user tries to close the window.
  37677. This is triggered by the user clicking the close button, or using some other
  37678. OS-specific key shortcut or OS menu for getting rid of a window.
  37679. If the window is just a pop-up, you should override this closeButtonPressed()
  37680. method and make it delete the window in whatever way is appropriate for your
  37681. app. E.g. you might just want to call "delete this".
  37682. If your app is centred around this window such that the whole app should quit when
  37683. the window is closed, then you will probably want to use this method as an opportunity
  37684. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  37685. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  37686. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  37687. or closing it via the taskbar icon on Windows).
  37688. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  37689. redirects it to call this method, so any methods of closing the window that are
  37690. caught by userTriedToCloseWindow() will also end up here).
  37691. */
  37692. virtual void closeButtonPressed();
  37693. /** Callback that is triggered when the minimise button is pressed.
  37694. The default implementation of this calls ResizableWindow::setMinimised(), but
  37695. you can override it to do more customised behaviour.
  37696. */
  37697. virtual void minimiseButtonPressed();
  37698. /** Callback that is triggered when the maximise button is pressed, or when the
  37699. title-bar is double-clicked.
  37700. The default implementation of this calls ResizableWindow::setFullScreen(), but
  37701. you can override it to do more customised behaviour.
  37702. */
  37703. virtual void maximiseButtonPressed();
  37704. /** Returns the close button, (or 0 if there isn't one). */
  37705. Button* getCloseButton() const throw();
  37706. /** Returns the minimise button, (or 0 if there isn't one). */
  37707. Button* getMinimiseButton() const throw();
  37708. /** Returns the maximise button, (or 0 if there isn't one). */
  37709. Button* getMaximiseButton() const throw();
  37710. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37711. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37712. methods.
  37713. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37714. */
  37715. enum ColourIds
  37716. {
  37717. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  37718. and feel class how this is used. */
  37719. };
  37720. /** @internal */
  37721. void paint (Graphics& g);
  37722. /** @internal */
  37723. void resized();
  37724. /** @internal */
  37725. void lookAndFeelChanged();
  37726. /** @internal */
  37727. const BorderSize getBorderThickness();
  37728. /** @internal */
  37729. const BorderSize getContentComponentBorder();
  37730. /** @internal */
  37731. void mouseDoubleClick (const MouseEvent& e);
  37732. /** @internal */
  37733. void userTriedToCloseWindow();
  37734. /** @internal */
  37735. void activeWindowStatusChanged();
  37736. /** @internal */
  37737. int getDesktopWindowStyleFlags() const;
  37738. /** @internal */
  37739. void parentHierarchyChanged();
  37740. /** @internal */
  37741. const Rectangle getTitleBarArea();
  37742. juce_UseDebuggingNewOperator
  37743. private:
  37744. int titleBarHeight, menuBarHeight, requiredButtons;
  37745. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  37746. Button* titleBarButtons [3];
  37747. Image* titleBarIcon;
  37748. MenuBarComponent* menuBar;
  37749. MenuBarModel* menuBarModel;
  37750. class ButtonListenerProxy : public ButtonListener
  37751. {
  37752. public:
  37753. ButtonListenerProxy();
  37754. void buttonClicked (Button* button);
  37755. DocumentWindow* owner;
  37756. } buttonListener;
  37757. void repaintTitleBar();
  37758. DocumentWindow (const DocumentWindow&);
  37759. const DocumentWindow& operator= (const DocumentWindow&);
  37760. };
  37761. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37762. /********* End of inlined file: juce_DocumentWindow.h *********/
  37763. class MultiDocumentPanel;
  37764. class MDITabbedComponentInternal;
  37765. /**
  37766. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  37767. component.
  37768. It's like a normal DocumentWindow but has some extra functionality to make sure
  37769. everything works nicely inside a MultiDocumentPanel.
  37770. @see MultiDocumentPanel
  37771. */
  37772. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  37773. {
  37774. public:
  37775. /**
  37776. */
  37777. MultiDocumentPanelWindow (const Colour& backgroundColour);
  37778. /** Destructor. */
  37779. ~MultiDocumentPanelWindow();
  37780. /** @internal */
  37781. void maximiseButtonPressed();
  37782. /** @internal */
  37783. void closeButtonPressed();
  37784. /** @internal */
  37785. void activeWindowStatusChanged();
  37786. /** @internal */
  37787. void broughtToFront();
  37788. juce_UseDebuggingNewOperator
  37789. private:
  37790. void updateOrder();
  37791. MultiDocumentPanel* getOwner() const throw();
  37792. };
  37793. /**
  37794. A component that contains a set of other components either in floating windows
  37795. or tabs.
  37796. This acts as a panel that can be used to hold a set of open document windows, with
  37797. different layout modes.
  37798. Use addDocument() and closeDocument() to add or remove components from the
  37799. panel - never use any of the Component methods to access the panel's child
  37800. components directly, as these are managed internally.
  37801. */
  37802. class JUCE_API MultiDocumentPanel : public Component,
  37803. private ComponentListener
  37804. {
  37805. public:
  37806. /** Creates an empty panel.
  37807. Use addDocument() and closeDocument() to add or remove components from the
  37808. panel - never use any of the Component methods to access the panel's child
  37809. components directly, as these are managed internally.
  37810. */
  37811. MultiDocumentPanel();
  37812. /** Destructor.
  37813. When deleted, this will call closeAllDocuments (false) to make sure all its
  37814. components are deleted. If you need to make sure all documents are saved
  37815. before closing, then you should call closeAllDocuments (true) and check that
  37816. it returns true before deleting the panel.
  37817. */
  37818. ~MultiDocumentPanel();
  37819. /** Tries to close all the documents.
  37820. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37821. be called for each open document, and any of these calls fails, this method
  37822. will stop and return false, leaving some documents still open.
  37823. If checkItsOkToCloseFirst is false, then all documents will be closed
  37824. unconditionally.
  37825. @see closeDocument
  37826. */
  37827. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  37828. /** Adds a document component to the panel.
  37829. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  37830. this will fail and return false. (If it does fail, the component passed-in will not be
  37831. deleted, even if deleteWhenRemoved was set to true).
  37832. The MultiDocumentPanel will deal with creating a window border to go around your component,
  37833. so just pass in the bare content component here, no need to give it a ResizableWindow
  37834. or DocumentWindow.
  37835. @param component the component to add
  37836. @param backgroundColour the background colour to use to fill the component's
  37837. window or tab
  37838. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  37839. or closeAllDocuments(), then it will be deleted. If false, then
  37840. the caller must handle the component's deletion
  37841. */
  37842. bool addDocument (Component* const component,
  37843. const Colour& backgroundColour,
  37844. const bool deleteWhenRemoved);
  37845. /** Closes one of the documents.
  37846. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37847. be called, and if it fails, this method will return false without closing the
  37848. document.
  37849. If checkItsOkToCloseFirst is false, then the documents will be closed
  37850. unconditionally.
  37851. The component will be deleted if the deleteWhenRemoved parameter was set to
  37852. true when it was added with addDocument.
  37853. @see addDocument, closeAllDocuments
  37854. */
  37855. bool closeDocument (Component* component,
  37856. const bool checkItsOkToCloseFirst);
  37857. /** Returns the number of open document windows.
  37858. @see getDocument
  37859. */
  37860. int getNumDocuments() const throw();
  37861. /** Returns one of the open documents.
  37862. The order of the documents in this array may change when they are added, removed
  37863. or moved around.
  37864. @see getNumDocuments
  37865. */
  37866. Component* getDocument (const int index) const throw();
  37867. /** Returns the document component that is currently focused or on top.
  37868. If currently using floating windows, then this will be the component in the currently
  37869. active window, or the top component if none are active.
  37870. If it's currently in tabbed mode, then it'll return the component in the active tab.
  37871. @see setActiveDocument
  37872. */
  37873. Component* getActiveDocument() const throw();
  37874. /** Makes one of the components active and brings it to the top.
  37875. @see getActiveDocument
  37876. */
  37877. void setActiveDocument (Component* component);
  37878. /** Callback which gets invoked when the currently-active document changes. */
  37879. virtual void activeDocumentChanged();
  37880. /** Sets a limit on how many windows can be open at once.
  37881. If this is zero or less there's no limit (the default). addDocument() will fail
  37882. if this number is exceeded.
  37883. */
  37884. void setMaximumNumDocuments (const int maximumNumDocuments);
  37885. /** Sets an option to make the document fullscreen if there's only one document open.
  37886. If set to true, then if there's only one document, it'll fill the whole of this
  37887. component without tabs or a window border. If false, then tabs or a window
  37888. will always be shown, even if there's only one document. If there's more than
  37889. one document open, then this option makes no difference.
  37890. */
  37891. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  37892. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  37893. */
  37894. bool isFullscreenWhenOneDocument() const throw();
  37895. /** The different layout modes available. */
  37896. enum LayoutMode
  37897. {
  37898. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  37899. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  37900. };
  37901. /** Changes the panel's mode.
  37902. @see LayoutMode, getLayoutMode
  37903. */
  37904. void setLayoutMode (const LayoutMode newLayoutMode);
  37905. /** Returns the current layout mode. */
  37906. LayoutMode getLayoutMode() const throw() { return mode; }
  37907. /** Sets the background colour for the whole panel.
  37908. Each document has its own background colour, but this is the one used to fill the areas
  37909. behind them.
  37910. */
  37911. void setBackgroundColour (const Colour& newBackgroundColour);
  37912. /** Returns the current background colour.
  37913. @see setBackgroundColour
  37914. */
  37915. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  37916. /** A subclass must override this to say whether its currently ok for a document
  37917. to be closed.
  37918. This method is called by closeDocument() and closeAllDocuments() to indicate that
  37919. a document should be saved if possible, ready for it to be closed.
  37920. If this method returns true, then it means the document is ok and can be closed.
  37921. If it returns false, then it means that the closeDocument() method should stop
  37922. and not close.
  37923. Normally, you'd use this method to ask the user if they want to save any changes,
  37924. then return true if the save operation went ok. If the user cancelled the save
  37925. operation you could return false here to abort the close operation.
  37926. If your component is based on the FileBasedDocument class, then you'd probably want
  37927. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  37928. FileBasedDocument::savedOk
  37929. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  37930. */
  37931. virtual bool tryToCloseDocument (Component* component) = 0;
  37932. /** Creates a new window to be used for a document.
  37933. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  37934. but you might want to override it to return a custom component.
  37935. */
  37936. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  37937. /** @internal */
  37938. void paint (Graphics& g);
  37939. /** @internal */
  37940. void resized();
  37941. /** @internal */
  37942. void componentNameChanged (Component&);
  37943. juce_UseDebuggingNewOperator
  37944. private:
  37945. LayoutMode mode;
  37946. Array <Component*> components;
  37947. TabbedComponent* tabComponent;
  37948. Colour backgroundColour;
  37949. int maximumNumDocuments, numDocsBeforeTabsUsed;
  37950. friend class MultiDocumentPanelWindow;
  37951. friend class MDITabbedComponentInternal;
  37952. Component* getContainerComp (Component* c) const;
  37953. void updateOrder();
  37954. void addWindow (Component* component);
  37955. };
  37956. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  37957. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  37958. #endif
  37959. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37960. #endif
  37961. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37962. #endif
  37963. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  37964. #endif
  37965. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37966. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  37967. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37968. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37969. /**
  37970. For laying out a set of components, where the components have preferred sizes
  37971. and size limits, but where they are allowed to stretch to fill the available
  37972. space.
  37973. For example, if you have a component containing several other components, and
  37974. each one should be given a share of the total size, you could use one of these
  37975. to resize the child components when the parent component is resized. Then
  37976. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  37977. A StretchableLayoutManager operates only in one dimension, so if you have a set
  37978. of components stacked vertically on top of each other, you'd use one to manage their
  37979. heights. To build up complex arrangements of components, e.g. for applications
  37980. with multiple nested panels, you would use more than one StretchableLayoutManager.
  37981. E.g. by using two (one vertical, one horizontal), you could create a resizable
  37982. spreadsheet-style table.
  37983. E.g.
  37984. @code
  37985. class MyComp : public Component
  37986. {
  37987. StretchableLayoutManager myLayout;
  37988. MyComp()
  37989. {
  37990. myLayout.setItemLayout (0, // for item 0
  37991. 50, 100, // must be between 50 and 100 pixels in size
  37992. -0.6); // and its preferred size is 60% of the total available space
  37993. myLayout.setItemLayout (1, // for item 1
  37994. -0.2, -0.6, // size must be between 20% and 60% of the available space
  37995. 50); // and its preferred size is 50 pixels
  37996. }
  37997. void resized()
  37998. {
  37999. // make a list of two of our child components that we want to reposition
  38000. Component* comps[] = { myComp1, myComp2 };
  38001. // this will position the 2 components, one above the other, to fit
  38002. // vertically into the rectangle provided.
  38003. myLayout.layOutComponents (comps, 2,
  38004. 0, 0, getWidth(), getHeight(),
  38005. true);
  38006. }
  38007. };
  38008. @endcode
  38009. @see StretchableLayoutResizerBar
  38010. */
  38011. class JUCE_API StretchableLayoutManager
  38012. {
  38013. public:
  38014. /** Creates an empty layout.
  38015. You'll need to add some item properties to the layout before it can be used
  38016. to resize things - see setItemLayout().
  38017. */
  38018. StretchableLayoutManager();
  38019. /** Destructor. */
  38020. ~StretchableLayoutManager();
  38021. /** For a numbered item, this sets its size limits and preferred size.
  38022. @param itemIndex the index of the item to change.
  38023. @param minimumSize the minimum size that this item is allowed to be - a positive number
  38024. indicates an absolute size in pixels. A negative number indicates a
  38025. proportion of the available space (e.g -0.5 is 50%)
  38026. @param maximumSize the maximum size that this item is allowed to be - a positive number
  38027. indicates an absolute size in pixels. A negative number indicates a
  38028. proportion of the available space
  38029. @param preferredSize the size that this item would like to be, if there's enough room. A
  38030. positive number indicates an absolute size in pixels. A negative number
  38031. indicates a proportion of the available space
  38032. @see getItemLayout
  38033. */
  38034. void setItemLayout (const int itemIndex,
  38035. const double minimumSize,
  38036. const double maximumSize,
  38037. const double preferredSize);
  38038. /** For a numbered item, this returns its size limits and preferred size.
  38039. @param itemIndex the index of the item.
  38040. @param minimumSize the minimum size that this item is allowed to be - a positive number
  38041. indicates an absolute size in pixels. A negative number indicates a
  38042. proportion of the available space (e.g -0.5 is 50%)
  38043. @param maximumSize the maximum size that this item is allowed to be - a positive number
  38044. indicates an absolute size in pixels. A negative number indicates a
  38045. proportion of the available space
  38046. @param preferredSize the size that this item would like to be, if there's enough room. A
  38047. positive number indicates an absolute size in pixels. A negative number
  38048. indicates a proportion of the available space
  38049. @returns false if the item's properties hadn't been set
  38050. @see setItemLayout
  38051. */
  38052. bool getItemLayout (const int itemIndex,
  38053. double& minimumSize,
  38054. double& maximumSize,
  38055. double& preferredSize) const;
  38056. /** Clears all the properties that have been set with setItemLayout() and resets
  38057. this object to its initial state.
  38058. */
  38059. void clearAllItems();
  38060. /** Takes a set of components that correspond to the layout's items, and positions
  38061. them to fill a space.
  38062. This will try to give each item its preferred size, whether that's a relative size
  38063. or an absolute one.
  38064. @param components an array of components that correspond to each of the
  38065. numbered items that the StretchableLayoutManager object
  38066. has been told about with setItemLayout()
  38067. @param numComponents the number of components in the array that is passed-in. This
  38068. should be the same as the number of items this object has been
  38069. told about.
  38070. @param x the left of the rectangle in which the components should
  38071. be laid out
  38072. @param y the top of the rectangle in which the components should
  38073. be laid out
  38074. @param width the width of the rectangle in which the components should
  38075. be laid out
  38076. @param height the height of the rectangle in which the components should
  38077. be laid out
  38078. @param vertically if true, the components will be positioned in a vertical stack,
  38079. so that they fill the height of the rectangle. If false, they
  38080. will be placed side-by-side in a horizontal line, filling the
  38081. available width
  38082. @param resizeOtherDimension if true, this means that the components will have their
  38083. other dimension resized to fit the space - i.e. if the 'vertically'
  38084. parameter is true, their x-positions and widths are adjusted to fit
  38085. the x and width parameters; if 'vertically' is false, their y-positions
  38086. and heights are adjusted to fit the y and height parameters.
  38087. */
  38088. void layOutComponents (Component** const components,
  38089. int numComponents,
  38090. int x, int y, int width, int height,
  38091. const bool vertically,
  38092. const bool resizeOtherDimension);
  38093. /** Returns the current position of one of the items.
  38094. This is only a valid call after layOutComponents() has been called, as it
  38095. returns the last position that this item was placed at. If the layout was
  38096. vertical, the value returned will be the y position of the top of the item,
  38097. relative to the top of the rectangle in which the items were placed (so for
  38098. example, item 0 will always have position of 0, even in the rectangle passed
  38099. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  38100. the position returned is the item's left-hand position, again relative to the
  38101. x position of the rectangle used.
  38102. @see getItemCurrentSize, setItemPosition
  38103. */
  38104. int getItemCurrentPosition (const int itemIndex) const;
  38105. /** Returns the current size of one of the items.
  38106. This is only meaningful after layOutComponents() has been called, as it
  38107. returns the last size that this item was given. If the layout was done
  38108. vertically, it'll return the item's height in pixels; if it was horizontal,
  38109. it'll return its width.
  38110. @see getItemCurrentRelativeSize
  38111. */
  38112. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  38113. /** Returns the current size of one of the items.
  38114. This is only meaningful after layOutComponents() has been called, as it
  38115. returns the last size that this item was given. If the layout was done
  38116. vertically, it'll return a negative value representing the item's height relative
  38117. to the last size used for laying the components out; if the layout was done
  38118. horizontally it'll be the proportion of its width.
  38119. @see getItemCurrentAbsoluteSize
  38120. */
  38121. double getItemCurrentRelativeSize (const int itemIndex) const;
  38122. /** Moves one of the items, shifting along any other items as necessary in
  38123. order to get it to the desired position.
  38124. Calling this method will also update the preferred sizes of the items it
  38125. shuffles along, so that they reflect their new positions.
  38126. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  38127. about when it's dragged).
  38128. @param itemIndex the item to move
  38129. @param newPosition the absolute position that you'd like this item to move
  38130. to. The item might not be able to always reach exactly this position,
  38131. because other items may have minimum sizes that constrain how
  38132. far it can go
  38133. */
  38134. void setItemPosition (const int itemIndex,
  38135. int newPosition);
  38136. juce_UseDebuggingNewOperator
  38137. private:
  38138. struct ItemLayoutProperties
  38139. {
  38140. int itemIndex;
  38141. int currentSize;
  38142. double minSize, maxSize, preferredSize;
  38143. };
  38144. OwnedArray <ItemLayoutProperties> items;
  38145. int totalSize;
  38146. static int sizeToRealSize (double size, int totalSpace);
  38147. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  38148. void setTotalSize (const int newTotalSize);
  38149. int fitComponentsIntoSpace (const int startIndex,
  38150. const int endIndex,
  38151. const int availableSpace,
  38152. int startPos);
  38153. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  38154. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  38155. void updatePrefSizesToMatchCurrentPositions();
  38156. StretchableLayoutManager (const StretchableLayoutManager&);
  38157. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  38158. };
  38159. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  38160. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  38161. #endif
  38162. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  38163. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  38164. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  38165. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  38166. /**
  38167. A component that acts as one of the vertical or horizontal bars you see being
  38168. used to resize panels in a window.
  38169. One of these acts with a StretchableLayoutManager to resize the other components.
  38170. @see StretchableLayoutManager
  38171. */
  38172. class JUCE_API StretchableLayoutResizerBar : public Component
  38173. {
  38174. public:
  38175. /** Creates a resizer bar for use on a specified layout.
  38176. @param layoutToUse the layout that will be affected when this bar
  38177. is dragged
  38178. @param itemIndexInLayout the item index in the layout that corresponds to
  38179. this bar component. You'll need to set up the item
  38180. properties in a suitable way for a divider bar, e.g.
  38181. for an 8-pixel wide bar which, you could call
  38182. myLayout->setItemLayout (barIndex, 8, 8, 8)
  38183. @param isBarVertical true if it's an upright bar that you drag left and
  38184. right; false for a horizontal one that you drag up and
  38185. down
  38186. */
  38187. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  38188. const int itemIndexInLayout,
  38189. const bool isBarVertical);
  38190. /** Destructor. */
  38191. ~StretchableLayoutResizerBar();
  38192. /** This is called when the bar is dragged.
  38193. This method must update the positions of any components whose position is
  38194. determined by the StretchableLayoutManager, because they might have just
  38195. moved.
  38196. The default implementation calls the resized() method of this component's
  38197. parent component, because that's often where you're likely to apply the
  38198. layout, but it can be overridden for more specific needs.
  38199. */
  38200. virtual void hasBeenMoved();
  38201. /** @internal */
  38202. void paint (Graphics& g);
  38203. /** @internal */
  38204. void mouseDown (const MouseEvent& e);
  38205. /** @internal */
  38206. void mouseDrag (const MouseEvent& e);
  38207. juce_UseDebuggingNewOperator
  38208. private:
  38209. StretchableLayoutManager* layout;
  38210. int itemIndex, mouseDownPos;
  38211. bool isVertical;
  38212. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  38213. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  38214. };
  38215. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  38216. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  38217. #endif
  38218. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  38219. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  38220. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  38221. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  38222. /**
  38223. A utility class for fitting a set of objects whose sizes can vary between
  38224. a minimum and maximum size, into a space.
  38225. This is a trickier algorithm than it would first seem, so I've put it in this
  38226. class to allow it to be shared by various bits of code.
  38227. To use it, create one of these objects, call addItem() to add the list of items
  38228. you need, then call resizeToFit(), which will change all their sizes. You can
  38229. then retrieve the new sizes with getItemSize() and getNumItems().
  38230. It's currently used by the TableHeaderComponent for stretching out the table
  38231. headings to fill the table's width.
  38232. */
  38233. class StretchableObjectResizer
  38234. {
  38235. public:
  38236. /** Creates an empty object resizer. */
  38237. StretchableObjectResizer();
  38238. /** Destructor. */
  38239. ~StretchableObjectResizer();
  38240. /** Adds an item to the list.
  38241. The order parameter lets you specify groups of items that are resized first when some
  38242. space needs to be found. Those items with an order of 0 will be the first ones to be
  38243. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  38244. will then try resizing the items with an order of 1, then 2, and so on.
  38245. */
  38246. void addItem (const double currentSize,
  38247. const double minSize,
  38248. const double maxSize,
  38249. const int order = 0);
  38250. /** Resizes all the items to fit this amount of space.
  38251. This will attempt to fit them in without exceeding each item's miniumum and
  38252. maximum sizes. In cases where none of the items can be expanded or enlarged any
  38253. further, the final size may be greater or less than the size passed in.
  38254. After calling this method, you can retrieve the new sizes with the getItemSize()
  38255. method.
  38256. */
  38257. void resizeToFit (const double targetSize);
  38258. /** Returns the number of items that have been added. */
  38259. int getNumItems() const throw() { return items.size(); }
  38260. /** Returns the size of one of the items. */
  38261. double getItemSize (const int index) const throw();
  38262. juce_UseDebuggingNewOperator
  38263. private:
  38264. struct Item
  38265. {
  38266. double size;
  38267. double minSize;
  38268. double maxSize;
  38269. int order;
  38270. };
  38271. OwnedArray <Item> items;
  38272. StretchableObjectResizer (const StretchableObjectResizer&);
  38273. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  38274. };
  38275. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  38276. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  38277. #endif
  38278. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38279. #endif
  38280. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38281. #endif
  38282. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  38283. #endif
  38284. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38285. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  38286. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38287. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38288. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  38289. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38290. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38291. /********* Start of inlined file: juce_FileFilter.h *********/
  38292. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  38293. #define __JUCE_FILEFILTER_JUCEHEADER__
  38294. /**
  38295. Interface for deciding which files are suitable for something.
  38296. For example, this is used by DirectoryContentsList to select which files
  38297. go into the list.
  38298. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38299. */
  38300. class JUCE_API FileFilter
  38301. {
  38302. public:
  38303. /** Creates a filter with the given description.
  38304. The description can be returned later with the getDescription() method.
  38305. */
  38306. FileFilter (const String& filterDescription);
  38307. /** Destructor. */
  38308. virtual ~FileFilter();
  38309. /** Returns the description that the filter was created with. */
  38310. const String& getDescription() const throw();
  38311. /** Should return true if this file is suitable for inclusion in whatever context
  38312. the object is being used.
  38313. */
  38314. virtual bool isFileSuitable (const File& file) const = 0;
  38315. /** Should return true if this directory is suitable for inclusion in whatever context
  38316. the object is being used.
  38317. */
  38318. virtual bool isDirectorySuitable (const File& file) const = 0;
  38319. protected:
  38320. String description;
  38321. };
  38322. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  38323. /********* End of inlined file: juce_FileFilter.h *********/
  38324. /**
  38325. A class to asynchronously scan for details about the files in a directory.
  38326. This keeps a list of files and some information about them, using a background
  38327. thread to scan for more files. As files are found, it broadcasts change messages
  38328. to tell any listeners.
  38329. @see FileListComponent, FileBrowserComponent
  38330. */
  38331. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  38332. public TimeSliceClient
  38333. {
  38334. public:
  38335. /** Creates a directory list.
  38336. To set the directory it should point to, use setDirectory(), which will
  38337. also start it scanning for files on the background thread.
  38338. When the background thread finds and adds new files to this list, the
  38339. ChangeBroadcaster class will send a change message, so you can register
  38340. listeners and update them when the list changes.
  38341. @param fileFilter an optional filter to select which files are
  38342. included in the list. If this is 0, then all files
  38343. and directories are included. Make sure that the
  38344. filter doesn't get deleted during the lifetime of this
  38345. object
  38346. @param threadToUse a thread object that this list can use
  38347. to scan for files as a background task. Make sure
  38348. that the thread you give it has been started, or you
  38349. won't get any files!
  38350. */
  38351. DirectoryContentsList (const FileFilter* const fileFilter,
  38352. TimeSliceThread& threadToUse);
  38353. /** Destructor. */
  38354. ~DirectoryContentsList();
  38355. /** Sets the directory to look in for files.
  38356. If the directory that's passed in is different to the current one, this will
  38357. also start the background thread scanning it for files.
  38358. */
  38359. void setDirectory (const File& directory,
  38360. const bool includeDirectories,
  38361. const bool includeFiles);
  38362. /** Returns the directory that's currently being used. */
  38363. const File& getDirectory() const throw();
  38364. /** Clears the list, and stops the thread scanning for files. */
  38365. void clear();
  38366. /** Clears the list and restarts scanning the directory for files. */
  38367. void refresh();
  38368. /** True if the background thread hasn't yet finished scanning for files. */
  38369. bool isStillLoading() const;
  38370. /** Tells the list whether or not to ignore hidden files.
  38371. By default these are ignored.
  38372. */
  38373. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  38374. /** Returns true if hidden files are ignored.
  38375. @see setIgnoresHiddenFiles
  38376. */
  38377. bool ignoresHiddenFiles() const throw() { return ignoreHiddenFiles; }
  38378. /** Contains cached information about one of the files in a DirectoryContentsList.
  38379. */
  38380. struct FileInfo
  38381. {
  38382. /** The filename.
  38383. This isn't a full pathname, it's just the last part of the path, same as you'd
  38384. get from File::getFileName().
  38385. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  38386. */
  38387. String filename;
  38388. /** File size in bytes. */
  38389. int64 fileSize;
  38390. /** File modification time.
  38391. As supplied by File::getLastModificationTime().
  38392. */
  38393. Time modificationTime;
  38394. /** File creation time.
  38395. As supplied by File::getCreationTime().
  38396. */
  38397. Time creationTime;
  38398. /** True if the file is a directory. */
  38399. bool isDirectory;
  38400. /** True if the file is read-only. */
  38401. bool isReadOnly;
  38402. };
  38403. /** Returns the number of files currently available in the list.
  38404. The info about one of these files can be retrieved with getFileInfo() or
  38405. getFile().
  38406. Obviously as the background thread runs and scans the directory for files, this
  38407. number will change.
  38408. @see getFileInfo, getFile
  38409. */
  38410. int getNumFiles() const;
  38411. /** Returns the cached information about one of the files in the list.
  38412. If the index is in-range, this will return true and will copy the file's details
  38413. to the structure that is passed-in.
  38414. If it returns false, then the index wasn't in range, and the structure won't
  38415. be affected.
  38416. @see getNumFiles, getFile
  38417. */
  38418. bool getFileInfo (const int index,
  38419. FileInfo& resultInfo) const;
  38420. /** Returns one of the files in the list.
  38421. @param index should be less than getNumFiles(). If this is out-of-range, the
  38422. return value will be File::nonexistent
  38423. @see getNumFiles, getFileInfo
  38424. */
  38425. const File getFile (const int index) const;
  38426. /** Returns the file filter being used.
  38427. The filter is specified in the constructor.
  38428. */
  38429. const FileFilter* getFilter() const throw() { return fileFilter; }
  38430. /** @internal */
  38431. bool useTimeSlice();
  38432. /** @internal */
  38433. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  38434. /** @internal */
  38435. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  38436. const DirectoryContentsList::FileInfo* const second) throw();
  38437. juce_UseDebuggingNewOperator
  38438. private:
  38439. File root;
  38440. const FileFilter* fileFilter;
  38441. TimeSliceThread& thread;
  38442. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  38443. CriticalSection fileListLock;
  38444. OwnedArray <FileInfo> files;
  38445. void* volatile fileFindHandle;
  38446. bool volatile shouldStop;
  38447. void changed();
  38448. bool checkNextFile (bool& hasChanged);
  38449. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  38450. const int64 fileSize, const Time& modTime,
  38451. const Time& creationTime, const bool isReadOnly);
  38452. DirectoryContentsList (const DirectoryContentsList&);
  38453. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  38454. };
  38455. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38456. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  38457. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  38458. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38459. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38460. /**
  38461. A listener for user selection events in a file browser.
  38462. This is used by a FileBrowserComponent or FileListComponent.
  38463. */
  38464. class JUCE_API FileBrowserListener
  38465. {
  38466. public:
  38467. /** Destructor. */
  38468. virtual ~FileBrowserListener();
  38469. /** Callback when the user selects a different file in the browser. */
  38470. virtual void selectionChanged() = 0;
  38471. /** Callback when the user clicks on a file in the browser. */
  38472. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  38473. /** Callback when the user double-clicks on a file in the browser. */
  38474. virtual void fileDoubleClicked (const File& file) = 0;
  38475. };
  38476. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38477. /********* End of inlined file: juce_FileBrowserListener.h *********/
  38478. /**
  38479. A base class for components that display a list of the files in a directory.
  38480. @see DirectoryContentsList
  38481. */
  38482. class JUCE_API DirectoryContentsDisplayComponent
  38483. {
  38484. public:
  38485. /**
  38486. */
  38487. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  38488. /** Destructor. */
  38489. virtual ~DirectoryContentsDisplayComponent();
  38490. /** Returns the number of files the user has got selected.
  38491. @see getSelectedFile
  38492. */
  38493. virtual int getNumSelectedFiles() const = 0;
  38494. /** Returns one of the files that the user has currently selected.
  38495. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38496. @see getNumSelectedFiles
  38497. */
  38498. virtual const File getSelectedFile (int index) const = 0;
  38499. /** Scrolls this view to the top. */
  38500. virtual void scrollToTop() = 0;
  38501. /** Adds a listener to be told when files are selected or clicked.
  38502. @see removeListener
  38503. */
  38504. void addListener (FileBrowserListener* const listener) throw();
  38505. /** Removes a listener.
  38506. @see addListener
  38507. */
  38508. void removeListener (FileBrowserListener* const listener) throw();
  38509. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38510. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38511. methods.
  38512. Note that you can also use the constants from TextEditor::ColourIds to change the
  38513. colour of the text editor that is opened when a label is editable.
  38514. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38515. */
  38516. enum ColourIds
  38517. {
  38518. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  38519. textColourId = 0x1000541, /**< The colour for the text. */
  38520. };
  38521. /** @internal */
  38522. void sendSelectionChangeMessage();
  38523. /** @internal */
  38524. void sendDoubleClickMessage (const File& file);
  38525. /** @internal */
  38526. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  38527. juce_UseDebuggingNewOperator
  38528. protected:
  38529. DirectoryContentsList& fileList;
  38530. SortedSet <void*> listeners;
  38531. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  38532. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  38533. };
  38534. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38535. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  38536. #endif
  38537. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38538. #endif
  38539. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38540. #endif
  38541. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38542. /********* Start of inlined file: juce_FileListComponent.h *********/
  38543. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38544. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38545. /**
  38546. A component that displays the files in a directory as a listbox.
  38547. This implements the DirectoryContentsDisplayComponent base class so that
  38548. it can be used in a FileBrowserComponent.
  38549. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38550. class and the FileBrowserListener class.
  38551. @see DirectoryContentsList, FileTreeComponent
  38552. */
  38553. class JUCE_API FileListComponent : public ListBox,
  38554. public DirectoryContentsDisplayComponent,
  38555. private ListBoxModel,
  38556. private ChangeListener
  38557. {
  38558. public:
  38559. /** Creates a listbox to show the contents of a specified directory.
  38560. */
  38561. FileListComponent (DirectoryContentsList& listToShow);
  38562. /** Destructor. */
  38563. ~FileListComponent();
  38564. /** Returns the number of files the user has got selected.
  38565. @see getSelectedFile
  38566. */
  38567. int getNumSelectedFiles() const;
  38568. /** Returns one of the files that the user has currently selected.
  38569. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38570. @see getNumSelectedFiles
  38571. */
  38572. const File getSelectedFile (int index = 0) const;
  38573. /** Scrolls to the top of the list. */
  38574. void scrollToTop();
  38575. /** @internal */
  38576. void changeListenerCallback (void*);
  38577. /** @internal */
  38578. int getNumRows();
  38579. /** @internal */
  38580. void paintListBoxItem (int, Graphics&, int, int, bool);
  38581. /** @internal */
  38582. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  38583. /** @internal */
  38584. void selectedRowsChanged (int lastRowSelected);
  38585. /** @internal */
  38586. void deleteKeyPressed (int currentSelectedRow);
  38587. /** @internal */
  38588. void returnKeyPressed (int currentSelectedRow);
  38589. juce_UseDebuggingNewOperator
  38590. private:
  38591. FileListComponent (const FileListComponent&);
  38592. const FileListComponent& operator= (const FileListComponent&);
  38593. File lastDirectory;
  38594. };
  38595. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38596. /********* End of inlined file: juce_FileListComponent.h *********/
  38597. #endif
  38598. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  38599. #endif
  38600. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38601. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  38602. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38603. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38604. /**
  38605. A component that displays the files in a directory as a treeview.
  38606. This implements the DirectoryContentsDisplayComponent base class so that
  38607. it can be used in a FileBrowserComponent.
  38608. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38609. class and the FileBrowserListener class.
  38610. @see DirectoryContentsList, FileListComponent
  38611. */
  38612. class JUCE_API FileTreeComponent : public TreeView,
  38613. public DirectoryContentsDisplayComponent
  38614. {
  38615. public:
  38616. /** Creates a listbox to show the contents of a specified directory.
  38617. */
  38618. FileTreeComponent (DirectoryContentsList& listToShow);
  38619. /** Destructor. */
  38620. ~FileTreeComponent();
  38621. /** Returns the number of files the user has got selected.
  38622. @see getSelectedFile
  38623. */
  38624. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  38625. /** Returns one of the files that the user has currently selected.
  38626. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38627. @see getNumSelectedFiles
  38628. */
  38629. const File getSelectedFile (int index = 0) const;
  38630. /** Scrolls the list to the top. */
  38631. void scrollToTop();
  38632. /** Setting a name for this allows tree items to be dragged.
  38633. The string that you pass in here will be returned by the getDragSourceDescription()
  38634. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38635. */
  38636. void setDragAndDropDescription (const String& description) throw();
  38637. /** Returns the last value that was set by setDragAndDropDescription().
  38638. */
  38639. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38640. juce_UseDebuggingNewOperator
  38641. private:
  38642. String dragAndDropDescription;
  38643. FileTreeComponent (const FileTreeComponent&);
  38644. const FileTreeComponent& operator= (const FileTreeComponent&);
  38645. };
  38646. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38647. /********* End of inlined file: juce_FileTreeComponent.h *********/
  38648. #endif
  38649. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38650. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  38651. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38652. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38653. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  38654. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38655. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38656. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  38657. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38658. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38659. /**
  38660. Base class for components that live inside a file chooser dialog box and
  38661. show previews of the files that get selected.
  38662. One of these allows special extra information to be displayed for files
  38663. in a dialog box as the user selects them. Each time the current file or
  38664. directory is changed, the selectedFileChanged() method will be called
  38665. to allow it to update itself appropriately.
  38666. @see FileChooser, ImagePreviewComponent
  38667. */
  38668. class JUCE_API FilePreviewComponent : public Component
  38669. {
  38670. public:
  38671. /** Creates a FilePreviewComponent. */
  38672. FilePreviewComponent();
  38673. /** Destructor. */
  38674. ~FilePreviewComponent();
  38675. /** Called to indicate that the user's currently selected file has changed.
  38676. @param newSelectedFile the newly selected file or directory, which may be
  38677. File::nonexistent if none is selected.
  38678. */
  38679. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  38680. juce_UseDebuggingNewOperator
  38681. private:
  38682. FilePreviewComponent (const FilePreviewComponent&);
  38683. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  38684. };
  38685. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38686. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  38687. /**
  38688. A component for browsing and selecting a file or directory to open or save.
  38689. This contains a FileListComponent and adds various boxes and controls for
  38690. navigating and selecting a file. It can work in different modes so that it can
  38691. be used for loading or saving a file, or for choosing a directory.
  38692. @see FileChooserDialogBox, FileChooser, FileListComponent
  38693. */
  38694. class JUCE_API FileBrowserComponent : public Component,
  38695. public ChangeBroadcaster,
  38696. private FileBrowserListener,
  38697. private TextEditorListener,
  38698. private ButtonListener,
  38699. private ComboBoxListener,
  38700. private FileFilter
  38701. {
  38702. public:
  38703. /** Various options for the browser.
  38704. A combination of these is passed into the FileBrowserComponent constructor.
  38705. */
  38706. enum FileChooserFlags
  38707. {
  38708. openMode = 1, /**< specifies that the component should allow the user to
  38709. choose an existing file with the intention of opening it. */
  38710. saveMode = 2, /**< specifies that the component should allow the user to specify
  38711. the name of a file that will be used to save something. */
  38712. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  38713. conjunction with canSelectDirectories). */
  38714. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  38715. conjuction with canSelectFiles). */
  38716. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  38717. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  38718. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  38719. };
  38720. /** Creates a FileBrowserComponent.
  38721. @param flags A combination of flags from the FileChooserFlags enumeration,
  38722. used to specify the component's behaviour. The flags must contain
  38723. either openMode or saveMode, and canSelectFiles and/or
  38724. canSelectDirectories.
  38725. @param initialFileOrDirectory The file or directory that should be selected when
  38726. the component begins. If this is File::nonexistent,
  38727. a default directory will be chosen.
  38728. @param fileFilter an optional filter to use to determine which files
  38729. are shown. If this is 0 then all files are displayed. Note
  38730. that a pointer is kept internally to this object, so
  38731. make sure that it is not deleted before the browser object
  38732. is deleted.
  38733. @param previewComp an optional preview component that will be used to
  38734. show previews of files that the user selects
  38735. */
  38736. FileBrowserComponent (int flags,
  38737. const File& initialFileOrDirectory,
  38738. const FileFilter* fileFilter,
  38739. FilePreviewComponent* previewComp);
  38740. /** Destructor. */
  38741. ~FileBrowserComponent();
  38742. /** Returns the number of files that the user has got selected.
  38743. If multiple select isn't active, this will only be 0 or 1. To get the complete
  38744. list of files they've chosen, pass an index to getCurrentFile().
  38745. */
  38746. int getNumSelectedFiles() const throw();
  38747. /** Returns one of the files that the user has chosen.
  38748. If the box has multi-select enabled, the index lets you specify which of the files
  38749. to get - see getNumSelectedFiles() to find out how many files were chosen.
  38750. @see getHighlightedFile
  38751. */
  38752. const File getSelectedFile (int index) const throw();
  38753. /** Returns true if the currently selected file(s) are usable.
  38754. This can be used to decide whether the user can press "ok" for the
  38755. current file. What it does depends on the mode, so for example in an "open"
  38756. mode, this only returns true if a file has been selected and if it exists.
  38757. In a "save" mode, a non-existent file would also be valid.
  38758. */
  38759. bool currentFileIsValid() const;
  38760. /** This returns the last item in the view that the user has highlighted.
  38761. This may be different from getCurrentFile(), which returns the value
  38762. that is shown in the filename box, and if there are multiple selections,
  38763. this will only return one of them.
  38764. @see getCurrentFile
  38765. */
  38766. const File getHighlightedFile() const throw();
  38767. /** Returns the directory whose contents are currently being shown in the listbox. */
  38768. const File getRoot() const;
  38769. /** Changes the directory that's being shown in the listbox. */
  38770. void setRoot (const File& newRootDirectory);
  38771. /** Equivalent to pressing the "up" button to browse the parent directory. */
  38772. void goUp();
  38773. /** Refreshes the directory that's currently being listed. */
  38774. void refresh();
  38775. /** Returns a verb to describe what should happen when the file is accepted.
  38776. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  38777. mode, it'll be "Save", etc.
  38778. */
  38779. virtual const String getActionVerb() const;
  38780. /** Returns true if the saveMode flag was set when this component was created.
  38781. */
  38782. bool isSaveMode() const throw();
  38783. /** Adds a listener to be told when the user selects and clicks on files.
  38784. @see removeListener
  38785. */
  38786. void addListener (FileBrowserListener* const listener) throw();
  38787. /** Removes a listener.
  38788. @see addListener
  38789. */
  38790. void removeListener (FileBrowserListener* const listener) throw();
  38791. /** @internal */
  38792. void resized();
  38793. /** @internal */
  38794. void buttonClicked (Button* b);
  38795. /** @internal */
  38796. void comboBoxChanged (ComboBox*);
  38797. /** @internal */
  38798. void textEditorTextChanged (TextEditor& editor);
  38799. /** @internal */
  38800. void textEditorReturnKeyPressed (TextEditor& editor);
  38801. /** @internal */
  38802. void textEditorEscapeKeyPressed (TextEditor& editor);
  38803. /** @internal */
  38804. void textEditorFocusLost (TextEditor& editor);
  38805. /** @internal */
  38806. bool keyPressed (const KeyPress& key);
  38807. /** @internal */
  38808. void selectionChanged();
  38809. /** @internal */
  38810. void fileClicked (const File& f, const MouseEvent& e);
  38811. /** @internal */
  38812. void fileDoubleClicked (const File& f);
  38813. /** @internal */
  38814. bool isFileSuitable (const File& file) const;
  38815. /** @internal */
  38816. bool isDirectorySuitable (const File&) const;
  38817. /** @internal */
  38818. FilePreviewComponent* getPreviewComponent() const throw();
  38819. juce_UseDebuggingNewOperator
  38820. protected:
  38821. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  38822. private:
  38823. DirectoryContentsList* fileList;
  38824. const FileFilter* fileFilter;
  38825. int flags;
  38826. File currentRoot;
  38827. OwnedArray <File> chosenFiles;
  38828. SortedSet <void*> listeners;
  38829. DirectoryContentsDisplayComponent* fileListComponent;
  38830. FilePreviewComponent* previewComp;
  38831. ComboBox* currentPathBox;
  38832. TextEditor* filenameBox;
  38833. Button* goUpButton;
  38834. TimeSliceThread thread;
  38835. void sendListenerChangeMessage();
  38836. bool isFileOrDirSuitable (const File& f) const;
  38837. FileBrowserComponent (const FileBrowserComponent&);
  38838. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  38839. };
  38840. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38841. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  38842. /**
  38843. A file open/save dialog box.
  38844. This is a Juce-based file dialog box; to use a native file chooser, see the
  38845. FileChooser class.
  38846. To use one of these, create it and call its show() method. e.g.
  38847. @code
  38848. {
  38849. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  38850. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  38851. File::nonexistent,
  38852. &wildcardFilter,
  38853. 0);
  38854. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  38855. T("Please choose some kind of file that you want to open..."),
  38856. browser,
  38857. getLookAndFeel().alertWindowBackground);
  38858. if (dialogBox.show())
  38859. {
  38860. File selectedFile = browser.getCurrentFile();
  38861. ...
  38862. }
  38863. }
  38864. @endcode
  38865. @see FileChooser
  38866. */
  38867. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  38868. public ButtonListener,
  38869. public FileBrowserListener
  38870. {
  38871. public:
  38872. /** Creates a file chooser box.
  38873. @param title the main title to show at the top of the box
  38874. @param instructions an optional longer piece of text to show below the title in
  38875. a smaller font, describing in more detail what's required.
  38876. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  38877. box. Make sure you delete this after (but not before!) the
  38878. dialog box has been deleted.
  38879. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  38880. if they try to select a file that already exists. (This
  38881. flag is only used when saving files)
  38882. @param backgroundColour the background colour for the top level window
  38883. @see FileBrowserComponent, FilePreviewComponent
  38884. */
  38885. FileChooserDialogBox (const String& title,
  38886. const String& instructions,
  38887. FileBrowserComponent& browserComponent,
  38888. const bool warnAboutOverwritingExistingFiles,
  38889. const Colour& backgroundColour);
  38890. /** Destructor. */
  38891. ~FileChooserDialogBox();
  38892. /** Displays and runs the dialog box modally.
  38893. This will show the box with the specified size, returning true if the user
  38894. pressed 'ok', or false if they cancelled.
  38895. Leave the width or height as 0 to use the default size
  38896. */
  38897. bool show (int width = 0,int height = 0);
  38898. /** @internal */
  38899. void buttonClicked (Button* button);
  38900. /** @internal */
  38901. void closeButtonPressed();
  38902. /** @internal */
  38903. void selectionChanged();
  38904. /** @internal */
  38905. void fileClicked (const File& file, const MouseEvent& e);
  38906. /** @internal */
  38907. void fileDoubleClicked (const File& file);
  38908. juce_UseDebuggingNewOperator
  38909. private:
  38910. class ContentComponent : public Component
  38911. {
  38912. public:
  38913. ContentComponent();
  38914. ~ContentComponent();
  38915. void paint (Graphics& g);
  38916. void resized();
  38917. String instructions;
  38918. GlyphArrangement text;
  38919. FileBrowserComponent* chooserComponent;
  38920. FilePreviewComponent* previewComponent;
  38921. TextButton* okButton;
  38922. TextButton* cancelButton;
  38923. };
  38924. ContentComponent* content;
  38925. const bool warnAboutOverwritingExistingFiles;
  38926. FileChooserDialogBox (const FileChooserDialogBox&);
  38927. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  38928. };
  38929. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  38930. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  38931. #endif
  38932. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38933. #endif
  38934. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38935. /********* Start of inlined file: juce_FilenameComponent.h *********/
  38936. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38937. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38938. class FilenameComponent;
  38939. /**
  38940. Listens for events happening to a FilenameComponent.
  38941. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  38942. register one of these objects for event callbacks when the filename is changed.
  38943. @see FilenameComponent
  38944. */
  38945. class JUCE_API FilenameComponentListener
  38946. {
  38947. public:
  38948. /** Destructor. */
  38949. virtual ~FilenameComponentListener() {}
  38950. /** This method is called after the FilenameComponent's file has been changed. */
  38951. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  38952. };
  38953. /**
  38954. Shows a filename as an editable text box, with a 'browse' button and a
  38955. drop-down list for recently selected files.
  38956. A handy component for dialogue boxes where you want the user to be able to
  38957. select a file or directory.
  38958. Attach an FilenameComponentListener using the addListener() method, and it will
  38959. get called each time the user changes the filename, either by browsing for a file
  38960. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38961. @see FileChooser, ComboBox
  38962. */
  38963. class JUCE_API FilenameComponent : public Component,
  38964. public SettableTooltipClient,
  38965. public FileDragAndDropTarget,
  38966. private AsyncUpdater,
  38967. private ButtonListener,
  38968. private ComboBoxListener
  38969. {
  38970. public:
  38971. /** Creates a FilenameComponent.
  38972. @param name the name for this component.
  38973. @param currentFile the file to initially show in the box
  38974. @param canEditFilename if true, the user can manually edit the filename; if false,
  38975. they can only change it by browsing for a new file
  38976. @param isDirectory if true, the file will be treated as a directory, and
  38977. an appropriate directory browser used
  38978. @param isForSaving if true, the file browser will allow non-existent files to
  38979. be picked, as the file is assumed to be used for saving rather
  38980. than loading
  38981. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38982. If an empty string is passed in, then the pattern is assumed to be "*"
  38983. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38984. to any filenames that are entered or chosen
  38985. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38986. will only appear if the initial file isn't valid)
  38987. */
  38988. FilenameComponent (const String& name,
  38989. const File& currentFile,
  38990. const bool canEditFilename,
  38991. const bool isDirectory,
  38992. const bool isForSaving,
  38993. const String& fileBrowserWildcard,
  38994. const String& enforcedSuffix,
  38995. const String& textWhenNothingSelected);
  38996. /** Destructor. */
  38997. ~FilenameComponent();
  38998. /** Returns the currently displayed filename. */
  38999. const File getCurrentFile() const;
  39000. /** Changes the current filename.
  39001. If addToRecentlyUsedList is true, the filename will also be added to the
  39002. drop-down list of recent files.
  39003. If sendChangeNotification is false, then the listeners won't be told of the
  39004. change.
  39005. */
  39006. void setCurrentFile (File newFile,
  39007. const bool addToRecentlyUsedList,
  39008. const bool sendChangeNotification = true);
  39009. /** Changes whether the use can type into the filename box.
  39010. */
  39011. void setFilenameIsEditable (const bool shouldBeEditable);
  39012. /** Sets a file or directory to be the default starting point for the browser to show.
  39013. This is only used if the current file hasn't been set.
  39014. */
  39015. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  39016. /** Returns all the entries on the recent files list.
  39017. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  39018. state of this list.
  39019. @see setRecentlyUsedFilenames
  39020. */
  39021. const StringArray getRecentlyUsedFilenames() const;
  39022. /** Sets all the entries on the recent files list.
  39023. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  39024. state of this list.
  39025. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  39026. */
  39027. void setRecentlyUsedFilenames (const StringArray& filenames);
  39028. /** Adds an entry to the recently-used files dropdown list.
  39029. If the file is already in the list, it will be moved to the top. A limit
  39030. is also placed on the number of items that are kept in the list.
  39031. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  39032. */
  39033. void addRecentlyUsedFile (const File& file);
  39034. /** Changes the limit for the number of files that will be stored in the recent-file list.
  39035. */
  39036. void setMaxNumberOfRecentFiles (const int newMaximum);
  39037. /** Changes the text shown on the 'browse' button.
  39038. By default this button just says "..." but you can change it. The button itself
  39039. can be changed using the look-and-feel classes, so it might not actually have any
  39040. text on it.
  39041. */
  39042. void setBrowseButtonText (const String& browseButtonText);
  39043. /** Adds a listener that will be called when the selected file is changed. */
  39044. void addListener (FilenameComponentListener* const listener) throw();
  39045. /** Removes a previously-registered listener. */
  39046. void removeListener (FilenameComponentListener* const listener) throw();
  39047. /** Gives the component a tooltip. */
  39048. void setTooltip (const String& newTooltip);
  39049. /** @internal */
  39050. void paintOverChildren (Graphics& g);
  39051. /** @internal */
  39052. void resized();
  39053. /** @internal */
  39054. void lookAndFeelChanged();
  39055. /** @internal */
  39056. bool isInterestedInFileDrag (const StringArray& files);
  39057. /** @internal */
  39058. void filesDropped (const StringArray& files, int, int);
  39059. /** @internal */
  39060. void fileDragEnter (const StringArray& files, int, int);
  39061. /** @internal */
  39062. void fileDragExit (const StringArray& files);
  39063. juce_UseDebuggingNewOperator
  39064. private:
  39065. ComboBox* filenameBox;
  39066. String lastFilename;
  39067. Button* browseButton;
  39068. int maxRecentFiles;
  39069. bool isDir, isSaving, isFileDragOver;
  39070. String wildcard, enforcedSuffix, browseButtonText;
  39071. SortedSet <void*> listeners;
  39072. File defaultBrowseFile;
  39073. void comboBoxChanged (ComboBox*);
  39074. void buttonClicked (Button* button);
  39075. void handleAsyncUpdate();
  39076. FilenameComponent (const FilenameComponent&);
  39077. const FilenameComponent& operator= (const FilenameComponent&);
  39078. };
  39079. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  39080. /********* End of inlined file: juce_FilenameComponent.h *********/
  39081. #endif
  39082. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  39083. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  39084. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  39085. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  39086. /**
  39087. Shows a set of file paths in a list, allowing them to be added, removed or
  39088. re-ordered.
  39089. @see FileSearchPath
  39090. */
  39091. class JUCE_API FileSearchPathListComponent : public Component,
  39092. public SettableTooltipClient,
  39093. public FileDragAndDropTarget,
  39094. private ButtonListener,
  39095. private ListBoxModel
  39096. {
  39097. public:
  39098. /** Creates an empty FileSearchPathListComponent.
  39099. */
  39100. FileSearchPathListComponent();
  39101. /** Destructor. */
  39102. ~FileSearchPathListComponent();
  39103. /** Returns the path as it is currently shown. */
  39104. const FileSearchPath& getPath() const throw() { return path; }
  39105. /** Changes the current path. */
  39106. void setPath (const FileSearchPath& newPath);
  39107. /** Sets a file or directory to be the default starting point for the browser to show.
  39108. This is only used if the current file hasn't been set.
  39109. */
  39110. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  39111. /** A set of colour IDs to use to change the colour of various aspects of the label.
  39112. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39113. methods.
  39114. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39115. */
  39116. enum ColourIds
  39117. {
  39118. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  39119. Make this transparent if you don't want the background to be filled. */
  39120. };
  39121. /** @internal */
  39122. int getNumRows();
  39123. /** @internal */
  39124. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  39125. /** @internal */
  39126. void deleteKeyPressed (int lastRowSelected);
  39127. /** @internal */
  39128. void returnKeyPressed (int lastRowSelected);
  39129. /** @internal */
  39130. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  39131. /** @internal */
  39132. void selectedRowsChanged (int lastRowSelected);
  39133. /** @internal */
  39134. void resized();
  39135. /** @internal */
  39136. void paint (Graphics& g);
  39137. /** @internal */
  39138. bool isInterestedInFileDrag (const StringArray& files);
  39139. /** @internal */
  39140. void filesDropped (const StringArray& files, int, int);
  39141. /** @internal */
  39142. void buttonClicked (Button* button);
  39143. juce_UseDebuggingNewOperator
  39144. private:
  39145. FileSearchPath path;
  39146. File defaultBrowseTarget;
  39147. ListBox* listBox;
  39148. Button* addButton;
  39149. Button* removeButton;
  39150. Button* changeButton;
  39151. Button* upButton;
  39152. Button* downButton;
  39153. void changed() throw();
  39154. void updateButtons() throw();
  39155. FileSearchPathListComponent (const FileSearchPathListComponent&);
  39156. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  39157. };
  39158. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  39159. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  39160. #endif
  39161. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  39162. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  39163. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  39164. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  39165. /**
  39166. A type of FileFilter that works by wildcard pattern matching.
  39167. This filter only allows files that match one of the specified patterns, but
  39168. allows all directories through.
  39169. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  39170. */
  39171. class JUCE_API WildcardFileFilter : public FileFilter
  39172. {
  39173. public:
  39174. /**
  39175. Creates a wildcard filter for one or more patterns.
  39176. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  39177. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  39178. or .aiff.
  39179. The description is a name to show the user in a list of possible patterns, so
  39180. for the wav/aiff example, your description might be "audio files".
  39181. */
  39182. WildcardFileFilter (const String& fileWildcardPatterns,
  39183. const String& directoryWildcardPatterns,
  39184. const String& description);
  39185. /** Destructor. */
  39186. ~WildcardFileFilter();
  39187. /** Returns true if the filename matches one of the patterns specified. */
  39188. bool isFileSuitable (const File& file) const;
  39189. /** This always returns true. */
  39190. bool isDirectorySuitable (const File& file) const;
  39191. juce_UseDebuggingNewOperator
  39192. private:
  39193. StringArray fileWildcards, directoryWildcards;
  39194. static void parse (const String& pattern, StringArray& result) throw();
  39195. static bool match (const File& file, const StringArray& wildcards) throw();
  39196. };
  39197. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  39198. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  39199. #endif
  39200. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  39201. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  39202. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  39203. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  39204. /**
  39205. A simple preview component that shows thumbnails of image files.
  39206. @see FileChooserDialogBox, FilePreviewComponent
  39207. */
  39208. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  39209. private Timer
  39210. {
  39211. public:
  39212. /** Creates an ImagePreviewComponent. */
  39213. ImagePreviewComponent();
  39214. /** Destructor. */
  39215. ~ImagePreviewComponent();
  39216. /** @internal */
  39217. void selectedFileChanged (const File& newSelectedFile);
  39218. /** @internal */
  39219. void paint (Graphics& g);
  39220. /** @internal */
  39221. void timerCallback();
  39222. juce_UseDebuggingNewOperator
  39223. private:
  39224. File fileToLoad;
  39225. Image* currentThumbnail;
  39226. String currentDetails;
  39227. void getThumbSize (int& w, int& h) const;
  39228. ImagePreviewComponent (const ImagePreviewComponent&);
  39229. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  39230. };
  39231. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  39232. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  39233. #endif
  39234. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  39235. #endif
  39236. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  39237. /********* Start of inlined file: juce_FileChooser.h *********/
  39238. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  39239. #define __JUCE_FILECHOOSER_JUCEHEADER__
  39240. /**
  39241. Creates a dialog box to choose a file or directory to load or save.
  39242. To use a FileChooser:
  39243. - create one (as a local stack variable is the neatest way)
  39244. - call one of its browseFor.. methods
  39245. - if this returns true, the user has selected a file, so you can retrieve it
  39246. with the getResult() method.
  39247. e.g. @code
  39248. void loadMooseFile()
  39249. {
  39250. FileChooser myChooser ("Please select the moose you want to load...",
  39251. File::getSpecialLocation (File::userHomeDirectory),
  39252. "*.moose");
  39253. if (myChooser.browseForFileToOpen())
  39254. {
  39255. File mooseFile (myChooser.getResult());
  39256. loadMoose (mooseFile);
  39257. }
  39258. }
  39259. @endcode
  39260. */
  39261. class JUCE_API FileChooser
  39262. {
  39263. public:
  39264. /** Creates a FileChooser.
  39265. After creating one of these, use one of the browseFor... methods to display it.
  39266. @param dialogBoxTitle a text string to display in the dialog box to
  39267. tell the user what's going on
  39268. @param initialFileOrDirectory the file or directory that should be selected when
  39269. the dialog box opens. If this parameter is set to
  39270. File::nonexistent, a sensible default directory
  39271. will be used instead.
  39272. @param filePatternsAllowed a set of file patterns to specify which files can be
  39273. selected - each pattern should be separated by a
  39274. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  39275. empty string means that all files are allowed
  39276. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  39277. possible; if false, then a Juce-based browser dialog
  39278. box will always be used
  39279. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  39280. */
  39281. FileChooser (const String& dialogBoxTitle,
  39282. const File& initialFileOrDirectory = File::nonexistent,
  39283. const String& filePatternsAllowed = String::empty,
  39284. const bool useOSNativeDialogBox = true);
  39285. /** Destructor. */
  39286. ~FileChooser();
  39287. /** Shows a dialog box to choose a file to open.
  39288. This will display the dialog box modally, using an "open file" mode, so that
  39289. it won't allow non-existent files or directories to be chosen.
  39290. @param previewComponent an optional component to display inside the dialog
  39291. box to show special info about the files that the user
  39292. is browsing. The component will not be deleted by this
  39293. object, so the caller must take care of it.
  39294. @returns true if the user selected a file, in which case, use the getResult()
  39295. method to find out what it was. Returns false if they cancelled instead.
  39296. @see browseForFileToSave, browseForDirectory
  39297. */
  39298. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  39299. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  39300. The files that are returned can be obtained by calling getResults(). See
  39301. browseForFileToOpen() for more info about the behaviour of this method.
  39302. */
  39303. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  39304. /** Shows a dialog box to choose a file to save.
  39305. This will display the dialog box modally, using an "save file" mode, so it
  39306. will allow non-existent files to be chosen, but not directories.
  39307. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  39308. the user if they're sure they want to overwrite a file that already
  39309. exists
  39310. @returns true if the user chose a file and pressed 'ok', in which case, use
  39311. the getResult() method to find out what the file was. Returns false
  39312. if they cancelled instead.
  39313. @see browseForFileToOpen, browseForDirectory
  39314. */
  39315. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  39316. /** Shows a dialog box to choose a directory.
  39317. This will display the dialog box modally, using an "open directory" mode, so it
  39318. will only allow directories to be returned, not files.
  39319. @returns true if the user chose a directory and pressed 'ok', in which case, use
  39320. the getResult() method to find out what they chose. Returns false
  39321. if they cancelled instead.
  39322. @see browseForFileToOpen, browseForFileToSave
  39323. */
  39324. bool browseForDirectory();
  39325. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  39326. The files that are returned can be obtained by calling getResults(). See
  39327. browseForFileToOpen() for more info about the behaviour of this method.
  39328. */
  39329. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  39330. /** Returns the last file that was chosen by one of the browseFor methods.
  39331. After calling the appropriate browseFor... method, this method lets you
  39332. find out what file or directory they chose.
  39333. Note that the file returned is only valid if the browse method returned true (i.e.
  39334. if the user pressed 'ok' rather than cancelling).
  39335. If you're using a multiple-file select, then use the getResults() method instead,
  39336. to obtain the list of all files chosen.
  39337. @see getResults
  39338. */
  39339. const File getResult() const;
  39340. /** Returns a list of all the files that were chosen during the last call to a
  39341. browse method.
  39342. This array may be empty if no files were chosen, or can contain multiple entries
  39343. if multiple files were chosen.
  39344. @see getResult
  39345. */
  39346. const OwnedArray <File>& getResults() const;
  39347. juce_UseDebuggingNewOperator
  39348. private:
  39349. String title, filters;
  39350. File startingFile;
  39351. OwnedArray <File> results;
  39352. bool useNativeDialogBox;
  39353. bool showDialog (const bool selectsDirectories,
  39354. const bool selectsFiles,
  39355. const bool isSave,
  39356. const bool warnAboutOverwritingExistingFiles,
  39357. const bool selectMultipleFiles,
  39358. FilePreviewComponent* const previewComponent);
  39359. static void showPlatformDialog (OwnedArray<File>& results,
  39360. const String& title,
  39361. const File& file,
  39362. const String& filters,
  39363. bool selectsDirectories,
  39364. bool selectsFiles,
  39365. bool isSave,
  39366. bool warnAboutOverwritingExistingFiles,
  39367. bool selectMultipleFiles,
  39368. FilePreviewComponent* previewComponent);
  39369. };
  39370. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  39371. /********* End of inlined file: juce_FileChooser.h *********/
  39372. #endif
  39373. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  39374. /********* Start of inlined file: juce_AlertWindow.h *********/
  39375. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  39376. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  39377. /** A window that displays a message and has buttons for the user to react to it.
  39378. For simple dialog boxes with just a couple of buttons on them, there are
  39379. some static methods for running these.
  39380. For more complex dialogs, an AlertWindow can be created, then it can have some
  39381. buttons and components added to it, and its runModalLoop() method is then used to
  39382. show it. The value returned by runModalLoop() shows which button the
  39383. user pressed to dismiss the box.
  39384. @see ThreadWithProgressWindow
  39385. */
  39386. class JUCE_API AlertWindow : public TopLevelWindow,
  39387. private ButtonListener
  39388. {
  39389. public:
  39390. /** The type of icon to show in the dialog box. */
  39391. enum AlertIconType
  39392. {
  39393. NoIcon, /**< No icon will be shown on the dialog box. */
  39394. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  39395. user to answer a question. */
  39396. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  39397. warning about something and shouldn't be ignored. */
  39398. InfoIcon /**< An icon that indicates that the dialog box is just
  39399. giving the user some information, which doesn't require
  39400. a response from them. */
  39401. };
  39402. /** Creates an AlertWindow.
  39403. @param title the headline to show at the top of the dialog box
  39404. @param message a longer, more descriptive message to show underneath the
  39405. headline
  39406. @param iconType the type of icon to display
  39407. @param associatedComponent if this is non-zero, it specifies the component that the
  39408. alert window should be associated with. Depending on the look
  39409. and feel, this might be used for positioning of the alert window.
  39410. */
  39411. AlertWindow (const String& title,
  39412. const String& message,
  39413. AlertIconType iconType,
  39414. Component* associatedComponent = 0);
  39415. /** Destroys the AlertWindow */
  39416. ~AlertWindow();
  39417. /** Returns the type of alert icon that was specified when the window
  39418. was created. */
  39419. AlertIconType getAlertType() const throw() { return alertIconType; }
  39420. /** Changes the dialog box's message.
  39421. This will also resize the window to fit the new message if required.
  39422. */
  39423. void setMessage (const String& message);
  39424. /** Adds a button to the window.
  39425. @param name the text to show on the button
  39426. @param returnValue the value that should be returned from runModalLoop()
  39427. if this is the button that the user presses.
  39428. @param shortcutKey1 an optional key that can be pressed to trigger this button
  39429. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  39430. */
  39431. void addButton (const String& name,
  39432. const int returnValue,
  39433. const KeyPress& shortcutKey1 = KeyPress(),
  39434. const KeyPress& shortcutKey2 = KeyPress());
  39435. /** Returns the number of buttons that the window currently has. */
  39436. int getNumButtons() const;
  39437. /** Adds a textbox to the window for entering strings.
  39438. @param name an internal name for the text-box. This is the name to pass to
  39439. the getTextEditorContents() method to find out what the
  39440. user typed-in.
  39441. @param initialContents a string to show in the text box when it's first shown
  39442. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39443. text-box to label it.
  39444. @param isPasswordBox if true, the text editor will display asterisks instead of
  39445. the actual text
  39446. @see getTextEditorContents
  39447. */
  39448. void addTextEditor (const String& name,
  39449. const String& initialContents,
  39450. const String& onScreenLabel = String::empty,
  39451. const bool isPasswordBox = false);
  39452. /** Returns the contents of a named textbox.
  39453. After showing an AlertWindow that contains a text editor, this can be
  39454. used to find out what the user has typed into it.
  39455. @param nameOfTextEditor the name of the text box that you're interested in
  39456. @see addTextEditor
  39457. */
  39458. const String getTextEditorContents (const String& nameOfTextEditor) const;
  39459. /** Adds a drop-down list of choices to the box.
  39460. After the box has been shown, the getComboBoxComponent() method can
  39461. be used to find out which item the user picked.
  39462. @param name the label to use for the drop-down list
  39463. @param items the list of items to show in it
  39464. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39465. combo-box to label it.
  39466. @see getComboBoxComponent
  39467. */
  39468. void addComboBox (const String& name,
  39469. const StringArray& items,
  39470. const String& onScreenLabel = String::empty);
  39471. /** Returns a drop-down list that was added to the AlertWindow.
  39472. @param nameOfList the name that was passed into the addComboBox() method
  39473. when creating the drop-down
  39474. @returns the ComboBox component, or 0 if none was found for the given name.
  39475. */
  39476. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  39477. /** Adds a block of text.
  39478. This is handy for adding a multi-line note next to a textbox or combo-box,
  39479. to provide more details about what's going on.
  39480. */
  39481. void addTextBlock (const String& text);
  39482. /** Adds a progress-bar to the window.
  39483. @param progressValue a variable that will be repeatedly checked while the
  39484. dialog box is visible, to see how far the process has
  39485. got. The value should be in the range 0 to 1.0
  39486. */
  39487. void addProgressBarComponent (double& progressValue);
  39488. /** Adds a user-defined component to the dialog box.
  39489. @param component the component to add - its size should be set up correctly
  39490. before it is passed in. The caller is responsible for deleting
  39491. the component later on - the AlertWindow won't delete it.
  39492. */
  39493. void addCustomComponent (Component* const component);
  39494. /** Returns the number of custom components in the dialog box.
  39495. @see getCustomComponent, addCustomComponent
  39496. */
  39497. int getNumCustomComponents() const;
  39498. /** Returns one of the custom components in the dialog box.
  39499. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39500. will return 0
  39501. @see getNumCustomComponents, addCustomComponent
  39502. */
  39503. Component* getCustomComponent (const int index) const;
  39504. /** Removes one of the custom components in the dialog box.
  39505. Note that this won't delete it, it just removes the component from the window
  39506. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39507. will return 0
  39508. @returns the component that was removed (or zero)
  39509. @see getNumCustomComponents, addCustomComponent
  39510. */
  39511. Component* removeCustomComponent (const int index);
  39512. /** Returns true if the window contains any components other than just buttons.*/
  39513. bool containsAnyExtraComponents() const;
  39514. // easy-to-use message box functions:
  39515. /** Shows a dialog box that just has a message and a single button to get rid of it.
  39516. The box is shown modally, and the method returns after the user
  39517. has clicked the button (or pressed the escape or return keys).
  39518. @param iconType the type of icon to show
  39519. @param title the headline to show at the top of the box
  39520. @param message a longer, more descriptive message to show underneath the
  39521. headline
  39522. @param buttonText the text to show in the button - if this string is empty, the
  39523. default string "ok" (or a localised version) will be used.
  39524. @param associatedComponent if this is non-zero, it specifies the component that the
  39525. alert window should be associated with. Depending on the look
  39526. and feel, this might be used for positioning of the alert window.
  39527. */
  39528. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  39529. const String& title,
  39530. const String& message,
  39531. const String& buttonText = String::empty,
  39532. Component* associatedComponent = 0);
  39533. /** Shows a dialog box with two buttons.
  39534. Ideal for ok/cancel or yes/no choices. The return key can also be used
  39535. to trigger the first button, and the escape key for the second button.
  39536. @param iconType the type of icon to show
  39537. @param title the headline to show at the top of the box
  39538. @param message a longer, more descriptive message to show underneath the
  39539. headline
  39540. @param button1Text the text to show in the first button - if this string is
  39541. empty, the default string "ok" (or a localised version of it)
  39542. will be used.
  39543. @param button2Text the text to show in the second button - if this string is
  39544. empty, the default string "cancel" (or a localised version of it)
  39545. will be used.
  39546. @param associatedComponent if this is non-zero, it specifies the component that the
  39547. alert window should be associated with. Depending on the look
  39548. and feel, this might be used for positioning of the alert window.
  39549. @returns true if button 1 was clicked, false if it was button 2
  39550. */
  39551. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  39552. const String& title,
  39553. const String& message,
  39554. const String& button1Text = String::empty,
  39555. const String& button2Text = String::empty,
  39556. Component* associatedComponent = 0);
  39557. /** Shows a dialog box with three buttons.
  39558. Ideal for yes/no/cancel boxes.
  39559. The escape key can be used to trigger the third button.
  39560. @param iconType the type of icon to show
  39561. @param title the headline to show at the top of the box
  39562. @param message a longer, more descriptive message to show underneath the
  39563. headline
  39564. @param button1Text the text to show in the first button - if an empty string, then
  39565. "yes" will be used (or a localised version of it)
  39566. @param button2Text the text to show in the first button - if an empty string, then
  39567. "no" will be used (or a localised version of it)
  39568. @param button3Text the text to show in the first button - if an empty string, then
  39569. "cancel" will be used (or a localised version of it)
  39570. @param associatedComponent if this is non-zero, it specifies the component that the
  39571. alert window should be associated with. Depending on the look
  39572. and feel, this might be used for positioning of the alert window.
  39573. @returns one of the following values:
  39574. - 0 if the third button was pressed (normally used for 'cancel')
  39575. - 1 if the first button was pressed (normally used for 'yes')
  39576. - 2 if the middle button was pressed (normally used for 'no')
  39577. */
  39578. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  39579. const String& title,
  39580. const String& message,
  39581. const String& button1Text = String::empty,
  39582. const String& button2Text = String::empty,
  39583. const String& button3Text = String::empty,
  39584. Component* associatedComponent = 0);
  39585. /** Shows an operating-system native dialog box.
  39586. @param title the title to use at the top
  39587. @param bodyText the longer message to show
  39588. @param isOkCancel if true, this will show an ok/cancel box, if false,
  39589. it'll show a box with just an ok button
  39590. @returns true if the ok button was pressed, false if they pressed cancel.
  39591. */
  39592. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  39593. const String& bodyText,
  39594. bool isOkCancel);
  39595. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  39596. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39597. methods.
  39598. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39599. */
  39600. enum ColourIds
  39601. {
  39602. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  39603. textColourId = 0x1001810, /**< The colour for the text. */
  39604. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  39605. };
  39606. juce_UseDebuggingNewOperator
  39607. protected:
  39608. /** @internal */
  39609. void paint (Graphics& g);
  39610. /** @internal */
  39611. void mouseDown (const MouseEvent& e);
  39612. /** @internal */
  39613. void mouseDrag (const MouseEvent& e);
  39614. /** @internal */
  39615. bool keyPressed (const KeyPress& key);
  39616. /** @internal */
  39617. void buttonClicked (Button* button);
  39618. /** @internal */
  39619. void lookAndFeelChanged();
  39620. /** @internal */
  39621. void userTriedToCloseWindow();
  39622. /** @internal */
  39623. int getDesktopWindowStyleFlags() const;
  39624. private:
  39625. String text;
  39626. TextLayout textLayout;
  39627. AlertIconType alertIconType;
  39628. ComponentBoundsConstrainer constrainer;
  39629. ComponentDragger dragger;
  39630. Rectangle textArea;
  39631. VoidArray buttons, textBoxes, comboBoxes;
  39632. VoidArray progressBars, customComps, textBlocks, allComps;
  39633. StringArray textboxNames, comboBoxNames;
  39634. Font font;
  39635. Component* associatedComponent;
  39636. void updateLayout (const bool onlyIncreaseSize);
  39637. // disable copy constructor
  39638. AlertWindow (const AlertWindow&);
  39639. const AlertWindow& operator= (const AlertWindow&);
  39640. };
  39641. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  39642. /********* End of inlined file: juce_AlertWindow.h *********/
  39643. #endif
  39644. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  39645. /********* Start of inlined file: juce_DialogWindow.h *********/
  39646. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  39647. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  39648. /**
  39649. A dialog-box style window.
  39650. This class is a convenient way of creating a DocumentWindow with a close button
  39651. that can be triggered by pressing the escape key.
  39652. Any of the methods available to a DocumentWindow or ResizableWindow are also
  39653. available to this, so it can be made resizable, have a menu bar, etc.
  39654. To add items to the box, see the ResizableWindow::setContentComponent() method.
  39655. Don't add components directly to this class - always put them in a content component!
  39656. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  39657. the user clicking the close button - for more info, see the DocumentWindow
  39658. help.
  39659. @see DocumentWindow, ResizableWindow
  39660. */
  39661. class JUCE_API DialogWindow : public DocumentWindow
  39662. {
  39663. public:
  39664. /** Creates a DialogWindow.
  39665. @param name the name to give the component - this is also
  39666. the title shown at the top of the window. To change
  39667. this later, use setName()
  39668. @param backgroundColour the colour to use for filling the window's background.
  39669. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  39670. close button to be triggered
  39671. @param addToDesktop if true, the window will be automatically added to the
  39672. desktop; if false, you can use it as a child component
  39673. */
  39674. DialogWindow (const String& name,
  39675. const Colour& backgroundColour,
  39676. const bool escapeKeyTriggersCloseButton,
  39677. const bool addToDesktop = true);
  39678. /** Destructor.
  39679. If a content component has been set with setContentComponent(), it
  39680. will be deleted.
  39681. */
  39682. ~DialogWindow();
  39683. /** Easy way of quickly showing a dialog box containing a given component.
  39684. This will open and display a DialogWindow containing a given component, returning
  39685. when the user clicks its close button.
  39686. It returns the value that was returned by the dialog box's runModalLoop() call.
  39687. To close the dialog programatically, you should call exitModalState (returnValue) on
  39688. the DialogWindow that is created. To find a pointer to this window from your
  39689. contentComponent, you can do something like this:
  39690. @code
  39691. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  39692. if (dw != 0)
  39693. dw->exitModalState (1234);
  39694. @endcode
  39695. @param dialogTitle the dialog box's title
  39696. @param contentComponent the content component for the dialog box. Make sure
  39697. that this has been set to the size you want it to
  39698. be before calling this method. The component won't
  39699. be deleted by this call, so you can re-use it or delete
  39700. it afterwards
  39701. @param componentToCentreAround if this is non-zero, it indicates a component that
  39702. you'd like to show this dialog box in front of. See the
  39703. DocumentWindow::centreAroundComponent() method for more
  39704. info on this parameter
  39705. @param backgroundColour a colour to use for the dialog box's background colour
  39706. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  39707. close button to be triggered
  39708. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  39709. a corner resizer
  39710. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  39711. to use a border or corner resizer component. See ResizableWindow::setResizable()
  39712. */
  39713. static int showModalDialog (const String& dialogTitle,
  39714. Component* contentComponent,
  39715. Component* componentToCentreAround,
  39716. const Colour& backgroundColour,
  39717. const bool escapeKeyTriggersCloseButton,
  39718. const bool shouldBeResizable = false,
  39719. const bool useBottomRightCornerResizer = false);
  39720. juce_UseDebuggingNewOperator
  39721. protected:
  39722. /** @internal */
  39723. void resized();
  39724. private:
  39725. bool escapeKeyTriggersCloseButton;
  39726. DialogWindow (const DialogWindow&);
  39727. const DialogWindow& operator= (const DialogWindow&);
  39728. };
  39729. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  39730. /********* End of inlined file: juce_DialogWindow.h *********/
  39731. #endif
  39732. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39733. #endif
  39734. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  39735. #endif
  39736. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  39737. /********* Start of inlined file: juce_SplashScreen.h *********/
  39738. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  39739. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  39740. /** A component for showing a splash screen while your app starts up.
  39741. This will automatically position itself, and delete itself when the app has
  39742. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  39743. this).
  39744. To use it, just create one of these in your JUCEApplication::initialise() method,
  39745. call its show() method and let the object delete itself later.
  39746. E.g. @code
  39747. void MyApp::initialise (const String& commandLine)
  39748. {
  39749. SplashScreen* splash = new SplashScreen();
  39750. splash->show (T("welcome to my app"),
  39751. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  39752. 4000, false);
  39753. .. no need to delete the splash screen - it'll do that itself.
  39754. }
  39755. @endcode
  39756. */
  39757. class JUCE_API SplashScreen : public Component,
  39758. public Timer,
  39759. private DeletedAtShutdown
  39760. {
  39761. public:
  39762. /** Creates a SplashScreen object.
  39763. After creating one of these (or your subclass of it), call one of the show()
  39764. methods to display it.
  39765. */
  39766. SplashScreen();
  39767. /** Destructor. */
  39768. ~SplashScreen();
  39769. /** Creates a SplashScreen object that will display an image.
  39770. As soon as this is called, the SplashScreen will be displayed in the centre of the
  39771. screen. This method will also dispatch any pending messages to make sure that when
  39772. it returns, the splash screen has been completely drawn, and your initialisation
  39773. code can carry on.
  39774. @param title the name to give the component
  39775. @param backgroundImage an image to draw on the component. The component's size
  39776. will be set to the size of this image, and if the image is
  39777. semi-transparent, the component will be made semi-transparent
  39778. too. This image will be deleted (or released from the ImageCache
  39779. if that's how it was created) by the splash screen object when
  39780. it is itself deleted.
  39781. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  39782. should stay visible for. If the initialisation takes longer than
  39783. this time, the splash screen will wait for it to finish before
  39784. disappearing, but if initialisation is very quick, this lets
  39785. you make sure that people get a good look at your splash.
  39786. @param useDropShadow if true, the window will have a drop shadow
  39787. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  39788. the mouse (anywhere)
  39789. */
  39790. void show (const String& title,
  39791. Image* const backgroundImage,
  39792. const int minimumTimeToDisplayFor,
  39793. const bool useDropShadow,
  39794. const bool removeOnMouseClick = true);
  39795. /** Creates a SplashScreen object with a specified size.
  39796. For a custom splash screen, you can use this method to display it at a certain size
  39797. and then override the paint() method yourself to do whatever's necessary.
  39798. As soon as this is called, the SplashScreen will be displayed in the centre of the
  39799. screen. This method will also dispatch any pending messages to make sure that when
  39800. it returns, the splash screen has been completely drawn, and your initialisation
  39801. code can carry on.
  39802. @param title the name to give the component
  39803. @param width the width to use
  39804. @param height the height to use
  39805. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  39806. should stay visible for. If the initialisation takes longer than
  39807. this time, the splash screen will wait for it to finish before
  39808. disappearing, but if initialisation is very quick, this lets
  39809. you make sure that people get a good look at your splash.
  39810. @param useDropShadow if true, the window will have a drop shadow
  39811. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  39812. the mouse (anywhere)
  39813. */
  39814. void show (const String& title,
  39815. const int width,
  39816. const int height,
  39817. const int minimumTimeToDisplayFor,
  39818. const bool useDropShadow,
  39819. const bool removeOnMouseClick = true);
  39820. /** @internal */
  39821. void paint (Graphics& g);
  39822. /** @internal */
  39823. void timerCallback();
  39824. juce_UseDebuggingNewOperator
  39825. private:
  39826. Image* backgroundImage;
  39827. Time earliestTimeToDelete;
  39828. int originalClickCounter;
  39829. bool isImageInCache;
  39830. SplashScreen (const SplashScreen&);
  39831. const SplashScreen& operator= (const SplashScreen&);
  39832. };
  39833. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  39834. /********* End of inlined file: juce_SplashScreen.h *********/
  39835. #endif
  39836. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  39837. #endif
  39838. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  39839. #endif
  39840. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39841. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  39842. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39843. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39844. /**
  39845. A thread that automatically pops up a modal dialog box with a progress bar
  39846. and cancel button while it's busy running.
  39847. These are handy for performing some sort of task while giving the user feedback
  39848. about how long there is to go, etc.
  39849. E.g. @code
  39850. class MyTask : public ThreadWithProgressWindow
  39851. {
  39852. public:
  39853. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  39854. {
  39855. }
  39856. ~MyTask()
  39857. {
  39858. }
  39859. void run()
  39860. {
  39861. for (int i = 0; i < thingsToDo; ++i)
  39862. {
  39863. // must check this as often as possible, because this is
  39864. // how we know if the user's pressed 'cancel'
  39865. if (threadShouldExit())
  39866. break;
  39867. // this will update the progress bar on the dialog box
  39868. setProgress (i / (double) thingsToDo);
  39869. // ... do the business here...
  39870. }
  39871. }
  39872. };
  39873. void doTheTask()
  39874. {
  39875. MyTask m;
  39876. if (m.runThread())
  39877. {
  39878. // thread finished normally..
  39879. }
  39880. else
  39881. {
  39882. // user pressed the cancel button..
  39883. }
  39884. }
  39885. @endcode
  39886. @see Thread, AlertWindow
  39887. */
  39888. class JUCE_API ThreadWithProgressWindow : public Thread,
  39889. private Timer
  39890. {
  39891. public:
  39892. /** Creates the thread.
  39893. Initially, the dialog box won't be visible, it'll only appear when the
  39894. runThread() method is called.
  39895. @param windowTitle the title to go at the top of the dialog box
  39896. @param hasProgressBar whether the dialog box should have a progress bar (see
  39897. setProgress() )
  39898. @param hasCancelButton whether the dialog box should have a cancel button
  39899. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  39900. the thread to stop before killing it forcibly (see
  39901. Thread::stopThread() )
  39902. @param cancelButtonText the text that should be shown in the cancel button
  39903. (if it has one)
  39904. */
  39905. ThreadWithProgressWindow (const String& windowTitle,
  39906. const bool hasProgressBar,
  39907. const bool hasCancelButton,
  39908. const int timeOutMsWhenCancelling = 10000,
  39909. const String& cancelButtonText = JUCE_T("Cancel"));
  39910. /** Destructor. */
  39911. ~ThreadWithProgressWindow();
  39912. /** Starts the thread and waits for it to finish.
  39913. This will start the thread, make the dialog box appear, and wait until either
  39914. the thread finishes normally, or until the cancel button is pressed.
  39915. Before returning, the dialog box will be hidden.
  39916. @param threadPriority the priority to use when starting the thread - see
  39917. Thread::startThread() for values
  39918. @returns true if the thread finished normally; false if the user pressed cancel
  39919. */
  39920. bool runThread (const int threadPriority = 5);
  39921. /** The thread should call this periodically to update the position of the progress bar.
  39922. @param newProgress the progress, from 0.0 to 1.0
  39923. @see setStatusMessage
  39924. */
  39925. void setProgress (const double newProgress);
  39926. /** The thread can call this to change the message that's displayed in the dialog box.
  39927. */
  39928. void setStatusMessage (const String& newStatusMessage);
  39929. /** Returns the AlertWindow that is being used.
  39930. */
  39931. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  39932. juce_UseDebuggingNewOperator
  39933. private:
  39934. void timerCallback();
  39935. double progress;
  39936. AlertWindow* alertWindow;
  39937. String message;
  39938. CriticalSection messageLock;
  39939. const int timeOutMsWhenCancelling;
  39940. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  39941. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  39942. };
  39943. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  39944. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  39945. #endif
  39946. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  39947. #endif
  39948. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39949. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  39950. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39951. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39952. #if JUCE_WINDOWS || DOXYGEN
  39953. /**
  39954. A Windows-specific class that can create and embed an ActiveX control inside
  39955. itself.
  39956. To use it, create one of these, put it in place and make sure it's visible in a
  39957. window, then use createControl() to instantiate an ActiveX control. The control
  39958. will then be moved and resized to follow the movements of this component.
  39959. Of course, since the control is a heavyweight window, it'll obliterate any
  39960. juce components that may overlap this component, but that's life.
  39961. */
  39962. class JUCE_API ActiveXControlComponent : public Component
  39963. {
  39964. public:
  39965. /** Create an initially-empty container. */
  39966. ActiveXControlComponent();
  39967. /** Destructor. */
  39968. ~ActiveXControlComponent();
  39969. /** Tries to create an ActiveX control and embed it in this peer.
  39970. The peer controlIID is a pointer to an IID structure - it's treated
  39971. as a void* because when including the Juce headers, you might not always
  39972. have included windows.h first, in which case IID wouldn't be defined.
  39973. e.g. @code
  39974. const IID myIID = __uuidof (QTControl);
  39975. myControlComp->createControl (&myIID);
  39976. @endcode
  39977. */
  39978. bool createControl (const void* controlIID);
  39979. /** Deletes the ActiveX control, if one has been created.
  39980. */
  39981. void deleteControl();
  39982. /** Returns true if a control is currently in use. */
  39983. bool isControlOpen() const throw() { return control != 0; }
  39984. /** Does a QueryInterface call on the embedded control object.
  39985. This allows you to cast the control to whatever type of COM object you need.
  39986. The iid parameter is a pointer to an IID structure - it's treated
  39987. as a void* because when including the Juce headers, you might not always
  39988. have included windows.h first, in which case IID wouldn't be defined, but
  39989. you should just pass a pointer to an IID.
  39990. e.g. @code
  39991. const IID iid = __uuidof (IOleWindow);
  39992. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  39993. if (oleWindow != 0)
  39994. {
  39995. HWND hwnd;
  39996. oleWindow->GetWindow (&hwnd);
  39997. ...
  39998. oleWindow->Release();
  39999. }
  40000. @endcode
  40001. */
  40002. void* queryInterface (const void* iid) const;
  40003. /** Set this to false to stop mouse events being allowed through to the control.
  40004. */
  40005. void setMouseEventsAllowed (const bool eventsCanReachControl);
  40006. /** Returns true if mouse events are allowed to get through to the control.
  40007. */
  40008. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  40009. /** @internal */
  40010. void paint (Graphics& g);
  40011. /** @internal */
  40012. void* originalWndProc;
  40013. juce_UseDebuggingNewOperator
  40014. private:
  40015. friend class ActiveXControlData;
  40016. void* control;
  40017. bool mouseEventsAllowed;
  40018. ActiveXControlComponent (const ActiveXControlComponent&);
  40019. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  40020. void setControlBounds (const Rectangle& bounds) const;
  40021. void setControlVisible (const bool b) const;
  40022. };
  40023. #endif
  40024. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  40025. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  40026. #endif
  40027. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  40028. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  40029. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  40030. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  40031. class MidiInputSelectorComponentListBox;
  40032. /**
  40033. A component containing controls to let the user change the audio settings of
  40034. an AudioDeviceManager object.
  40035. Very easy to use - just create one of these and show it to the user.
  40036. @see AudioDeviceManager
  40037. */
  40038. class JUCE_API AudioDeviceSelectorComponent : public Component,
  40039. public ComboBoxListener,
  40040. public ButtonListener,
  40041. public ChangeListener
  40042. {
  40043. public:
  40044. /** Creates the component.
  40045. If your app needs only output channels, you might ask for a maximum of 0 input
  40046. channels, and the component won't display any options for choosing the input
  40047. channels. And likewise if you're doing an input-only app.
  40048. @param deviceManager the device manager that this component should control
  40049. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  40050. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  40051. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  40052. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  40053. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  40054. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  40055. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  40056. treated as a set of separate mono channels.
  40057. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  40058. are shown, with an "advanced" button that shows the rest of them
  40059. */
  40060. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  40061. const int minAudioInputChannels,
  40062. const int maxAudioInputChannels,
  40063. const int minAudioOutputChannels,
  40064. const int maxAudioOutputChannels,
  40065. const bool showMidiInputOptions,
  40066. const bool showMidiOutputSelector,
  40067. const bool showChannelsAsStereoPairs,
  40068. const bool hideAdvancedOptionsWithButton);
  40069. /** Destructor */
  40070. ~AudioDeviceSelectorComponent();
  40071. /** @internal */
  40072. void resized();
  40073. /** @internal */
  40074. void comboBoxChanged (ComboBox*);
  40075. /** @internal */
  40076. void buttonClicked (Button*);
  40077. /** @internal */
  40078. void changeListenerCallback (void*);
  40079. /** @internal */
  40080. void childBoundsChanged (Component*);
  40081. juce_UseDebuggingNewOperator
  40082. private:
  40083. AudioDeviceManager& deviceManager;
  40084. ComboBox* deviceTypeDropDown;
  40085. Label* deviceTypeDropDownLabel;
  40086. Component* audioDeviceSettingsComp;
  40087. String audioDeviceSettingsCompType;
  40088. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  40089. const bool showChannelsAsStereoPairs;
  40090. const bool hideAdvancedOptionsWithButton;
  40091. MidiInputSelectorComponentListBox* midiInputsList;
  40092. Label* midiInputsLabel;
  40093. ComboBox* midiOutputSelector;
  40094. Label* midiOutputLabel;
  40095. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  40096. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  40097. };
  40098. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  40099. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  40100. #endif
  40101. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  40102. /********* Start of inlined file: juce_BubbleComponent.h *********/
  40103. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  40104. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  40105. /**
  40106. A component for showing a message or other graphics inside a speech-bubble-shaped
  40107. outline, pointing at a location on the screen.
  40108. This is a base class that just draws and positions the bubble shape, but leaves
  40109. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  40110. that draws a text message.
  40111. To use it, create your subclass, then either add it to a parent component or
  40112. put it on the desktop with addToDesktop (0), use setPosition() to
  40113. resize and position it, then make it visible.
  40114. @see BubbleMessageComponent
  40115. */
  40116. class JUCE_API BubbleComponent : public Component
  40117. {
  40118. protected:
  40119. /** Creates a BubbleComponent.
  40120. Your subclass will need to implement the getContentSize() and paintContent()
  40121. methods to draw the bubble's contents.
  40122. */
  40123. BubbleComponent();
  40124. public:
  40125. /** Destructor. */
  40126. ~BubbleComponent();
  40127. /** A list of permitted placements for the bubble, relative to the co-ordinates
  40128. at which it should be pointing.
  40129. @see setAllowedPlacement
  40130. */
  40131. enum BubblePlacement
  40132. {
  40133. above = 1,
  40134. below = 2,
  40135. left = 4,
  40136. right = 8
  40137. };
  40138. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  40139. point at which it's pointing.
  40140. By default when setPosition() is called, the bubble will place itself either
  40141. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  40142. the values in BubblePlacement to restrict this choice.
  40143. E.g. if you only want your bubble to appear above or below the target area,
  40144. use setAllowedPlacement (above | below);
  40145. @see BubblePlacement
  40146. */
  40147. void setAllowedPlacement (const int newPlacement);
  40148. /** Moves and resizes the bubble to point at a given component.
  40149. This will resize the bubble to fit its content, then find a position for it
  40150. so that it's next to, but doesn't overlap the given component.
  40151. It'll put itself either above, below, or to the side of the component depending
  40152. on where there's the most space, honouring any restrictions that were set
  40153. with setAllowedPlacement().
  40154. */
  40155. void setPosition (Component* componentToPointTo);
  40156. /** Moves and resizes the bubble to point at a given point.
  40157. This will resize the bubble to fit its content, then position it
  40158. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  40159. are relative to either the bubble component's parent component if it has one, or
  40160. they are screen co-ordinates if not.
  40161. It'll put itself either above, below, or to the side of this point, depending
  40162. on where there's the most space, honouring any restrictions that were set
  40163. with setAllowedPlacement().
  40164. */
  40165. void setPosition (const int arrowTipX,
  40166. const int arrowTipY);
  40167. /** Moves and resizes the bubble to point at a given rectangle.
  40168. This will resize the bubble to fit its content, then find a position for it
  40169. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  40170. co-ordinates are relative to either the bubble component's parent component
  40171. if it has one, or they are screen co-ordinates if not.
  40172. It'll put itself either above, below, or to the side of the component depending
  40173. on where there's the most space, honouring any restrictions that were set
  40174. with setAllowedPlacement().
  40175. */
  40176. void setPosition (const Rectangle& rectangleToPointTo);
  40177. protected:
  40178. /** Subclasses should override this to return the size of the content they
  40179. want to draw inside the bubble.
  40180. */
  40181. virtual void getContentSize (int& width, int& height) = 0;
  40182. /** Subclasses should override this to draw their bubble's contents.
  40183. The graphics object's clip region and the dimensions passed in here are
  40184. set up to paint just the rectangle inside the bubble.
  40185. */
  40186. virtual void paintContent (Graphics& g, int width, int height) = 0;
  40187. public:
  40188. /** @internal */
  40189. void paint (Graphics& g);
  40190. juce_UseDebuggingNewOperator
  40191. private:
  40192. Rectangle content;
  40193. int side, allowablePlacements;
  40194. float arrowTipX, arrowTipY;
  40195. DropShadowEffect shadow;
  40196. BubbleComponent (const BubbleComponent&);
  40197. const BubbleComponent& operator= (const BubbleComponent&);
  40198. };
  40199. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  40200. /********* End of inlined file: juce_BubbleComponent.h *********/
  40201. #endif
  40202. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  40203. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  40204. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  40205. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  40206. /**
  40207. A speech-bubble component that displays a short message.
  40208. This can be used to show a message with the tail of the speech bubble
  40209. pointing to a particular component or location on the screen.
  40210. @see BubbleComponent
  40211. */
  40212. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  40213. private Timer
  40214. {
  40215. public:
  40216. /** Creates a bubble component.
  40217. After creating one a BubbleComponent, do the following:
  40218. - add it to an appropriate parent component, or put it on the
  40219. desktop with Component::addToDesktop (0).
  40220. - use the showAt() method to show a message.
  40221. - it will make itself invisible after it times-out (and can optionally
  40222. also delete itself), or you can reuse it somewhere else by calling
  40223. showAt() again.
  40224. */
  40225. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  40226. /** Destructor. */
  40227. ~BubbleMessageComponent();
  40228. /** Shows a message bubble at a particular position.
  40229. This shows the bubble with its stem pointing to the given location
  40230. (co-ordinates being relative to its parent component).
  40231. For details about exactly how it decides where to position itself, see
  40232. BubbleComponent::updatePosition().
  40233. @param x the x co-ordinate of end of the bubble's tail
  40234. @param y the y co-ordinate of end of the bubble's tail
  40235. @param message the text to display
  40236. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  40237. from its parent compnent. If this is 0 or less, it
  40238. will stay there until manually removed.
  40239. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  40240. mouse button is pressed (anywhere on the screen)
  40241. @param deleteSelfAfterUse if true, then the component will delete itself after
  40242. it becomes invisible
  40243. */
  40244. void showAt (int x, int y,
  40245. const String& message,
  40246. const int numMillisecondsBeforeRemoving,
  40247. const bool removeWhenMouseClicked = true,
  40248. const bool deleteSelfAfterUse = false);
  40249. /** Shows a message bubble next to a particular component.
  40250. This shows the bubble with its stem pointing at the given component.
  40251. For details about exactly how it decides where to position itself, see
  40252. BubbleComponent::updatePosition().
  40253. @param component the component that you want to point at
  40254. @param message the text to display
  40255. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  40256. from its parent compnent. If this is 0 or less, it
  40257. will stay there until manually removed.
  40258. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  40259. mouse button is pressed (anywhere on the screen)
  40260. @param deleteSelfAfterUse if true, then the component will delete itself after
  40261. it becomes invisible
  40262. */
  40263. void showAt (Component* const component,
  40264. const String& message,
  40265. const int numMillisecondsBeforeRemoving,
  40266. const bool removeWhenMouseClicked = true,
  40267. const bool deleteSelfAfterUse = false);
  40268. /** @internal */
  40269. void getContentSize (int& w, int& h);
  40270. /** @internal */
  40271. void paintContent (Graphics& g, int w, int h);
  40272. /** @internal */
  40273. void timerCallback();
  40274. juce_UseDebuggingNewOperator
  40275. private:
  40276. int fadeOutLength, mouseClickCounter;
  40277. TextLayout textLayout;
  40278. int64 expiryTime;
  40279. bool deleteAfterUse;
  40280. void init (const int numMillisecondsBeforeRemoving,
  40281. const bool removeWhenMouseClicked,
  40282. const bool deleteSelfAfterUse);
  40283. BubbleMessageComponent (const BubbleMessageComponent&);
  40284. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  40285. };
  40286. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  40287. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  40288. #endif
  40289. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  40290. /********* Start of inlined file: juce_ColourSelector.h *********/
  40291. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  40292. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  40293. /**
  40294. A component that lets the user choose a colour.
  40295. This shows RGB sliders and a colourspace that the user can pick colours from.
  40296. This class is also a ChangeBroadcaster, so listeners can register to be told
  40297. when the colour changes.
  40298. */
  40299. class JUCE_API ColourSelector : public Component,
  40300. public ChangeBroadcaster,
  40301. protected SliderListener
  40302. {
  40303. public:
  40304. /** Options for the type of selector to show. These are passed into the constructor. */
  40305. enum ColourSelectorOptions
  40306. {
  40307. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  40308. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  40309. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  40310. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  40311. };
  40312. /** Creates a ColourSelector object.
  40313. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  40314. which of the selector's features should be visible.
  40315. The edgeGap value specifies the amount of space to leave around the edge.
  40316. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  40317. colourspace and hue selector components.
  40318. */
  40319. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  40320. const int edgeGap = 4,
  40321. const int gapAroundColourSpaceComponent = 7);
  40322. /** Destructor. */
  40323. ~ColourSelector();
  40324. /** Returns the colour that the user has currently selected.
  40325. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  40326. register to be told when the colour changes.
  40327. @see setCurrentColour
  40328. */
  40329. const Colour getCurrentColour() const;
  40330. /** Changes the colour that is currently being shown.
  40331. */
  40332. void setCurrentColour (const Colour& newColour);
  40333. /** Tells the selector how many preset colour swatches you want to have on the component.
  40334. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  40335. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  40336. their values.
  40337. */
  40338. virtual int getNumSwatches() const;
  40339. /** Called by the selector to find out the colour of one of the swatches.
  40340. Your subclass should return the colour of the swatch with the given index.
  40341. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  40342. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  40343. their values.
  40344. */
  40345. virtual const Colour getSwatchColour (const int index) const;
  40346. /** Called by the selector when the user puts a new colour into one of the swatches.
  40347. Your subclass should change the colour of the swatch with the given index.
  40348. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  40349. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  40350. their values.
  40351. */
  40352. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  40353. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  40354. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40355. methods.
  40356. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40357. */
  40358. enum ColourIds
  40359. {
  40360. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  40361. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  40362. };
  40363. juce_UseDebuggingNewOperator
  40364. private:
  40365. friend class ColourSpaceView;
  40366. friend class HueSelectorComp;
  40367. Colour colour;
  40368. float h, s, v;
  40369. Slider* sliders[4];
  40370. Component* colourSpace;
  40371. Component* hueSelector;
  40372. VoidArray swatchComponents;
  40373. const int flags;
  40374. int topSpace, edgeGap;
  40375. void setHue (float newH);
  40376. void setSV (float newS, float newV);
  40377. void updateHSV();
  40378. void update();
  40379. void sliderValueChanged (Slider*);
  40380. void paint (Graphics& g);
  40381. void resized();
  40382. ColourSelector (const ColourSelector&);
  40383. const ColourSelector& operator= (const ColourSelector&);
  40384. // this constructor is here temporarily to prevent old code compiling, because the parameters
  40385. // have changed - if you get an error here, update your code to use the new constructor instead..
  40386. // (xxx - note to self: remember to remove this at some point in the future)
  40387. ColourSelector (const bool);
  40388. };
  40389. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  40390. /********* End of inlined file: juce_ColourSelector.h *********/
  40391. #endif
  40392. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  40393. #endif
  40394. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  40395. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  40396. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  40397. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  40398. /**
  40399. A component that contains another component, and can magnify or shrink it.
  40400. This component will continually update its size so that it fits the zoomed
  40401. version of the content component that you put inside it, so don't try to
  40402. change the size of this component directly - instead change that of the
  40403. content component.
  40404. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  40405. to remap mouse events correctly. This means that the content component won't
  40406. appear to be a direct child of this component, and instead will think its
  40407. on the desktop.
  40408. */
  40409. class JUCE_API MagnifierComponent : public Component
  40410. {
  40411. public:
  40412. /** Creates a MagnifierComponent.
  40413. This component will continually update its size so that it fits the zoomed
  40414. version of the content component that you put inside it, so don't try to
  40415. change the size of this component directly - instead change that of the
  40416. content component.
  40417. @param contentComponent the component to add as the magnified one
  40418. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  40419. be deleted when this component is deleted. If false,
  40420. it's the caller's responsibility to delete it later.
  40421. */
  40422. MagnifierComponent (Component* const contentComponent,
  40423. const bool deleteContentCompWhenNoLongerNeeded);
  40424. /** Destructor. */
  40425. ~MagnifierComponent();
  40426. /** Returns the current content component. */
  40427. Component* getContentComponent() const throw() { return content; }
  40428. /** Changes the zoom level.
  40429. The scale factor must be greater than zero. Values less than 1 will shrink the
  40430. image; values greater than 1 will multiply its size by this amount.
  40431. When this is called, this component will change its size to fit the full extent
  40432. of the newly zoomed content.
  40433. */
  40434. void setScaleFactor (double newScaleFactor);
  40435. /** Returns the current zoom factor. */
  40436. double getScaleFactor() const throw() { return scaleFactor; }
  40437. /** Changes the quality setting used to rescale the graphics.
  40438. */
  40439. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  40440. juce_UseDebuggingNewOperator
  40441. /** @internal */
  40442. void childBoundsChanged (Component*);
  40443. private:
  40444. Component* content;
  40445. Component* holderComp;
  40446. double scaleFactor;
  40447. ComponentPeer* peer;
  40448. bool deleteContent;
  40449. Graphics::ResamplingQuality quality;
  40450. void paint (Graphics& g);
  40451. void mouseDown (const MouseEvent& e);
  40452. void mouseUp (const MouseEvent& e);
  40453. void mouseDrag (const MouseEvent& e);
  40454. void mouseMove (const MouseEvent& e);
  40455. void mouseEnter (const MouseEvent& e);
  40456. void mouseExit (const MouseEvent& e);
  40457. void mouseWheelMove (const MouseEvent& e, float, float);
  40458. int scaleInt (const int n) const throw();
  40459. MagnifierComponent (const MagnifierComponent&);
  40460. const MagnifierComponent& operator= (const MagnifierComponent&);
  40461. };
  40462. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  40463. /********* End of inlined file: juce_MagnifierComponent.h *********/
  40464. #endif
  40465. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40466. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  40467. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40468. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40469. /**
  40470. A component that displays a piano keyboard, whose notes can be clicked on.
  40471. This component will mimic a physical midi keyboard, showing the current state of
  40472. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  40473. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  40474. Another feature is that the computer keyboard can also be used to play notes. By
  40475. default it maps the top two rows of a standard querty keyboard to the notes, but
  40476. these can be remapped if needed. It will only respond to keypresses when it has
  40477. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  40478. The component is also a ChangeBroadcaster, so if you want to be informed when the
  40479. keyboard is scrolled, you can register a ChangeListener for callbacks.
  40480. @see MidiKeyboardState
  40481. */
  40482. class JUCE_API MidiKeyboardComponent : public Component,
  40483. public MidiKeyboardStateListener,
  40484. public ChangeBroadcaster,
  40485. private Timer,
  40486. private AsyncUpdater
  40487. {
  40488. public:
  40489. /** The direction of the keyboard.
  40490. @see setOrientation
  40491. */
  40492. enum Orientation
  40493. {
  40494. horizontalKeyboard,
  40495. verticalKeyboardFacingLeft,
  40496. verticalKeyboardFacingRight,
  40497. };
  40498. /** Creates a MidiKeyboardComponent.
  40499. @param state the midi keyboard model that this component will represent
  40500. @param orientation whether the keyboard is horizonal or vertical
  40501. */
  40502. MidiKeyboardComponent (MidiKeyboardState& state,
  40503. const Orientation orientation);
  40504. /** Destructor. */
  40505. ~MidiKeyboardComponent();
  40506. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  40507. on the component.
  40508. Values are 0 to 1.0, where 1.0 is the heaviest.
  40509. @see setMidiChannel
  40510. */
  40511. void setVelocity (const float velocity);
  40512. /** Changes the midi channel number that will be used for events triggered by clicking
  40513. on the component.
  40514. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  40515. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  40516. Although this is the channel used for outgoing events, the component can display
  40517. incoming events from more than one channel - see setMidiChannelsToDisplay()
  40518. @see setVelocity
  40519. */
  40520. void setMidiChannel (const int midiChannelNumber);
  40521. /** Returns the midi channel that the keyboard is using for midi messages.
  40522. @see setMidiChannel
  40523. */
  40524. int getMidiChannel() const throw() { return midiChannel; }
  40525. /** Sets a mask to indicate which incoming midi channels should be represented by
  40526. key movements.
  40527. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  40528. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  40529. in this mask, the on-screen keys will also go down.
  40530. By default, this mask is set to 0xffff (all channels displayed).
  40531. @see setMidiChannel
  40532. */
  40533. void setMidiChannelsToDisplay (const int midiChannelMask);
  40534. /** Returns the current set of midi channels represented by the component.
  40535. This is the value that was set with setMidiChannelsToDisplay().
  40536. */
  40537. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  40538. /** Changes the width used to draw the white keys. */
  40539. void setKeyWidth (const float widthInPixels);
  40540. /** Returns the width that was set by setKeyWidth(). */
  40541. float getKeyWidth() const throw() { return keyWidth; }
  40542. /** Changes the keyboard's current direction. */
  40543. void setOrientation (const Orientation newOrientation);
  40544. /** Returns the keyboard's current direction. */
  40545. const Orientation getOrientation() const throw() { return orientation; }
  40546. /** Sets the range of midi notes that the keyboard will be limited to.
  40547. By default the range is 0 to 127 (inclusive), but you can limit this if you
  40548. only want a restricted set of the keys to be shown.
  40549. Note that the values here are inclusive and must be between 0 and 127.
  40550. */
  40551. void setAvailableRange (const int lowestNote,
  40552. const int highestNote);
  40553. /** Returns the first note in the available range.
  40554. @see setAvailableRange
  40555. */
  40556. int getRangeStart() const throw() { return rangeStart; }
  40557. /** Returns the last note in the available range.
  40558. @see setAvailableRange
  40559. */
  40560. int getRangeEnd() const throw() { return rangeEnd; }
  40561. /** If the keyboard extends beyond the size of the component, this will scroll
  40562. it to show the given key at the start.
  40563. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  40564. base class to send a callback to any ChangeListeners that have been registered.
  40565. */
  40566. void setLowestVisibleKey (int noteNumber);
  40567. /** Returns the number of the first key shown in the component.
  40568. @see setLowestVisibleKey
  40569. */
  40570. int getLowestVisibleKey() const throw() { return firstKey; }
  40571. /** Returns the length of the black notes.
  40572. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  40573. */
  40574. int getBlackNoteLength() const throw() { return blackNoteLength; }
  40575. /** If set to true, then scroll buttons will appear at either end of the keyboard
  40576. if there are too many notes to fit them all in the component at once.
  40577. */
  40578. void setScrollButtonsVisible (const bool canScroll);
  40579. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  40580. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40581. methods.
  40582. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40583. */
  40584. enum ColourIds
  40585. {
  40586. whiteNoteColourId = 0x1005000,
  40587. blackNoteColourId = 0x1005001,
  40588. keySeparatorLineColourId = 0x1005002,
  40589. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  40590. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  40591. textLabelColourId = 0x1005005,
  40592. upDownButtonBackgroundColourId = 0x1005006,
  40593. upDownButtonArrowColourId = 0x1005007
  40594. };
  40595. /** Returns the position within the component of the left-hand edge of a key.
  40596. Depending on the keyboard's orientation, this may be a horizontal or vertical
  40597. distance, in either direction.
  40598. */
  40599. int getKeyStartPosition (const int midiNoteNumber) const;
  40600. /** Deletes all key-mappings.
  40601. @see setKeyPressForNote
  40602. */
  40603. void clearKeyMappings();
  40604. /** Maps a key-press to a given note.
  40605. @param key the key that should trigger the note
  40606. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  40607. be. The actual midi note that gets played will be
  40608. this value + (12 * the current base octave). To change
  40609. the base octave, see setKeyPressBaseOctave()
  40610. */
  40611. void setKeyPressForNote (const KeyPress& key,
  40612. const int midiNoteOffsetFromC);
  40613. /** Removes any key-mappings for a given note.
  40614. For a description of what the note number means, see setKeyPressForNote().
  40615. */
  40616. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  40617. /** Changes the base note above which key-press-triggered notes are played.
  40618. The set of key-mappings that trigger notes can be moved up and down to cover
  40619. the entire scale using this method.
  40620. The value passed in is an octave number between 0 and 10 (inclusive), and
  40621. indicates which C is the base note to which the key-mapped notes are
  40622. relative.
  40623. */
  40624. void setKeyPressBaseOctave (const int newOctaveNumber);
  40625. /** This sets the octave number which is shown as the octave number for middle C.
  40626. This affects only the default implementation of getWhiteNoteText(), which
  40627. passes this octave number to MidiMessage::getMidiNoteName() in order to
  40628. get the note text. See MidiMessage::getMidiNoteName() for more info about
  40629. the parameter.
  40630. By default this value is set to 3.
  40631. @see getOctaveForMiddleC
  40632. */
  40633. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  40634. /** This returns the value set by setOctaveForMiddleC().
  40635. @see setOctaveForMiddleC
  40636. */
  40637. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  40638. /** @internal */
  40639. void paint (Graphics& g);
  40640. /** @internal */
  40641. void resized();
  40642. /** @internal */
  40643. void mouseMove (const MouseEvent& e);
  40644. /** @internal */
  40645. void mouseDrag (const MouseEvent& e);
  40646. /** @internal */
  40647. void mouseDown (const MouseEvent& e);
  40648. /** @internal */
  40649. void mouseUp (const MouseEvent& e);
  40650. /** @internal */
  40651. void mouseEnter (const MouseEvent& e);
  40652. /** @internal */
  40653. void mouseExit (const MouseEvent& e);
  40654. /** @internal */
  40655. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40656. /** @internal */
  40657. void timerCallback();
  40658. /** @internal */
  40659. bool keyStateChanged (const bool isKeyDown);
  40660. /** @internal */
  40661. void focusLost (FocusChangeType cause);
  40662. /** @internal */
  40663. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  40664. /** @internal */
  40665. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  40666. /** @internal */
  40667. void handleAsyncUpdate();
  40668. /** @internal */
  40669. void colourChanged();
  40670. juce_UseDebuggingNewOperator
  40671. protected:
  40672. friend class MidiKeyboardUpDownButton;
  40673. /** Draws a white note in the given rectangle.
  40674. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  40675. currently pressed down.
  40676. When doing this, be sure to note the keyboard's orientation.
  40677. */
  40678. virtual void drawWhiteNote (int midiNoteNumber,
  40679. Graphics& g,
  40680. int x, int y, int w, int h,
  40681. bool isDown, bool isOver,
  40682. const Colour& lineColour,
  40683. const Colour& textColour);
  40684. /** Draws a black note in the given rectangle.
  40685. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  40686. currently pressed down.
  40687. When doing this, be sure to note the keyboard's orientation.
  40688. */
  40689. virtual void drawBlackNote (int midiNoteNumber,
  40690. Graphics& g,
  40691. int x, int y, int w, int h,
  40692. bool isDown, bool isOver,
  40693. const Colour& noteFillColour);
  40694. /** Allows text to be drawn on the white notes.
  40695. By default this is used to label the C in each octave, but could be used for other things.
  40696. @see setOctaveForMiddleC
  40697. */
  40698. virtual const String getWhiteNoteText (const int midiNoteNumber);
  40699. /** Draws the up and down buttons that change the base note. */
  40700. virtual void drawUpDownButton (Graphics& g, int w, int h,
  40701. const bool isMouseOver,
  40702. const bool isButtonPressed,
  40703. const bool movesOctavesUp);
  40704. /** Callback when the mouse is clicked on a key.
  40705. You could use this to do things like handle right-clicks on keys, etc.
  40706. Return true if you want the click to trigger the note, or false if you
  40707. want to handle it yourself and not have the note played.
  40708. @see mouseDraggedToKey
  40709. */
  40710. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  40711. /** Callback when the mouse is dragged from one key onto another.
  40712. @see mouseDownOnKey
  40713. */
  40714. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  40715. /** Calculates the positon of a given midi-note.
  40716. This can be overridden to create layouts with custom key-widths.
  40717. @param midiNoteNumber the note to find
  40718. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  40719. @param x the x position of the left-hand edge of the key (this method
  40720. always works in terms of a horizontal keyboard)
  40721. @param w the width of the key
  40722. */
  40723. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  40724. int& x, int& w) const;
  40725. private:
  40726. MidiKeyboardState& state;
  40727. int xOffset, blackNoteLength;
  40728. float keyWidth;
  40729. Orientation orientation;
  40730. int midiChannel, midiInChannelMask;
  40731. float velocity;
  40732. int noteUnderMouse, mouseDownNote;
  40733. BitArray keysPressed, keysCurrentlyDrawnDown;
  40734. int rangeStart, rangeEnd, firstKey;
  40735. bool canScroll, mouseDragging;
  40736. Button* scrollDown;
  40737. Button* scrollUp;
  40738. Array <KeyPress> keyPresses;
  40739. Array <int> keyPressNotes;
  40740. int keyMappingOctave;
  40741. int octaveNumForMiddleC;
  40742. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  40743. int xyToNote (int x, int y);
  40744. int remappedXYToNote (int x, int y) const;
  40745. void resetAnyKeysInUse();
  40746. void updateNoteUnderMouse (int x, int y);
  40747. void repaintNote (const int midiNoteNumber);
  40748. MidiKeyboardComponent (const MidiKeyboardComponent&);
  40749. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  40750. };
  40751. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40752. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  40753. #endif
  40754. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40755. /********* Start of inlined file: juce_NSViewComponent.h *********/
  40756. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40757. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40758. #if ! DOXYGEN
  40759. class NSViewComponentInternal;
  40760. #endif
  40761. #if JUCE_MAC || DOXYGEN
  40762. /**
  40763. A Mac-specific class that can create and embed an NSView inside itself.
  40764. To use it, create one of these, put it in place and make sure it's visible in a
  40765. window, then use setView() to assign an NSView to it. The view will then be
  40766. moved and resized to follow the movements of this component.
  40767. Of course, since the view is a native object, it'll obliterate any
  40768. juce components that may overlap this component, but that's life.
  40769. */
  40770. class JUCE_API NSViewComponent : public Component
  40771. {
  40772. public:
  40773. /** Create an initially-empty container. */
  40774. NSViewComponent();
  40775. /** Destructor. */
  40776. ~NSViewComponent();
  40777. /** Assigns an NSView to this peer.
  40778. The view will be retained and released by this component for as long as
  40779. it is needed. To remove the current view, just call setView (0).
  40780. Note: a void* is used here to avoid including the cocoa headers as
  40781. part of the juce.h, but the method expects an NSView*.
  40782. */
  40783. void setView (void* nsView);
  40784. /** Returns the current NSView.
  40785. Note: a void* is returned here to avoid including the cocoa headers as
  40786. a requirement of juce.h, so you should just cast the object to an NSView*.
  40787. */
  40788. void* getView() const;
  40789. /** @internal */
  40790. void paint (Graphics& g);
  40791. juce_UseDebuggingNewOperator
  40792. private:
  40793. friend class NSViewComponentInternal;
  40794. NSViewComponentInternal* info;
  40795. NSViewComponent (const NSViewComponent&);
  40796. const NSViewComponent& operator= (const NSViewComponent&);
  40797. };
  40798. #endif
  40799. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40800. /********* End of inlined file: juce_NSViewComponent.h *********/
  40801. #endif
  40802. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40803. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  40804. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40805. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40806. // this is used to disable OpenGL, and is defined in juce_Config.h
  40807. #if JUCE_OPENGL || DOXYGEN
  40808. class OpenGLComponentWatcher;
  40809. /**
  40810. Represents the various properties of an OpenGL bitmap format.
  40811. @see OpenGLComponent::setPixelFormat
  40812. */
  40813. class JUCE_API OpenGLPixelFormat
  40814. {
  40815. public:
  40816. /** Creates an OpenGLPixelFormat.
  40817. The default constructor just initialises the object as a simple 8-bit
  40818. RGBA format.
  40819. */
  40820. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  40821. const int alphaBits = 8,
  40822. const int depthBufferBits = 16,
  40823. const int stencilBufferBits = 0) throw();
  40824. int redBits; /**< The number of bits per pixel to use for the red channel. */
  40825. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  40826. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  40827. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  40828. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  40829. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  40830. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  40831. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  40832. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  40833. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  40834. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  40835. /** Returns a list of all the pixel formats that can be used in this system.
  40836. A reference component is needed in case there are multiple screens with different
  40837. capabilities - in which case, the one that the component is on will be used.
  40838. */
  40839. static void getAvailablePixelFormats (Component* component,
  40840. OwnedArray <OpenGLPixelFormat>& results);
  40841. bool operator== (const OpenGLPixelFormat&) const throw();
  40842. juce_UseDebuggingNewOperator
  40843. };
  40844. /**
  40845. A base class for types of OpenGL context.
  40846. An OpenGLComponent will supply its own context for drawing in its window.
  40847. */
  40848. class JUCE_API OpenGLContext
  40849. {
  40850. public:
  40851. /** Destructor. */
  40852. virtual ~OpenGLContext();
  40853. /** Makes this context the currently active one. */
  40854. virtual bool makeActive() const throw() = 0;
  40855. /** If this context is currently active, it is disactivated. */
  40856. virtual bool makeInactive() const throw() = 0;
  40857. /** Returns true if this context is currently active. */
  40858. virtual bool isActive() const throw() = 0;
  40859. /** Swaps the buffers (if the context can do this). */
  40860. virtual void swapBuffers() = 0;
  40861. /** Sets whether the context checks the vertical sync before swapping.
  40862. The value is the number of frames to allow between buffer-swapping. This is
  40863. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  40864. and greater numbers indicate that it should swap less often.
  40865. Returns true if it sets the value successfully.
  40866. */
  40867. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  40868. /** Returns the current swap-sync interval.
  40869. See setSwapInterval() for info about the value returned.
  40870. */
  40871. virtual int getSwapInterval() const = 0;
  40872. /** Returns the pixel format being used by this context. */
  40873. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  40874. /** For windowed contexts, this moves the context within the bounds of
  40875. its parent window.
  40876. */
  40877. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  40878. /** For windowed contexts, this triggers a repaint of the window.
  40879. (Not relevent on all platforms).
  40880. */
  40881. virtual void repaint() = 0;
  40882. /** Returns an OS-dependent handle to the raw GL context.
  40883. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  40884. a GLXContext.
  40885. */
  40886. virtual void* getRawContext() const throw() = 0;
  40887. /** This tries to create a context that can be used for drawing into the
  40888. area occupied by the specified component.
  40889. Note that you probably shouldn't use this method directly unless you know what
  40890. you're doing - the OpenGLComponent calls this and manages the context for you.
  40891. */
  40892. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  40893. const OpenGLPixelFormat& pixelFormat,
  40894. const OpenGLContext* const contextToShareWith);
  40895. /** Returns the context that's currently in active use by the calling thread.
  40896. Returns 0 if there isn't an active context.
  40897. */
  40898. static OpenGLContext* getCurrentContext();
  40899. juce_UseDebuggingNewOperator
  40900. protected:
  40901. OpenGLContext() throw();
  40902. };
  40903. /**
  40904. A component that contains an OpenGL canvas.
  40905. Override this, add it to whatever component you want to, and use the renderOpenGL()
  40906. method to draw its contents.
  40907. */
  40908. class JUCE_API OpenGLComponent : public Component
  40909. {
  40910. public:
  40911. /** Creates an OpenGLComponent.
  40912. */
  40913. OpenGLComponent();
  40914. /** Destructor. */
  40915. ~OpenGLComponent();
  40916. /** Changes the pixel format used by this component.
  40917. @see OpenGLPixelFormat::getAvailablePixelFormats()
  40918. */
  40919. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  40920. /** Returns the pixel format that this component is currently using. */
  40921. const OpenGLPixelFormat getPixelFormat() const;
  40922. /** Specifies an OpenGL context which should be shared with the one that this
  40923. component is using.
  40924. This is an OpenGL feature that lets two contexts share their texture data.
  40925. Note that this pointer is stored by the component, and when the component
  40926. needs to recreate its internal context for some reason, the same context
  40927. will be used again to share lists. So if you pass a context in here,
  40928. don't delete the context while this component is still using it! You can
  40929. call shareWith (0) to stop this component from sharing with it.
  40930. */
  40931. void shareWith (OpenGLContext* contextToShareListsWith);
  40932. /** Returns the context that this component is sharing with.
  40933. @see shareWith
  40934. */
  40935. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  40936. /** Flips the openGL buffers over. */
  40937. void swapBuffers();
  40938. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  40939. When this is called, makeCurrentContextActive() will already have been called
  40940. for you, so you just need to draw.
  40941. */
  40942. virtual void renderOpenGL() = 0;
  40943. /** This method is called when the component creates a new OpenGL context.
  40944. A new context may be created when the component is first used, or when it
  40945. is moved to a different window, or when the window is hidden and re-shown,
  40946. etc.
  40947. You can use this callback as an opportunity to set up things like textures
  40948. that your context needs.
  40949. New contexts are created on-demand by the makeCurrentContextActive() method - so
  40950. if the context is deleted, e.g. by changing the pixel format or window, no context
  40951. will be created until the next call to makeCurrentContextActive(), which will
  40952. synchronously create one and call this method. This means that if you're using
  40953. a non-GUI thread for rendering, you can make sure this method is be called by
  40954. your renderer thread.
  40955. When this callback happens, the context will already have been made current
  40956. using the makeCurrentContextActive() method, so there's no need to call it
  40957. again in your code.
  40958. */
  40959. virtual void newOpenGLContextCreated() = 0;
  40960. /** Returns the context that will draw into this component.
  40961. This may return 0 if the component is currently invisible or hasn't currently
  40962. got a context. The context object can be deleted and a new one created during
  40963. the lifetime of this component, and there may be times when it doesn't have one.
  40964. @see newOpenGLContextCreated()
  40965. */
  40966. OpenGLContext* getCurrentContext() const throw() { return context; }
  40967. /** Makes this component the current openGL context.
  40968. You might want to use this in things like your resize() method, before calling
  40969. GL commands.
  40970. If this returns false, then the context isn't active, so you should avoid
  40971. making any calls.
  40972. This call may actually create a context if one isn't currently initialised. If
  40973. it does this, it will also synchronously call the newOpenGLContextCreated()
  40974. method to let you initialise it as necessary.
  40975. @see OpenGLContext::makeActive
  40976. */
  40977. bool makeCurrentContextActive();
  40978. /** Stops the current component being the active OpenGL context.
  40979. This is the opposite of makeCurrentContextActive()
  40980. @see OpenGLContext::makeInactive
  40981. */
  40982. void makeCurrentContextInactive();
  40983. /** Returns true if this component is the active openGL context for the
  40984. current thread.
  40985. @see OpenGLContext::isActive
  40986. */
  40987. bool isActiveContext() const throw();
  40988. /** Calls the rendering callback, and swaps the buffers afterwards.
  40989. This is called automatically by paint() when the component needs to be rendered.
  40990. It can be overridden if you need to decouple the rendering from the paint callback
  40991. and render with a custom thread.
  40992. Returns true if the operation succeeded.
  40993. */
  40994. virtual bool renderAndSwapBuffers();
  40995. /** This returns a critical section that can be used to lock the current context.
  40996. Because the context that is used by this component can change, e.g. when the
  40997. component is shown or hidden, then if you're rendering to it on a background
  40998. thread, this allows you to lock the context for the duration of your rendering
  40999. routine.
  41000. */
  41001. CriticalSection& getContextLock() throw() { return contextLock; }
  41002. /** @internal */
  41003. void paint (Graphics& g);
  41004. /** Returns the native handle of an embedded heavyweight window, if there is one.
  41005. E.g. On windows, this will return the HWND of the sub-window containing
  41006. the opengl context, on the mac it'll be the NSOpenGLView.
  41007. */
  41008. void* getNativeWindowHandle() const;
  41009. juce_UseDebuggingNewOperator
  41010. private:
  41011. friend class OpenGLComponentWatcher;
  41012. OpenGLComponentWatcher* componentWatcher;
  41013. OpenGLContext* context;
  41014. OpenGLContext* contextToShareListsWith;
  41015. CriticalSection contextLock;
  41016. OpenGLPixelFormat preferredPixelFormat;
  41017. bool needToUpdateViewport;
  41018. void deleteContext();
  41019. void updateContextPosition();
  41020. void internalRepaint (int x, int y, int w, int h);
  41021. OpenGLComponent (const OpenGLComponent&);
  41022. const OpenGLComponent& operator= (const OpenGLComponent&);
  41023. };
  41024. #endif
  41025. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  41026. /********* End of inlined file: juce_OpenGLComponent.h *********/
  41027. #endif
  41028. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  41029. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  41030. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  41031. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  41032. /**
  41033. A component with a set of buttons at the top for changing between pages of
  41034. preferences.
  41035. This is just a handy way of writing a Mac-style preferences panel where you
  41036. have a row of buttons along the top for the different preference categories,
  41037. each button having an icon above its name. Clicking these will show an
  41038. appropriate prefs page below it.
  41039. You can either put one of these inside your own component, or just use the
  41040. showInDialogBox() method to show it in a window and run it modally.
  41041. To use it, just add a set of named pages with the addSettingsPage() method,
  41042. and implement the createComponentForPage() method to create suitable components
  41043. for each of these pages.
  41044. */
  41045. class JUCE_API PreferencesPanel : public Component,
  41046. private ButtonListener
  41047. {
  41048. public:
  41049. /** Creates an empty panel.
  41050. Use addSettingsPage() to add some pages to it in your constructor.
  41051. */
  41052. PreferencesPanel();
  41053. /** Destructor. */
  41054. ~PreferencesPanel();
  41055. /** Creates a page using a set of drawables to define the page's icon.
  41056. Note that the other version of this method is much easier if you're using
  41057. an image instead of a custom drawable.
  41058. @param pageTitle the name of this preferences page - you'll need to
  41059. make sure your createComponentForPage() method creates
  41060. a suitable component when it is passed this name
  41061. @param normalIcon the drawable to display in the page's button normally
  41062. @param overIcon the drawable to display in the page's button when the mouse is over
  41063. @param downIcon the drawable to display in the page's button when the button is down
  41064. @see DrawableButton
  41065. */
  41066. void addSettingsPage (const String& pageTitle,
  41067. const Drawable* normalIcon,
  41068. const Drawable* overIcon,
  41069. const Drawable* downIcon);
  41070. /** Creates a page using a set of drawables to define the page's icon.
  41071. The other version of this method gives you more control over the icon, but this
  41072. one is much easier if you're just loading it from a file.
  41073. @param pageTitle the name of this preferences page - you'll need to
  41074. make sure your createComponentForPage() method creates
  41075. a suitable component when it is passed this name
  41076. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  41077. For this to look good, you'll probably want to use a nice
  41078. transparent png file.
  41079. @param imageDataSize the size of the image data, in bytes
  41080. */
  41081. void addSettingsPage (const String& pageTitle,
  41082. const char* imageData,
  41083. const int imageDataSize);
  41084. /** Utility method to display this panel in a DialogWindow.
  41085. Calling this will create a DialogWindow containing this panel with the
  41086. given size and title, and will run it modally, returning when the user
  41087. closes the dialog box.
  41088. */
  41089. void showInDialogBox (const String& dialogtitle,
  41090. int dialogWidth,
  41091. int dialogHeight,
  41092. const Colour& backgroundColour = Colours::white);
  41093. /** Subclasses must override this to return a component for each preferences page.
  41094. The subclass should return a pointer to a new component representing the named
  41095. page, which the panel will then display.
  41096. The panel will delete the component later when the user goes to another page
  41097. or deletes the panel.
  41098. */
  41099. virtual Component* createComponentForPage (const String& pageName) = 0;
  41100. /** Changes the current page being displayed. */
  41101. void setCurrentPage (const String& pageName);
  41102. /** @internal */
  41103. void resized();
  41104. /** @internal */
  41105. void paint (Graphics& g);
  41106. /** @internal */
  41107. void buttonClicked (Button* button);
  41108. juce_UseDebuggingNewOperator
  41109. private:
  41110. String currentPageName;
  41111. Component* currentPage;
  41112. int buttonSize;
  41113. PreferencesPanel (const PreferencesPanel&);
  41114. const PreferencesPanel& operator= (const PreferencesPanel&);
  41115. };
  41116. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  41117. /********* End of inlined file: juce_PreferencesPanel.h *********/
  41118. #endif
  41119. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  41120. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  41121. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  41122. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  41123. #if JUCE_WEB_BROWSER || DOXYGEN
  41124. #if ! DOXYGEN
  41125. class WebBrowserComponentInternal;
  41126. #endif
  41127. /**
  41128. A component that displays an embedded web browser.
  41129. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  41130. Windows, probably IE.
  41131. */
  41132. class JUCE_API WebBrowserComponent : public Component
  41133. {
  41134. public:
  41135. /** Creates a WebBrowserComponent.
  41136. Once it's created and visible, send the browser to a URL using goToURL().
  41137. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  41138. component is taken offscreen, it'll clear the current page
  41139. and replace it with a blank page - this can be handy to stop
  41140. the browser using resources in the background when it's not
  41141. actually being used.
  41142. */
  41143. WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden = true);
  41144. /** Destructor. */
  41145. ~WebBrowserComponent();
  41146. /** Sends the browser to a particular URL.
  41147. @param url the URL to go to.
  41148. @param headers an optional set of parameters to put in the HTTP header. If
  41149. you supply this, it should be a set of string in the form
  41150. "HeaderKey: HeaderValue"
  41151. @param postData an optional block of data that will be attached to the HTTP
  41152. POST request
  41153. */
  41154. void goToURL (const String& url,
  41155. const StringArray* headers = 0,
  41156. const MemoryBlock* postData = 0);
  41157. /** Stops the current page loading.
  41158. */
  41159. void stop();
  41160. /** Sends the browser back one page.
  41161. */
  41162. void goBack();
  41163. /** Sends the browser forward one page.
  41164. */
  41165. void goForward();
  41166. /** Refreshes the browser.
  41167. */
  41168. void refresh();
  41169. /** This callback is called when the browser is about to navigate
  41170. to a new location.
  41171. You can override this method to perform some action when the user
  41172. tries to go to a particular URL. To allow the operation to carry on,
  41173. return true, or return false to stop the navigation happening.
  41174. */
  41175. virtual bool pageAboutToLoad (const String& newURL);
  41176. /** @internal */
  41177. void paint (Graphics& g);
  41178. /** @internal */
  41179. void resized();
  41180. /** @internal */
  41181. void parentHierarchyChanged();
  41182. /** @internal */
  41183. void visibilityChanged();
  41184. juce_UseDebuggingNewOperator
  41185. private:
  41186. WebBrowserComponentInternal* browser;
  41187. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  41188. String lastURL;
  41189. StringArray lastHeaders;
  41190. MemoryBlock lastPostData;
  41191. void reloadLastURL();
  41192. void checkWindowAssociation();
  41193. WebBrowserComponent (const WebBrowserComponent&);
  41194. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  41195. };
  41196. #endif
  41197. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  41198. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  41199. #endif
  41200. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  41201. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  41202. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  41203. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  41204. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  41205. /**
  41206. On Windows only, this component sits in the taskbar tray as a small icon.
  41207. To use it, just create one of these components, but don't attempt to make it
  41208. visible, add it to a parent, or put it on the desktop.
  41209. You can then call setIconImage() to create an icon for it in the taskbar.
  41210. To change the icon's tooltip, you can use setIconTooltip().
  41211. To respond to mouse-events, you can override the normal mouseDown(),
  41212. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  41213. position will not be valid, you can use this to respond to clicks. Traditionally
  41214. you'd use a left-click to show your application's window, and a right-click
  41215. to show a pop-up menu.
  41216. */
  41217. class JUCE_API SystemTrayIconComponent : public Component
  41218. {
  41219. public:
  41220. SystemTrayIconComponent();
  41221. /** Destructor. */
  41222. ~SystemTrayIconComponent();
  41223. /** Changes the image shown in the taskbar.
  41224. */
  41225. void setIconImage (const Image& newImage);
  41226. /** Changes the tooltip that Windows shows above the icon. */
  41227. void setIconTooltip (const String& tooltip);
  41228. #if JUCE_LINUX
  41229. /** @internal */
  41230. void paint (Graphics& g);
  41231. #endif
  41232. juce_UseDebuggingNewOperator
  41233. private:
  41234. SystemTrayIconComponent (const SystemTrayIconComponent&);
  41235. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  41236. };
  41237. #endif
  41238. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  41239. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  41240. #endif
  41241. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  41242. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  41243. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  41244. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  41245. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  41246. // amalgamated build)
  41247. #if JUCE_WINDOWS
  41248. typedef ActiveXControlComponent QTCompBaseClass;
  41249. #elif JUCE_MAC
  41250. typedef NSViewComponent QTCompBaseClass;
  41251. #endif
  41252. // this is used to disable QuickTime, and is defined in juce_Config.h
  41253. #if JUCE_QUICKTIME || DOXYGEN
  41254. /**
  41255. A window that can play back a QuickTime movie.
  41256. */
  41257. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  41258. {
  41259. public:
  41260. /** Creates a QuickTimeMovieComponent, initially blank.
  41261. Use the loadMovie() method to load a movie once you've added the
  41262. component to a window, (or put it on the desktop as a heavyweight window).
  41263. Loading a movie when the component isn't visible can cause problems, as
  41264. QuickTime needs a window handle to initialise properly.
  41265. */
  41266. QuickTimeMovieComponent();
  41267. /** Destructor. */
  41268. ~QuickTimeMovieComponent();
  41269. /** Returns true if QT is installed and working on this machine.
  41270. */
  41271. static bool isQuickTimeAvailable() throw();
  41272. /** Tries to load a QuickTime movie from a file into the player.
  41273. It's best to call this function once you've added the component to a window,
  41274. (or put it on the desktop as a heavyweight window). Loading a movie when the
  41275. component isn't visible can cause problems, because QuickTime needs a window
  41276. handle to do its stuff.
  41277. @param movieFile the .mov file to open
  41278. @param isControllerVisible whether to show a controller bar at the bottom
  41279. @returns true if the movie opens successfully
  41280. */
  41281. bool loadMovie (const File& movieFile,
  41282. const bool isControllerVisible);
  41283. /** Tries to load a QuickTime movie from a URL into the player.
  41284. It's best to call this function once you've added the component to a window,
  41285. (or put it on the desktop as a heavyweight window). Loading a movie when the
  41286. component isn't visible can cause problems, because QuickTime needs a window
  41287. handle to do its stuff.
  41288. @param movieURL the .mov file to open
  41289. @param isControllerVisible whether to show a controller bar at the bottom
  41290. @returns true if the movie opens successfully
  41291. */
  41292. bool loadMovie (const URL& movieURL,
  41293. const bool isControllerVisible);
  41294. /** Tries to load a QuickTime movie from a stream into the player.
  41295. It's best to call this function once you've added the component to a window,
  41296. (or put it on the desktop as a heavyweight window). Loading a movie when the
  41297. component isn't visible can cause problems, because QuickTime needs a window
  41298. handle to do its stuff.
  41299. @param movieStream a stream containing a .mov file. The component may try
  41300. to read the whole stream before playing, rather than
  41301. streaming from it.
  41302. @param isControllerVisible whether to show a controller bar at the bottom
  41303. @returns true if the movie opens successfully
  41304. */
  41305. bool loadMovie (InputStream* movieStream,
  41306. const bool isControllerVisible);
  41307. /** Closes the movie, if one is open. */
  41308. void closeMovie();
  41309. /** Returns the movie file that is currently open.
  41310. If there isn't one, this returns File::nonexistent
  41311. */
  41312. const File getCurrentMovieFile() const;
  41313. /** Returns true if there's currently a movie open. */
  41314. bool isMovieOpen() const;
  41315. /** Returns the length of the movie, in seconds. */
  41316. double getMovieDuration() const;
  41317. /** Returns the movie's natural size, in pixels.
  41318. You can use this to resize the component to show the movie at its preferred
  41319. scale.
  41320. If no movie is loaded, the size returned will be 0 x 0.
  41321. */
  41322. void getMovieNormalSize (int& width, int& height) const;
  41323. /** This will position the component within a given area, keeping its aspect
  41324. ratio correct according to the movie's normal size.
  41325. The component will be made as large as it can go within the space, and will
  41326. be aligned according to the justification value if this means there are gaps at
  41327. the top or sides.
  41328. */
  41329. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  41330. const RectanglePlacement& placement);
  41331. /** Starts the movie playing. */
  41332. void play();
  41333. /** Stops the movie playing. */
  41334. void stop();
  41335. /** Returns true if the movie is currently playing. */
  41336. bool isPlaying() const;
  41337. /** Moves the movie's position back to the start. */
  41338. void goToStart();
  41339. /** Sets the movie's position to a given time. */
  41340. void setPosition (const double seconds);
  41341. /** Returns the current play position of the movie. */
  41342. double getPosition() const;
  41343. /** Changes the movie playback rate.
  41344. A value of 1 is normal speed, greater values play it proportionately faster,
  41345. smaller values play it slower.
  41346. */
  41347. void setSpeed (const float newSpeed);
  41348. /** Changes the movie's playback volume.
  41349. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  41350. */
  41351. void setMovieVolume (const float newVolume);
  41352. /** Returns the movie's playback volume.
  41353. @returns the volume in the range 0 (silent) to 1.0 (full)
  41354. */
  41355. float getMovieVolume() const;
  41356. /** Tells the movie whether it should loop. */
  41357. void setLooping (const bool shouldLoop);
  41358. /** Returns true if the movie is currently looping.
  41359. @see setLooping
  41360. */
  41361. bool isLooping() const;
  41362. /** True if the native QuickTime controller bar is shown in the window.
  41363. @see loadMovie
  41364. */
  41365. bool isControllerVisible() const;
  41366. /** @internal */
  41367. void paint (Graphics& g);
  41368. juce_UseDebuggingNewOperator
  41369. private:
  41370. File movieFile;
  41371. bool movieLoaded, controllerVisible, looping;
  41372. #if JUCE_WINDOWS
  41373. /** @internal */
  41374. void parentHierarchyChanged();
  41375. /** @internal */
  41376. void visibilityChanged();
  41377. void createControlIfNeeded();
  41378. bool isControlCreated() const;
  41379. void* internal;
  41380. #else
  41381. void* movie;
  41382. #endif
  41383. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  41384. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  41385. };
  41386. #endif
  41387. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  41388. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  41389. #endif
  41390. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  41391. /********* Start of inlined file: juce_LookAndFeel.h *********/
  41392. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  41393. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  41394. class ToggleButton;
  41395. class TextButton;
  41396. class AlertWindow;
  41397. class TextLayout;
  41398. class ScrollBar;
  41399. class BubbleComponent;
  41400. class ComboBox;
  41401. class Button;
  41402. class FilenameComponent;
  41403. class DocumentWindow;
  41404. class ResizableWindow;
  41405. class GroupComponent;
  41406. class MenuBarComponent;
  41407. class DropShadower;
  41408. class GlyphArrangement;
  41409. class PropertyComponent;
  41410. class TableHeaderComponent;
  41411. class Toolbar;
  41412. class ToolbarItemComponent;
  41413. class PopupMenu;
  41414. class ProgressBar;
  41415. class FileBrowserComponent;
  41416. class DirectoryContentsDisplayComponent;
  41417. class FilePreviewComponent;
  41418. class ImageButton;
  41419. /**
  41420. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  41421. can be used to apply different 'skins' to the application.
  41422. */
  41423. class JUCE_API LookAndFeel
  41424. {
  41425. public:
  41426. /** Creates the default JUCE look and feel. */
  41427. LookAndFeel();
  41428. /** Destructor. */
  41429. virtual ~LookAndFeel();
  41430. /** Returns the current default look-and-feel for a component to use when it
  41431. hasn't got one explicitly set.
  41432. @see setDefaultLookAndFeel
  41433. */
  41434. static LookAndFeel& getDefaultLookAndFeel() throw();
  41435. /** Changes the default look-and-feel.
  41436. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  41437. set to 0, it will revert to using the default one. The
  41438. object passed-in must be deleted by the caller when
  41439. it's no longer needed.
  41440. @see getDefaultLookAndFeel
  41441. */
  41442. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  41443. /** Looks for a colour that has been registered with the given colour ID number.
  41444. If a colour has been set for this ID number using setColour(), then it is
  41445. returned. If none has been set, it will just return Colours::black.
  41446. The colour IDs for various purposes are stored as enums in the components that
  41447. they are relevent to - for an example, see Slider::ColourIds,
  41448. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  41449. If you're looking up a colour for use in drawing a component, it's usually
  41450. best not to call this directly, but to use the Component::findColour() method
  41451. instead. That will first check whether a suitable colour has been registered
  41452. directly with the component, and will fall-back on calling the component's
  41453. LookAndFeel's findColour() method if none is found.
  41454. @see setColour, Component::findColour, Component::setColour
  41455. */
  41456. const Colour findColour (const int colourId) const throw();
  41457. /** Registers a colour to be used for a particular purpose.
  41458. For more details, see the comments for findColour().
  41459. @see findColour, Component::findColour, Component::setColour
  41460. */
  41461. void setColour (const int colourId, const Colour& colour) throw();
  41462. /** Returns true if the specified colour ID has been explicitly set using the
  41463. setColour() method.
  41464. */
  41465. bool isColourSpecified (const int colourId) const throw();
  41466. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  41467. /** Allows you to change the default sans-serif font.
  41468. If you need to supply your own Typeface object for any of the default fonts, rather
  41469. than just supplying the name (e.g. if you want to use an embedded font), then
  41470. you should instead override getTypefaceForFont() to create and return the typeface.
  41471. */
  41472. void setDefaultSansSerifTypefaceName (const String& newName);
  41473. /** Override this to get the chance to swap a component's mouse cursor for a
  41474. customised one.
  41475. */
  41476. virtual const MouseCursor getMouseCursorFor (Component& component);
  41477. /** Draws the lozenge-shaped background for a standard button. */
  41478. virtual void drawButtonBackground (Graphics& g,
  41479. Button& button,
  41480. const Colour& backgroundColour,
  41481. bool isMouseOverButton,
  41482. bool isButtonDown);
  41483. virtual const Font getFontForTextButton (TextButton& button);
  41484. /** Draws the text for a TextButton. */
  41485. virtual void drawButtonText (Graphics& g,
  41486. TextButton& button,
  41487. bool isMouseOverButton,
  41488. bool isButtonDown);
  41489. /** Draws the contents of a standard ToggleButton. */
  41490. virtual void drawToggleButton (Graphics& g,
  41491. ToggleButton& button,
  41492. bool isMouseOverButton,
  41493. bool isButtonDown);
  41494. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  41495. virtual void drawTickBox (Graphics& g,
  41496. Component& component,
  41497. int x, int y, int w, int h,
  41498. const bool ticked,
  41499. const bool isEnabled,
  41500. const bool isMouseOverButton,
  41501. const bool isButtonDown);
  41502. /* AlertWindow handling..
  41503. */
  41504. virtual AlertWindow* createAlertWindow (const String& title,
  41505. const String& message,
  41506. const String& button1,
  41507. const String& button2,
  41508. const String& button3,
  41509. AlertWindow::AlertIconType iconType,
  41510. int numButtons,
  41511. Component* associatedComponent);
  41512. virtual void drawAlertBox (Graphics& g,
  41513. AlertWindow& alert,
  41514. const Rectangle& textArea,
  41515. TextLayout& textLayout);
  41516. virtual int getAlertBoxWindowFlags();
  41517. virtual int getAlertWindowButtonHeight();
  41518. virtual const Font getAlertWindowFont();
  41519. /** Draws a progress bar.
  41520. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  41521. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  41522. isn't known). It can use the current time as a basis for playing an animation.
  41523. (Used by progress bars in AlertWindow).
  41524. */
  41525. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  41526. int width, int height,
  41527. double progress, const String& textToShow);
  41528. // Draws a small image that spins to indicate that something's happening..
  41529. // This method should use the current time to animate itself, so just keep
  41530. // repainting it every so often.
  41531. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  41532. int x, int y, int w, int h);
  41533. /** Draws one of the buttons on a scrollbar.
  41534. @param g the context to draw into
  41535. @param scrollbar the bar itself
  41536. @param width the width of the button
  41537. @param height the height of the button
  41538. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  41539. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  41540. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  41541. @param isButtonDown whether the mouse button's held down
  41542. */
  41543. virtual void drawScrollbarButton (Graphics& g,
  41544. ScrollBar& scrollbar,
  41545. int width, int height,
  41546. int buttonDirection,
  41547. bool isScrollbarVertical,
  41548. bool isMouseOverButton,
  41549. bool isButtonDown);
  41550. /** Draws the thumb area of a scrollbar.
  41551. @param g the context to draw into
  41552. @param scrollbar the bar itself
  41553. @param x the x position of the left edge of the thumb area to draw in
  41554. @param y the y position of the top edge of the thumb area to draw in
  41555. @param width the width of the thumb area to draw in
  41556. @param height the height of the thumb area to draw in
  41557. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  41558. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  41559. thumb, or its x position for horizontal bars
  41560. @param thumbSize for vertical bars, the height of the thumb, or its width for
  41561. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  41562. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  41563. currently dragging the thumb
  41564. @param isMouseDown whether the mouse is currently dragging the scrollbar
  41565. */
  41566. virtual void drawScrollbar (Graphics& g,
  41567. ScrollBar& scrollbar,
  41568. int x, int y,
  41569. int width, int height,
  41570. bool isScrollbarVertical,
  41571. int thumbStartPosition,
  41572. int thumbSize,
  41573. bool isMouseOver,
  41574. bool isMouseDown);
  41575. /** Returns the component effect to use for a scrollbar */
  41576. virtual ImageEffectFilter* getScrollbarEffect();
  41577. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  41578. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  41579. /** Returns the default thickness to use for a scrollbar. */
  41580. virtual int getDefaultScrollbarWidth();
  41581. /** Returns the length in pixels to use for a scrollbar button. */
  41582. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  41583. /** Returns a tick shape for use in yes/no boxes, etc. */
  41584. virtual const Path getTickShape (const float height);
  41585. /** Returns a cross shape for use in yes/no boxes, etc. */
  41586. virtual const Path getCrossShape (const float height);
  41587. /** Draws the + or - box in a treeview. */
  41588. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  41589. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  41590. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  41591. // these return an image from the ImageCache, so use ImageCache::release() to free it
  41592. virtual Image* getDefaultFolderImage();
  41593. virtual Image* getDefaultDocumentFileImage();
  41594. virtual void createFileChooserHeaderText (const String& title,
  41595. const String& instructions,
  41596. GlyphArrangement& destArrangement,
  41597. int width);
  41598. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  41599. const String& filename, Image* icon,
  41600. const String& fileSizeDescription,
  41601. const String& fileTimeDescription,
  41602. const bool isDirectory,
  41603. const bool isItemSelected,
  41604. const int itemIndex);
  41605. virtual Button* createFileBrowserGoUpButton();
  41606. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  41607. DirectoryContentsDisplayComponent* fileListComponent,
  41608. FilePreviewComponent* previewComp,
  41609. ComboBox* currentPathBox,
  41610. TextEditor* filenameBox,
  41611. Button* goUpButton);
  41612. virtual void drawBubble (Graphics& g,
  41613. float tipX, float tipY,
  41614. float boxX, float boxY, float boxW, float boxH);
  41615. /** Fills the background of a popup menu component. */
  41616. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  41617. /** Draws one of the items in a popup menu. */
  41618. virtual void drawPopupMenuItem (Graphics& g,
  41619. int width, int height,
  41620. const bool isSeparator,
  41621. const bool isActive,
  41622. const bool isHighlighted,
  41623. const bool isTicked,
  41624. const bool hasSubMenu,
  41625. const String& text,
  41626. const String& shortcutKeyText,
  41627. Image* image,
  41628. const Colour* const textColour);
  41629. /** Returns the size and style of font to use in popup menus. */
  41630. virtual const Font getPopupMenuFont();
  41631. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  41632. int width, int height,
  41633. bool isScrollUpArrow);
  41634. /** Finds the best size for an item in a popup menu. */
  41635. virtual void getIdealPopupMenuItemSize (const String& text,
  41636. const bool isSeparator,
  41637. int standardMenuItemHeight,
  41638. int& idealWidth,
  41639. int& idealHeight);
  41640. virtual int getMenuWindowFlags();
  41641. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  41642. bool isMouseOverBar,
  41643. MenuBarComponent& menuBar);
  41644. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  41645. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  41646. virtual void drawMenuBarItem (Graphics& g,
  41647. int width, int height,
  41648. int itemIndex,
  41649. const String& itemText,
  41650. bool isMouseOverItem,
  41651. bool isMenuOpen,
  41652. bool isMouseOverBar,
  41653. MenuBarComponent& menuBar);
  41654. virtual void drawComboBox (Graphics& g, int width, int height,
  41655. const bool isButtonDown,
  41656. int buttonX, int buttonY,
  41657. int buttonW, int buttonH,
  41658. ComboBox& box);
  41659. virtual const Font getComboBoxFont (ComboBox& box);
  41660. virtual Label* createComboBoxTextBox (ComboBox& box);
  41661. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  41662. virtual void drawLabel (Graphics& g, Label& label);
  41663. virtual void drawLinearSlider (Graphics& g,
  41664. int x, int y,
  41665. int width, int height,
  41666. float sliderPos,
  41667. float minSliderPos,
  41668. float maxSliderPos,
  41669. const Slider::SliderStyle style,
  41670. Slider& slider);
  41671. virtual void drawLinearSliderBackground (Graphics& g,
  41672. int x, int y,
  41673. int width, int height,
  41674. float sliderPos,
  41675. float minSliderPos,
  41676. float maxSliderPos,
  41677. const Slider::SliderStyle style,
  41678. Slider& slider);
  41679. virtual void drawLinearSliderThumb (Graphics& g,
  41680. int x, int y,
  41681. int width, int height,
  41682. float sliderPos,
  41683. float minSliderPos,
  41684. float maxSliderPos,
  41685. const Slider::SliderStyle style,
  41686. Slider& slider);
  41687. virtual int getSliderThumbRadius (Slider& slider);
  41688. virtual void drawRotarySlider (Graphics& g,
  41689. int x, int y,
  41690. int width, int height,
  41691. float sliderPosProportional,
  41692. const float rotaryStartAngle,
  41693. const float rotaryEndAngle,
  41694. Slider& slider);
  41695. virtual Button* createSliderButton (const bool isIncrement);
  41696. virtual Label* createSliderTextBox (Slider& slider);
  41697. virtual ImageEffectFilter* getSliderEffect();
  41698. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  41699. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  41700. virtual Button* createFilenameComponentBrowseButton (const String& text);
  41701. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  41702. ComboBox* filenameBox, Button* browseButton);
  41703. virtual void drawCornerResizer (Graphics& g,
  41704. int w, int h,
  41705. bool isMouseOver,
  41706. bool isMouseDragging);
  41707. virtual void drawResizableFrame (Graphics& g,
  41708. int w, int h,
  41709. const BorderSize& borders);
  41710. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  41711. const BorderSize& border,
  41712. ResizableWindow& window);
  41713. virtual void drawResizableWindowBorder (Graphics& g,
  41714. int w, int h,
  41715. const BorderSize& border,
  41716. ResizableWindow& window);
  41717. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  41718. Graphics& g, int w, int h,
  41719. int titleSpaceX, int titleSpaceW,
  41720. const Image* icon,
  41721. bool drawTitleTextOnLeft);
  41722. virtual Button* createDocumentWindowButton (int buttonType);
  41723. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  41724. int titleBarX, int titleBarY,
  41725. int titleBarW, int titleBarH,
  41726. Button* minimiseButton,
  41727. Button* maximiseButton,
  41728. Button* closeButton,
  41729. bool positionTitleBarButtonsOnLeft);
  41730. virtual int getDefaultMenuBarHeight();
  41731. virtual DropShadower* createDropShadowerForComponent (Component* component);
  41732. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  41733. int w, int h,
  41734. bool isVerticalBar,
  41735. bool isMouseOver,
  41736. bool isMouseDragging);
  41737. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  41738. const String& text,
  41739. const Justification& position,
  41740. GroupComponent& group);
  41741. virtual void createTabButtonShape (Path& p,
  41742. int width, int height,
  41743. int tabIndex,
  41744. const String& text,
  41745. Button& button,
  41746. TabbedButtonBar::Orientation orientation,
  41747. const bool isMouseOver,
  41748. const bool isMouseDown,
  41749. const bool isFrontTab);
  41750. virtual void fillTabButtonShape (Graphics& g,
  41751. const Path& path,
  41752. const Colour& preferredBackgroundColour,
  41753. int tabIndex,
  41754. const String& text,
  41755. Button& button,
  41756. TabbedButtonBar::Orientation orientation,
  41757. const bool isMouseOver,
  41758. const bool isMouseDown,
  41759. const bool isFrontTab);
  41760. virtual void drawTabButtonText (Graphics& g,
  41761. int x, int y, int w, int h,
  41762. const Colour& preferredBackgroundColour,
  41763. int tabIndex,
  41764. const String& text,
  41765. Button& button,
  41766. TabbedButtonBar::Orientation orientation,
  41767. const bool isMouseOver,
  41768. const bool isMouseDown,
  41769. const bool isFrontTab);
  41770. virtual int getTabButtonOverlap (int tabDepth);
  41771. virtual int getTabButtonSpaceAroundImage();
  41772. virtual int getTabButtonBestWidth (int tabIndex,
  41773. const String& text,
  41774. int tabDepth,
  41775. Button& button);
  41776. virtual void drawTabButton (Graphics& g,
  41777. int w, int h,
  41778. const Colour& preferredColour,
  41779. int tabIndex,
  41780. const String& text,
  41781. Button& button,
  41782. TabbedButtonBar::Orientation orientation,
  41783. const bool isMouseOver,
  41784. const bool isMouseDown,
  41785. const bool isFrontTab);
  41786. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  41787. int w, int h,
  41788. TabbedButtonBar& tabBar,
  41789. TabbedButtonBar::Orientation orientation);
  41790. virtual Button* createTabBarExtrasButton();
  41791. virtual void drawImageButton (Graphics& g, Image* image,
  41792. int imageX, int imageY, int imageW, int imageH,
  41793. const Colour& overlayColour,
  41794. float imageOpacity,
  41795. ImageButton& button);
  41796. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  41797. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  41798. int width, int height,
  41799. bool isMouseOver, bool isMouseDown,
  41800. int columnFlags);
  41801. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  41802. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  41803. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  41804. bool isMouseOver, bool isMouseDown,
  41805. ToolbarItemComponent& component);
  41806. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  41807. const String& text, ToolbarItemComponent& component);
  41808. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  41809. bool isOpen, int width, int height);
  41810. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  41811. PropertyComponent& component);
  41812. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  41813. PropertyComponent& component);
  41814. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  41815. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  41816. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  41817. /**
  41818. */
  41819. virtual void playAlertSound();
  41820. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  41821. static void drawGlassSphere (Graphics& g,
  41822. const float x, const float y,
  41823. const float diameter,
  41824. const Colour& colour,
  41825. const float outlineThickness) throw();
  41826. static void drawGlassPointer (Graphics& g,
  41827. const float x, const float y,
  41828. const float diameter,
  41829. const Colour& colour, const float outlineThickness,
  41830. const int direction) throw();
  41831. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  41832. static void drawGlassLozenge (Graphics& g,
  41833. const float x, const float y,
  41834. const float width, const float height,
  41835. const Colour& colour,
  41836. const float outlineThickness,
  41837. const float cornerSize,
  41838. const bool flatOnLeft, const bool flatOnRight,
  41839. const bool flatOnTop, const bool flatOnBottom) throw();
  41840. juce_UseDebuggingNewOperator
  41841. protected:
  41842. // xxx the following methods are only here to cause a compiler error, because they've been
  41843. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  41844. // error if you try to build a subclass with the old versions.
  41845. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  41846. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  41847. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  41848. virtual void getTabButtonBestWidth (int, const String&, int) {}
  41849. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  41850. private:
  41851. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  41852. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  41853. Array <int> colourIds;
  41854. Array <Colour> colours;
  41855. // default typeface names
  41856. String defaultSans, defaultSerif, defaultFixed;
  41857. void drawShinyButtonShape (Graphics& g,
  41858. float x, float y, float w, float h, float maxCornerSize,
  41859. const Colour& baseColour,
  41860. const float strokeWidth,
  41861. const bool flatOnLeft,
  41862. const bool flatOnRight,
  41863. const bool flatOnTop,
  41864. const bool flatOnBottom) throw();
  41865. LookAndFeel (const LookAndFeel&);
  41866. const LookAndFeel& operator= (const LookAndFeel&);
  41867. };
  41868. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  41869. /********* End of inlined file: juce_LookAndFeel.h *********/
  41870. #endif
  41871. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41872. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  41873. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41874. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41875. /**
  41876. The original Juce look-and-feel.
  41877. */
  41878. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  41879. {
  41880. public:
  41881. /** Creates the default JUCE look and feel. */
  41882. OldSchoolLookAndFeel();
  41883. /** Destructor. */
  41884. virtual ~OldSchoolLookAndFeel();
  41885. /** Draws the lozenge-shaped background for a standard button. */
  41886. virtual void drawButtonBackground (Graphics& g,
  41887. Button& button,
  41888. const Colour& backgroundColour,
  41889. bool isMouseOverButton,
  41890. bool isButtonDown);
  41891. /** Draws the contents of a standard ToggleButton. */
  41892. virtual void drawToggleButton (Graphics& g,
  41893. ToggleButton& button,
  41894. bool isMouseOverButton,
  41895. bool isButtonDown);
  41896. virtual void drawTickBox (Graphics& g,
  41897. Component& component,
  41898. int x, int y, int w, int h,
  41899. const bool ticked,
  41900. const bool isEnabled,
  41901. const bool isMouseOverButton,
  41902. const bool isButtonDown);
  41903. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  41904. int width, int height,
  41905. double progress, const String& textToShow);
  41906. virtual void drawScrollbarButton (Graphics& g,
  41907. ScrollBar& scrollbar,
  41908. int width, int height,
  41909. int buttonDirection,
  41910. bool isScrollbarVertical,
  41911. bool isMouseOverButton,
  41912. bool isButtonDown);
  41913. virtual void drawScrollbar (Graphics& g,
  41914. ScrollBar& scrollbar,
  41915. int x, int y,
  41916. int width, int height,
  41917. bool isScrollbarVertical,
  41918. int thumbStartPosition,
  41919. int thumbSize,
  41920. bool isMouseOver,
  41921. bool isMouseDown);
  41922. virtual ImageEffectFilter* getScrollbarEffect();
  41923. virtual void drawTextEditorOutline (Graphics& g,
  41924. int width, int height,
  41925. TextEditor& textEditor);
  41926. /** Fills the background of a popup menu component. */
  41927. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  41928. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  41929. bool isMouseOverBar,
  41930. MenuBarComponent& menuBar);
  41931. virtual void drawComboBox (Graphics& g, int width, int height,
  41932. const bool isButtonDown,
  41933. int buttonX, int buttonY,
  41934. int buttonW, int buttonH,
  41935. ComboBox& box);
  41936. virtual const Font getComboBoxFont (ComboBox& box);
  41937. virtual void drawLinearSlider (Graphics& g,
  41938. int x, int y,
  41939. int width, int height,
  41940. float sliderPos,
  41941. float minSliderPos,
  41942. float maxSliderPos,
  41943. const Slider::SliderStyle style,
  41944. Slider& slider);
  41945. virtual int getSliderThumbRadius (Slider& slider);
  41946. virtual Button* createSliderButton (const bool isIncrement);
  41947. virtual ImageEffectFilter* getSliderEffect();
  41948. virtual void drawCornerResizer (Graphics& g,
  41949. int w, int h,
  41950. bool isMouseOver,
  41951. bool isMouseDragging);
  41952. virtual Button* createDocumentWindowButton (int buttonType);
  41953. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  41954. int titleBarX, int titleBarY,
  41955. int titleBarW, int titleBarH,
  41956. Button* minimiseButton,
  41957. Button* maximiseButton,
  41958. Button* closeButton,
  41959. bool positionTitleBarButtonsOnLeft);
  41960. juce_UseDebuggingNewOperator
  41961. private:
  41962. DropShadowEffect scrollbarShadow;
  41963. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  41964. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  41965. };
  41966. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  41967. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  41968. #endif
  41969. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  41970. #endif
  41971. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41972. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  41973. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41974. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41975. /**
  41976. A class to take care of the logic involved with the loading/saving of some kind
  41977. of document.
  41978. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  41979. functions you need for documents that get saved to a file, so this class attempts
  41980. to abstract most of the boring stuff.
  41981. Your subclass should just implement all the pure virtual methods, and you can
  41982. then use the higher-level public methods to do the load/save dialogs, to warn the user
  41983. about overwriting files, etc.
  41984. The document object keeps track of whether it has changed since it was last saved or
  41985. loaded, so when you change something, call its changed() method. This will set a
  41986. flag so it knows it needs saving, and will also broadcast a change message using the
  41987. ChangeBroadcaster base class.
  41988. @see ChangeBroadcaster
  41989. */
  41990. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  41991. {
  41992. public:
  41993. /** Creates a FileBasedDocument.
  41994. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  41995. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  41996. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  41997. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  41998. */
  41999. FileBasedDocument (const String& fileExtension,
  42000. const String& fileWildCard,
  42001. const String& openFileDialogTitle,
  42002. const String& saveFileDialogTitle);
  42003. /** Destructor. */
  42004. virtual ~FileBasedDocument();
  42005. /** Returns true if the changed() method has been called since the file was
  42006. last saved or loaded.
  42007. @see resetChangedFlag, changed
  42008. */
  42009. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  42010. /** Called to indicate that the document has changed and needs saving.
  42011. This method will also trigger a change message to be sent out using the
  42012. ChangeBroadcaster base class.
  42013. After calling the method, the hasChangedSinceSaved() method will return true, until
  42014. it is reset either by saving to a file or using the resetChangedFlag() method.
  42015. @see hasChangedSinceSaved, resetChangedFlag
  42016. */
  42017. virtual void changed();
  42018. /** Sets the state of the 'changed' flag.
  42019. The 'changed' flag is set to true when the changed() method is called - use this method
  42020. to reset it or to set it without also broadcasting a change message.
  42021. @see changed, hasChangedSinceSaved
  42022. */
  42023. void setChangedFlag (const bool hasChanged);
  42024. /** Tries to open a file.
  42025. If the file opens correctly, the document's file (see the getFile() method) is set
  42026. to this new one; if it fails, the document's file is left unchanged, and optionally
  42027. a message box is shown telling the user there was an error.
  42028. @returns true if the new file loaded successfully
  42029. @see loadDocument, loadFromUserSpecifiedFile
  42030. */
  42031. bool loadFrom (const File& fileToLoadFrom,
  42032. const bool showMessageOnFailure);
  42033. /** Asks the user for a file and tries to load it.
  42034. This will pop up a dialog box using the title, file extension and
  42035. wildcard specified in the document's constructor, and asks the user
  42036. for a file. If they pick one, the loadFrom() method is used to
  42037. try to load it, optionally showing a message if it fails.
  42038. @returns true if a file was loaded; false if the user cancelled or if they
  42039. picked a file which failed to load correctly
  42040. @see loadFrom
  42041. */
  42042. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  42043. /** A set of possible outcomes of one of the save() methods
  42044. */
  42045. enum SaveResult
  42046. {
  42047. savedOk = 0, /**< indicates that a file was saved successfully. */
  42048. userCancelledSave, /**< indicates that the user aborted the save operation. */
  42049. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  42050. };
  42051. /** Tries to save the document to the last file it was saved or loaded from.
  42052. This will always try to write to the file, even if the document isn't flagged as
  42053. having changed.
  42054. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  42055. true, it will prompt the user to pick a file, as if
  42056. saveAsInteractive() was called.
  42057. @param showMessageOnFailure if true it will show a warning message when if the
  42058. save operation fails
  42059. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  42060. */
  42061. SaveResult save (const bool askUserForFileIfNotSpecified,
  42062. const bool showMessageOnFailure);
  42063. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  42064. it if they say yes.
  42065. If you've got a document open and want to close it (e.g. to quit the app), this is the
  42066. method to call.
  42067. If the document doesn't need saving it'll return the value savedOk so
  42068. you can go ahead and delete the document.
  42069. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  42070. return savedOk, so again, you can safely delete the document.
  42071. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  42072. close-document operation.
  42073. And if they click "save changes", it'll try to save and either return savedOk, or
  42074. failedToWriteToFile if there was a problem.
  42075. @see save, saveAs, saveAsInteractive
  42076. */
  42077. SaveResult saveIfNeededAndUserAgrees();
  42078. /** Tries to save the document to a specified file.
  42079. If this succeeds, it'll also change the document's internal file (as returned by
  42080. the getFile() method). If it fails, the file will be left unchanged.
  42081. @param newFile the file to try to write to
  42082. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  42083. the user first if they want to overwrite it
  42084. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  42085. use the saveAsInteractive() method to ask the user for a
  42086. filename
  42087. @param showMessageOnFailure if true and the write operation fails, it'll show
  42088. a message box to warn the user
  42089. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  42090. */
  42091. SaveResult saveAs (const File& newFile,
  42092. const bool warnAboutOverwritingExistingFiles,
  42093. const bool askUserForFileIfNotSpecified,
  42094. const bool showMessageOnFailure);
  42095. /** Prompts the user for a filename and tries to save to it.
  42096. This will pop up a dialog box using the title, file extension and
  42097. wildcard specified in the document's constructor, and asks the user
  42098. for a file. If they pick one, the saveAs() method is used to try to save
  42099. to this file.
  42100. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  42101. the user first if they want to overwrite it
  42102. @see saveIfNeededAndUserAgrees, save, saveAs
  42103. */
  42104. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  42105. /** Returns the file that this document was last successfully saved or loaded from.
  42106. When the document object is created, this will be set to File::nonexistent.
  42107. It is changed when one of the load or save methods is used, or when setFile()
  42108. is used to explicitly set it.
  42109. */
  42110. const File getFile() const throw() { return documentFile; }
  42111. /** Sets the file that this document thinks it was loaded from.
  42112. This won't actually load anything - it just changes the file stored internally.
  42113. @see getFile
  42114. */
  42115. void setFile (const File& newFile);
  42116. protected:
  42117. /** Overload this to return the title of the document.
  42118. This is used in message boxes, filenames and file choosers, so it should be
  42119. something sensible.
  42120. */
  42121. virtual const String getDocumentTitle() = 0;
  42122. /** This method should try to load your document from the given file.
  42123. If it fails, it should return an error message. If it succeeds, it should return
  42124. an empty string.
  42125. */
  42126. virtual const String loadDocument (const File& file) = 0;
  42127. /** This method should try to write your document to the given file.
  42128. If it fails, it should return an error message. If it succeeds, it should return
  42129. an empty string.
  42130. */
  42131. virtual const String saveDocument (const File& file) = 0;
  42132. /** This is used for dialog boxes to make them open at the last folder you
  42133. were using.
  42134. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  42135. the last document that was used - you might want to store this value
  42136. in a static variable, or even in your application's properties. It should
  42137. be a global setting rather than a property of this object.
  42138. This method works very well in conjunction with a RecentlyOpenedFilesList
  42139. object to manage your recent-files list.
  42140. As a default value, it's ok to return File::nonexistent, and the document
  42141. object will use a sensible one instead.
  42142. @see RecentlyOpenedFilesList
  42143. */
  42144. virtual const File getLastDocumentOpened() = 0;
  42145. /** This is used for dialog boxes to make them open at the last folder you
  42146. were using.
  42147. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  42148. the last document that was used - you might want to store this value
  42149. in a static variable, or even in your application's properties. It should
  42150. be a global setting rather than a property of this object.
  42151. This method works very well in conjunction with a RecentlyOpenedFilesList
  42152. object to manage your recent-files list.
  42153. @see RecentlyOpenedFilesList
  42154. */
  42155. virtual void setLastDocumentOpened (const File& file) = 0;
  42156. public:
  42157. juce_UseDebuggingNewOperator
  42158. private:
  42159. File documentFile;
  42160. bool changedSinceSave;
  42161. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  42162. FileBasedDocument (const FileBasedDocument&);
  42163. const FileBasedDocument& operator= (const FileBasedDocument&);
  42164. };
  42165. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42166. /********* End of inlined file: juce_FileBasedDocument.h *********/
  42167. #endif
  42168. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  42169. #endif
  42170. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42171. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  42172. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42173. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42174. /**
  42175. Manages a set of files for use as a list of recently-opened documents.
  42176. This is a handy class for holding your list of recently-opened documents, with
  42177. helpful methods for things like purging any non-existent files, automatically
  42178. adding them to a menu, and making persistence easy.
  42179. @see File, FileBasedDocument
  42180. */
  42181. class JUCE_API RecentlyOpenedFilesList
  42182. {
  42183. public:
  42184. /** Creates an empty list.
  42185. */
  42186. RecentlyOpenedFilesList();
  42187. /** Destructor. */
  42188. ~RecentlyOpenedFilesList();
  42189. /** Sets a limit for the number of files that will be stored in the list.
  42190. When addFile() is called, then if there is no more space in the list, the
  42191. least-recently added file will be dropped.
  42192. @see getMaxNumberOfItems
  42193. */
  42194. void setMaxNumberOfItems (const int newMaxNumber);
  42195. /** Returns the number of items that this list will store.
  42196. @see setMaxNumberOfItems
  42197. */
  42198. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  42199. /** Returns the number of files in the list.
  42200. The most recently added file is always at index 0.
  42201. */
  42202. int getNumFiles() const;
  42203. /** Returns one of the files in the list.
  42204. The most recently added file is always at index 0.
  42205. */
  42206. const File getFile (const int index) const;
  42207. /** Returns an array of all the absolute pathnames in the list.
  42208. */
  42209. const StringArray& getAllFilenames() const throw() { return files; }
  42210. /** Clears all the files from the list. */
  42211. void clear();
  42212. /** Adds a file to the list.
  42213. The file will be added at index 0. If this file is already in the list, it will
  42214. be moved up to index 0, but a file can only appear once in the list.
  42215. If the list already contains the maximum number of items that is permitted, the
  42216. least-recently added file will be dropped from the end.
  42217. */
  42218. void addFile (const File& file);
  42219. /** Checks each of the files in the list, removing any that don't exist.
  42220. You might want to call this after reloading a list of files, or before putting them
  42221. on a menu.
  42222. */
  42223. void removeNonExistentFiles();
  42224. /** Adds entries to a menu, representing each of the files in the list.
  42225. This is handy for creating an "open recent file..." menu in your app. The
  42226. menu items are numbered consecutively starting with the baseItemId value,
  42227. and can either be added as complete pathnames, or just the last part of the
  42228. filename.
  42229. If dontAddNonExistentFiles is true, then each file will be checked and only those
  42230. that exist will be added.
  42231. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  42232. pointers to file objects. Any files that appear in this list will not be added to the
  42233. menu - the reason for this is that you might have a number of files already open, so
  42234. might not want these to be shown in the menu.
  42235. It returns the number of items that were added.
  42236. */
  42237. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  42238. const int baseItemId,
  42239. const bool showFullPaths,
  42240. const bool dontAddNonExistentFiles,
  42241. const File** filesToAvoid = 0);
  42242. /** Returns a string that encapsulates all the files in the list.
  42243. The string that is returned can later be passed into restoreFromString() in
  42244. order to recreate the list. This is handy for persisting your list, e.g. in
  42245. a PropertiesFile object.
  42246. @see restoreFromString
  42247. */
  42248. const String toString() const;
  42249. /** Restores the list from a previously stringified version of the list.
  42250. Pass in a stringified version created with toString() in order to persist/restore
  42251. your list.
  42252. @see toString
  42253. */
  42254. void restoreFromString (const String& stringifiedVersion);
  42255. juce_UseDebuggingNewOperator
  42256. private:
  42257. StringArray files;
  42258. int maxNumberOfItems;
  42259. };
  42260. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42261. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  42262. #endif
  42263. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  42264. #endif
  42265. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42266. /********* Start of inlined file: juce_SystemClipboard.h *********/
  42267. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42268. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42269. /**
  42270. Handles reading/writing to the system's clipboard.
  42271. */
  42272. class JUCE_API SystemClipboard
  42273. {
  42274. public:
  42275. /** Copies a string of text onto the clipboard */
  42276. static void copyTextToClipboard (const String& text) throw();
  42277. /** Gets the current clipboard's contents.
  42278. Obviously this might have come from another app, so could contain
  42279. anything..
  42280. */
  42281. static const String getTextFromClipboard() throw();
  42282. };
  42283. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42284. /********* End of inlined file: juce_SystemClipboard.h *********/
  42285. #endif
  42286. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  42287. #endif
  42288. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  42289. #endif
  42290. #endif
  42291. /********* End of inlined file: juce_app_includes.h *********/
  42292. #endif
  42293. #if JUCE_MSVC
  42294. #pragma warning (pop)
  42295. #pragma pack (pop)
  42296. #endif
  42297. #if JUCE_MAC || JUCE_IPHONE
  42298. #pragma align=reset
  42299. #endif
  42300. END_JUCE_NAMESPACE
  42301. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  42302. #ifdef JUCE_NAMESPACE
  42303. // this will obviously save a lot of typing, but can be disabled by
  42304. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  42305. using namespace JUCE_NAMESPACE;
  42306. /* On the Mac, these symbols are defined in the Mac libraries, so
  42307. these macros make it easier to reference them without writing out
  42308. the namespace every time.
  42309. If you run into difficulties where these macros interfere with the contents
  42310. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  42311. the comments in that file for more information.
  42312. */
  42313. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  42314. #define Component JUCE_NAMESPACE::Component
  42315. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  42316. #define Point JUCE_NAMESPACE::Point
  42317. #define Button JUCE_NAMESPACE::Button
  42318. #endif
  42319. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  42320. it easier to use the juce version explicitly.
  42321. If you run into difficulties where this macro interferes with other 3rd party header
  42322. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  42323. file for more information.
  42324. */
  42325. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  42326. #define Rectangle JUCE_NAMESPACE::Rectangle
  42327. #endif
  42328. #endif
  42329. #endif
  42330. /* Easy autolinking to the right JUCE libraries under win32.
  42331. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  42332. including this header file.
  42333. */
  42334. #if JUCE_MSVC
  42335. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  42336. /** If you want your application to link to Juce as a DLL instead of
  42337. a static library (on win32), just define the JUCE_DLL macro before
  42338. including juce.h
  42339. */
  42340. #ifdef JUCE_DLL
  42341. #ifdef JUCE_DEBUG
  42342. #define AUTOLINKEDLIB "JUCE_debug.lib"
  42343. #else
  42344. #define AUTOLINKEDLIB "JUCE.lib"
  42345. #endif
  42346. #else
  42347. #ifdef JUCE_DEBUG
  42348. #ifdef _WIN64
  42349. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  42350. #else
  42351. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  42352. #endif
  42353. #else
  42354. #ifdef _WIN64
  42355. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  42356. #else
  42357. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  42358. #endif
  42359. #endif
  42360. #endif
  42361. #pragma comment(lib, AUTOLINKEDLIB)
  42362. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  42363. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  42364. #endif
  42365. // Auto-link the other win32 libs that are needed by library calls..
  42366. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  42367. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  42368. // Auto-links to various win32 libs that are needed by library calls..
  42369. #pragma comment(lib, "kernel32.lib")
  42370. #pragma comment(lib, "user32.lib")
  42371. #pragma comment(lib, "shell32.lib")
  42372. #pragma comment(lib, "gdi32.lib")
  42373. #pragma comment(lib, "vfw32.lib")
  42374. #pragma comment(lib, "comdlg32.lib")
  42375. #pragma comment(lib, "winmm.lib")
  42376. #pragma comment(lib, "wininet.lib")
  42377. #pragma comment(lib, "ole32.lib")
  42378. #pragma comment(lib, "advapi32.lib")
  42379. #pragma comment(lib, "ws2_32.lib")
  42380. #pragma comment(lib, "comsupp.lib")
  42381. #pragma comment(lib, "version.lib")
  42382. #if JUCE_OPENGL
  42383. #pragma comment(lib, "OpenGL32.Lib")
  42384. #pragma comment(lib, "GlU32.Lib")
  42385. #endif
  42386. #if JUCE_QUICKTIME
  42387. #pragma comment (lib, "QTMLClient.lib")
  42388. #endif
  42389. #if JUCE_USE_CAMERA
  42390. #pragma comment (lib, "Strmiids.lib")
  42391. #endif
  42392. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  42393. #endif
  42394. #endif
  42395. #endif
  42396. /*
  42397. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  42398. AppSubClass is the name of a class derived from JUCEApplication.
  42399. See the JUCEApplication class documentation (juce_Application.h) for more details.
  42400. */
  42401. #if defined (JUCE_GCC) || defined (__MWERKS__)
  42402. #define START_JUCE_APPLICATION(AppClass) \
  42403. int main (int argc, char* argv[]) \
  42404. { \
  42405. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  42406. }
  42407. #elif JUCE_WINDOWS
  42408. #ifdef _CONSOLE
  42409. #define START_JUCE_APPLICATION(AppClass) \
  42410. int main (int, char* argv[]) \
  42411. { \
  42412. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42413. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42414. }
  42415. #elif ! defined (_AFXDLL)
  42416. #ifdef _WINDOWS_
  42417. #define START_JUCE_APPLICATION(AppClass) \
  42418. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  42419. { \
  42420. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42421. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42422. }
  42423. #else
  42424. #define START_JUCE_APPLICATION(AppClass) \
  42425. int __stdcall WinMain (int, int, const char*, int) \
  42426. { \
  42427. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42428. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42429. }
  42430. #endif
  42431. #endif
  42432. #endif
  42433. #endif // __JUCE_JUCEHEADER__
  42434. /********* End of inlined file: juce.h *********/
  42435. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__