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.

57172 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_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  582. #if JUCE_LOG_ASSERTIONS
  583. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  584. #endif
  585. /********* Start of inlined file: juce_Memory.h *********/
  586. #ifndef __JUCE_MEMORY_JUCEHEADER__
  587. #define __JUCE_MEMORY_JUCEHEADER__
  588. /*
  589. This file defines the various juce_malloc(), juce_free() macros that should be used in
  590. preference to the standard calls.
  591. */
  592. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  593. #ifndef JUCE_DLL
  594. // Win32 debug non-DLL versions..
  595. /** This should be used instead of calling malloc directly.
  596. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  597. */
  598. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  599. /** This should be used instead of calling calloc directly.
  600. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  601. */
  602. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  603. /** This should be used instead of calling realloc directly.
  604. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  605. */
  606. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  607. /** This should be used instead of calling free directly.
  608. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  609. */
  610. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  611. #else
  612. // Win32 debug DLL versions..
  613. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  614. // way all juce calls in the DLL and in the host API will all use the same allocator.
  615. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  616. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  617. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  618. extern JUCE_API void juce_DebugFree (void* const block);
  619. /** This should be used instead of calling malloc directly.
  620. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  621. */
  622. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  623. /** This should be used instead of calling calloc directly.
  624. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  625. */
  626. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  627. /** This should be used instead of calling realloc directly.
  628. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  629. */
  630. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  631. /** This should be used instead of calling free directly.
  632. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  633. */
  634. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  635. #endif
  636. #if ! defined (_AFXDLL)
  637. /** This macro can be added to classes to add extra debugging information to the memory
  638. allocated for them, so you can see the type of objects involved when there's a dump
  639. of leaked objects at program shutdown. (Only works on win32 at the moment).
  640. */
  641. #define juce_UseDebuggingNewOperator \
  642. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  643. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  644. static void operator delete (void* p) { juce_free (p); }
  645. #endif
  646. #elif defined (JUCE_DLL)
  647. // Win32 DLL (release) versions..
  648. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  649. // way all juce calls in the DLL and in the host API will all use the same allocator.
  650. extern JUCE_API void* juce_Malloc (const int size);
  651. extern JUCE_API void* juce_Calloc (const int size);
  652. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  653. extern JUCE_API void juce_Free (void* const block);
  654. /** This should be used instead of calling malloc directly.
  655. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  656. */
  657. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  658. /** This should be used instead of calling calloc directly.
  659. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  660. */
  661. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  662. /** This should be used instead of calling realloc directly.
  663. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  664. */
  665. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  666. /** This should be used instead of calling free directly.
  667. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  668. */
  669. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  670. #define juce_UseDebuggingNewOperator \
  671. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  672. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  673. static void operator delete (void* p) { juce_free (p); }
  674. #else
  675. // Mac, Linux and Win32 (release) versions..
  676. /** This should be used instead of calling malloc directly.
  677. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  678. */
  679. #define juce_malloc(numBytes) malloc (numBytes)
  680. /** This should be used instead of calling calloc directly.
  681. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  682. */
  683. #define juce_calloc(numBytes) calloc (1, numBytes)
  684. /** This should be used instead of calling realloc directly.
  685. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  686. */
  687. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  688. /** This should be used instead of calling free directly.
  689. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  690. */
  691. #define juce_free(location) free (location)
  692. #endif
  693. /** This macro can be added to classes to add extra debugging information to the memory
  694. allocated for them, so you can see the type of objects involved when there's a dump
  695. of leaked objects at program shutdown. (Only works on win32 at the moment).
  696. Note that if you create a class that inherits from a class that uses this macro,
  697. your class must also use the macro, otherwise you'll probably get compile errors
  698. because of ambiguous new operators.
  699. Most of the JUCE classes use it, so see these for examples of where it should go.
  700. */
  701. #ifndef juce_UseDebuggingNewOperator
  702. #define juce_UseDebuggingNewOperator
  703. #endif
  704. #if JUCE_MSVC
  705. /** This is a compiler-independent way of declaring a variable as being thread-local.
  706. E.g.
  707. @code
  708. juce_ThreadLocal int myVariable;
  709. @endcode
  710. */
  711. #define juce_ThreadLocal __declspec(thread)
  712. #else
  713. #define juce_ThreadLocal __thread
  714. #endif
  715. /** Clears a block of memory. */
  716. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  717. /** Clears a reference to a local structure. */
  718. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  719. /** A handy macro that calls delete on a pointer if it's non-zero, and
  720. then sets the pointer to null.
  721. */
  722. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  723. #endif // __JUCE_MEMORY_JUCEHEADER__
  724. /********* End of inlined file: juce_Memory.h *********/
  725. /********* Start of inlined file: juce_MathsFunctions.h *********/
  726. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  727. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  728. /*
  729. This file sets up some handy mathematical typdefs and functions.
  730. */
  731. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  732. /** A platform-independent 8-bit signed integer type. */
  733. typedef signed char int8;
  734. /** A platform-independent 8-bit unsigned integer type. */
  735. typedef unsigned char uint8;
  736. /** A platform-independent 16-bit signed integer type. */
  737. typedef signed short int16;
  738. /** A platform-independent 16-bit unsigned integer type. */
  739. typedef unsigned short uint16;
  740. /** A platform-independent 32-bit signed integer type. */
  741. typedef signed int int32;
  742. /** A platform-independent 32-bit unsigned integer type. */
  743. typedef unsigned int uint32;
  744. #if JUCE_MSVC
  745. /** A platform-independent 64-bit integer type. */
  746. typedef __int64 int64;
  747. /** A platform-independent 64-bit unsigned integer type. */
  748. typedef unsigned __int64 uint64;
  749. /** A platform-independent macro for writing 64-bit literals, needed because
  750. different compilers have different syntaxes for this.
  751. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  752. GCC, or 0x1000000000 for MSVC.
  753. */
  754. #define literal64bit(longLiteral) ((__int64) longLiteral)
  755. #else
  756. /** A platform-independent 64-bit integer type. */
  757. typedef long long int64;
  758. /** A platform-independent 64-bit unsigned integer type. */
  759. typedef unsigned long long uint64;
  760. /** A platform-independent macro for writing 64-bit literals, needed because
  761. different compilers have different syntaxes for this.
  762. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  763. GCC, or 0x1000000000 for MSVC.
  764. */
  765. #define literal64bit(longLiteral) (longLiteral##LL)
  766. #endif
  767. #if JUCE_64BIT
  768. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  769. typedef int64 pointer_sized_int;
  770. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  771. typedef uint64 pointer_sized_uint;
  772. #elif _MSC_VER >= 1300
  773. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  774. typedef _W64 int pointer_sized_int;
  775. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  776. typedef _W64 unsigned int pointer_sized_uint;
  777. #else
  778. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  779. typedef int pointer_sized_int;
  780. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  781. typedef unsigned int pointer_sized_uint;
  782. #endif
  783. /** A platform-independent unicode character type. */
  784. typedef wchar_t juce_wchar;
  785. // Some indispensible min/max functions
  786. /** Returns the larger of two values. */
  787. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  788. /** Returns the larger of two values. */
  789. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  790. /** Returns the larger of two values. */
  791. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  792. /** Returns the larger of two values. */
  793. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  794. /** Returns the larger of three values. */
  795. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  796. /** Returns the larger of three values. */
  797. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  798. /** Returns the larger of three values. */
  799. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  800. /** Returns the larger of three values. */
  801. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  802. /** Returns the larger of four values. */
  803. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  804. /** Returns the larger of four values. */
  805. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  806. /** Returns the larger of four values. */
  807. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  808. /** Returns the larger of four values. */
  809. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  810. /** Returns the smaller of two values. */
  811. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  812. /** Returns the smaller of two values. */
  813. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  814. /** Returns the smaller of two values. */
  815. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  816. /** Returns the smaller of two values. */
  817. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  818. /** Returns the smaller of three values. */
  819. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  820. /** Returns the smaller of three values. */
  821. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  822. /** Returns the smaller of three values. */
  823. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  824. /** Returns the smaller of three values. */
  825. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  826. /** Returns the smaller of four values. */
  827. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  828. /** Returns the smaller of four values. */
  829. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  830. /** Returns the smaller of four values. */
  831. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  832. /** Returns the smaller of four values. */
  833. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  834. /** Constrains a value to keep it within a given range.
  835. This will check that the specified value lies between the lower and upper bounds
  836. specified, and if not, will return the nearest value that would be in-range. Effectively,
  837. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  838. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  839. the results will be unpredictable.
  840. @param lowerLimit the minimum value to return
  841. @param upperLimit the maximum value to return
  842. @param valueToConstrain the value to try to return
  843. @returns the closest value to valueToConstrain which lies between lowerLimit
  844. and upperLimit (inclusive)
  845. @see jlimit0To, jmin, jmax
  846. */
  847. template <typename Type>
  848. inline Type jlimit (const Type lowerLimit,
  849. const Type upperLimit,
  850. const Type valueToConstrain) throw()
  851. {
  852. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  853. return (valueToConstrain < lowerLimit) ? lowerLimit
  854. : ((valueToConstrain > upperLimit) ? upperLimit
  855. : valueToConstrain);
  856. }
  857. /** Handy function to swap two values over.
  858. */
  859. template <typename Type>
  860. inline void swapVariables (Type& variable1, Type& variable2)
  861. {
  862. const Type tempVal = variable1;
  863. variable1 = variable2;
  864. variable2 = tempVal;
  865. }
  866. /** Handy macro for getting the number of elements in a simple const C array.
  867. E.g.
  868. @code
  869. static int myArray[] = { 1, 2, 3 };
  870. int numElements = numElementsInArray (myArray) // returns 3
  871. @endcode
  872. */
  873. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  874. // Some useful maths functions that aren't always present with all compilers and build settings.
  875. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  876. versions of these functions of various platforms and compilers. */
  877. inline double juce_hypot (double a, double b)
  878. {
  879. #if JUCE_WINDOWS
  880. return _hypot (a, b);
  881. #else
  882. return hypot (a, b);
  883. #endif
  884. }
  885. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  886. versions of these functions of various platforms and compilers. */
  887. inline float juce_hypotf (float a, float b)
  888. {
  889. #if JUCE_WINDOWS
  890. return (float) _hypot (a, b);
  891. #else
  892. return hypotf (a, b);
  893. #endif
  894. }
  895. /** 64-bit abs function. */
  896. inline int64 abs64 (const int64 n)
  897. {
  898. return (n >= 0) ? n : -n;
  899. }
  900. /** A predefined value for Pi, at double-precision.
  901. @see float_Pi
  902. */
  903. const double double_Pi = 3.1415926535897932384626433832795;
  904. /** A predefined value for Pi, at sngle-precision.
  905. @see double_Pi
  906. */
  907. const float float_Pi = 3.14159265358979323846f;
  908. /** The isfinite() method seems to vary between platforms, so this is a
  909. platform-independent function for it.
  910. */
  911. template <typename FloatingPointType>
  912. inline bool juce_isfinite (FloatingPointType value)
  913. {
  914. #if JUCE_WINDOWS
  915. return _finite (value);
  916. #else
  917. return std::isfinite (value);
  918. #endif
  919. }
  920. /** Fast floating-point-to-integer conversion.
  921. This is faster than using the normal c++ cast to convert a double to an int, and
  922. it will round the value to the nearest integer, rather than rounding it down
  923. like the normal cast does.
  924. Note that this routine gets its speed at the expense of some accuracy, and when
  925. rounding values whose floating point component is exactly 0.5, odd numbers and
  926. even numbers will be rounded up or down differently. For a more accurate conversion,
  927. see roundDoubleToIntAccurate().
  928. */
  929. inline int roundDoubleToInt (const double value) throw()
  930. {
  931. union { int asInt[2]; double asDouble; } n;
  932. n.asDouble = value + 6755399441055744.0;
  933. #if JUCE_BIG_ENDIAN
  934. return n.asInt [1];
  935. #else
  936. return n.asInt [0];
  937. #endif
  938. }
  939. /** Fast floating-point-to-integer conversion.
  940. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  941. fine for values above zero, but negative numbers are rounded the wrong way.
  942. */
  943. inline int roundDoubleToIntAccurate (const double value) throw()
  944. {
  945. return roundDoubleToInt (value + 1.5e-8);
  946. }
  947. /** Fast floating-point-to-integer conversion.
  948. This is faster than using the normal c++ cast to convert a float to an int, and
  949. it will round the value to the nearest integer, rather than rounding it down
  950. like the normal cast does.
  951. Note that this routine gets its speed at the expense of some accuracy, and when
  952. rounding values whose floating point component is exactly 0.5, odd numbers and
  953. even numbers will be rounded up or down differently.
  954. */
  955. inline int roundFloatToInt (const float value) throw()
  956. {
  957. union { int asInt[2]; double asDouble; } n;
  958. n.asDouble = value + 6755399441055744.0;
  959. #if JUCE_BIG_ENDIAN
  960. return n.asInt [1];
  961. #else
  962. return n.asInt [0];
  963. #endif
  964. }
  965. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  966. /********* End of inlined file: juce_MathsFunctions.h *********/
  967. /********* Start of inlined file: juce_ByteOrder.h *********/
  968. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  969. #define __JUCE_BYTEORDER_JUCEHEADER__
  970. /** Contains static methods for converting the byte order between different
  971. endiannesses.
  972. */
  973. class JUCE_API ByteOrder
  974. {
  975. public:
  976. /** Swaps the upper and lower bytes of a 16-bit integer. */
  977. static uint16 swap (uint16 value);
  978. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  979. static uint32 swap (uint32 value);
  980. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  981. static uint64 swap (uint64 value);
  982. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  983. static uint16 swapIfBigEndian (const uint16 value);
  984. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  985. static uint32 swapIfBigEndian (const uint32 value);
  986. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  987. static uint64 swapIfBigEndian (const uint64 value);
  988. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  989. static uint16 swapIfLittleEndian (const uint16 value);
  990. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  991. static uint32 swapIfLittleEndian (const uint32 value);
  992. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  993. static uint64 swapIfLittleEndian (const uint64 value);
  994. /** Turns 4 bytes into a little-endian integer. */
  995. static uint32 littleEndianInt (const char* const bytes);
  996. /** Turns 2 bytes into a little-endian integer. */
  997. static uint16 littleEndianShort (const char* const bytes);
  998. /** Turns 4 bytes into a big-endian integer. */
  999. static uint32 bigEndianInt (const char* const bytes);
  1000. /** Turns 2 bytes into a big-endian integer. */
  1001. static uint16 bigEndianShort (const char* const bytes);
  1002. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1003. static int littleEndian24Bit (const char* const bytes);
  1004. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1005. static int bigEndian24Bit (const char* const bytes);
  1006. /** Copies a 24-bit number to 3 little-endian bytes. */
  1007. static void littleEndian24BitToChars (const int value, char* const destBytes);
  1008. /** Copies a 24-bit number to 3 big-endian bytes. */
  1009. static void bigEndian24BitToChars (const int value, char* const destBytes);
  1010. /** Returns true if the current CPU is big-endian. */
  1011. static bool isBigEndian();
  1012. };
  1013. #if JUCE_USE_INTRINSICS
  1014. #pragma intrinsic (_byteswap_ulong)
  1015. #endif
  1016. inline uint16 ByteOrder::swap (uint16 n)
  1017. {
  1018. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1019. return (uint16) _byteswap_ushort (n);
  1020. #else
  1021. return (uint16) ((n << 8) | (n >> 8));
  1022. #endif
  1023. }
  1024. inline uint32 ByteOrder::swap (uint32 n)
  1025. {
  1026. #if JUCE_MAC || JUCE_IPHONE
  1027. return OSSwapInt32 (n);
  1028. #elif JUCE_GCC
  1029. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1030. return n;
  1031. #elif JUCE_USE_INTRINSICS
  1032. return _byteswap_ulong (n);
  1033. #else
  1034. __asm {
  1035. mov eax, n
  1036. bswap eax
  1037. mov n, eax
  1038. }
  1039. return n;
  1040. #endif
  1041. }
  1042. inline uint64 ByteOrder::swap (uint64 value)
  1043. {
  1044. #if JUCE_MAC || JUCE_IPHONE
  1045. return OSSwapInt64 (value);
  1046. #elif JUCE_USE_INTRINSICS
  1047. return _byteswap_uint64 (value);
  1048. #else
  1049. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1050. #endif
  1051. }
  1052. #if JUCE_LITTLE_ENDIAN
  1053. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1054. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1055. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1056. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1057. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1058. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1059. inline uint32 ByteOrder::littleEndianInt (const char* const bytes) { return *(uint32*) bytes; }
  1060. inline uint16 ByteOrder::littleEndianShort (const char* const bytes) { return *(uint16*) bytes; }
  1061. inline uint32 ByteOrder::bigEndianInt (const char* const bytes) { return swap (*(uint32*) bytes); }
  1062. inline uint16 ByteOrder::bigEndianShort (const char* const bytes) { return swap (*(uint16*) bytes); }
  1063. inline bool ByteOrder::isBigEndian() { return false; }
  1064. #else
  1065. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1066. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1067. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1068. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1069. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1070. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1071. inline uint32 ByteOrder::littleEndianInt (const char* const bytes) { return swap (*(uint32*) bytes); }
  1072. inline uint16 ByteOrder::littleEndianShort (const char* const bytes) { return swap (*(uint16*) bytes); }
  1073. inline uint32 ByteOrder::bigEndianInt (const char* const bytes) { return *(uint32*) bytes; }
  1074. inline uint16 ByteOrder::bigEndianShort (const char* const bytes) { return *(uint16*) bytes; }
  1075. inline bool ByteOrder::isBigEndian() { return true; }
  1076. #endif
  1077. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1078. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1079. inline void ByteOrder::littleEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  1080. inline void ByteOrder::bigEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  1081. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1082. /********* End of inlined file: juce_ByteOrder.h *********/
  1083. /********* Start of inlined file: juce_Logger.h *********/
  1084. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1085. #define __JUCE_LOGGER_JUCEHEADER__
  1086. /********* Start of inlined file: juce_String.h *********/
  1087. #ifndef __JUCE_STRING_JUCEHEADER__
  1088. #define __JUCE_STRING_JUCEHEADER__
  1089. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1090. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1091. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1092. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1093. (in the default system encoding) as its internal representation.
  1094. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1095. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1096. literals in the T("abcd") macro, so that it all works nicely either way round.
  1097. */
  1098. #if JUCE_STRINGS_ARE_UNICODE
  1099. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1100. typedef juce_wchar tchar;
  1101. #define juce_tcharToWideChar(c) (c)
  1102. #else
  1103. #define JUCE_T(stringLiteral) (stringLiteral)
  1104. typedef char tchar;
  1105. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1106. #endif
  1107. #if ! JUCE_DONT_DEFINE_MACROS
  1108. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1109. or unicode.
  1110. If you write your string literals in the form T("xyz"), this will either be compiled
  1111. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1112. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1113. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1114. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1115. the juce/src directory) to avoid defining this macro. See the comments in
  1116. juce_withoutMacros.h for more info.
  1117. */
  1118. #define T(stringLiteral) JUCE_T(stringLiteral)
  1119. #endif
  1120. /**
  1121. A set of methods for manipulating characters and character strings, with
  1122. duplicate methods to handle 8-bit and unicode characters.
  1123. These are defined as wrappers around the basic C string handlers, to provide
  1124. a clean, cross-platform layer, (because various platforms differ in the
  1125. range of C library calls that they provide).
  1126. @see String
  1127. */
  1128. class JUCE_API CharacterFunctions
  1129. {
  1130. public:
  1131. static int length (const char* const s) throw();
  1132. static int length (const juce_wchar* const s) throw();
  1133. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1134. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1135. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1136. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1137. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1138. static void append (char* dest, const char* src) throw();
  1139. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1140. static int compare (const char* const s1, const char* const s2) throw();
  1141. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1142. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1143. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1144. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1145. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1146. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1147. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1148. static const char* find (const char* const haystack, const char* const needle) throw();
  1149. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1150. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1151. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1152. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1153. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1154. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1155. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1156. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1157. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1158. static int getIntValue (const char* const s) throw();
  1159. static int getIntValue (const juce_wchar* s) throw();
  1160. static int64 getInt64Value (const char* s) throw();
  1161. static int64 getInt64Value (const juce_wchar* s) throw();
  1162. static double getDoubleValue (const char* const s) throw();
  1163. static double getDoubleValue (const juce_wchar* const s) throw();
  1164. static char toUpperCase (const char character) throw();
  1165. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1166. static void toUpperCase (char* s) throw();
  1167. static void toUpperCase (juce_wchar* s) throw();
  1168. static bool isUpperCase (const char character) throw();
  1169. static bool isUpperCase (const juce_wchar character) throw();
  1170. static char toLowerCase (const char character) throw();
  1171. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1172. static void toLowerCase (char* s) throw();
  1173. static void toLowerCase (juce_wchar* s) throw();
  1174. static bool isLowerCase (const char character) throw();
  1175. static bool isLowerCase (const juce_wchar character) throw();
  1176. static bool isWhitespace (const char character) throw();
  1177. static bool isWhitespace (const juce_wchar character) throw();
  1178. static bool isDigit (const char character) throw();
  1179. static bool isDigit (const juce_wchar character) throw();
  1180. static bool isLetter (const char character) throw();
  1181. static bool isLetter (const juce_wchar character) throw();
  1182. static bool isLetterOrDigit (const char character) throw();
  1183. static bool isLetterOrDigit (const juce_wchar character) throw();
  1184. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1185. hex digit.
  1186. */
  1187. static int getHexDigitValue (const tchar digit) throw();
  1188. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1189. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1190. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1191. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1192. };
  1193. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1194. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1195. /**
  1196. The JUCE String class!
  1197. Using a reference-counted internal representation, these strings are fast
  1198. and efficient, and there are methods to do just about any operation you'll ever
  1199. dream of.
  1200. @see StringArray, StringPairArray
  1201. */
  1202. class JUCE_API String
  1203. {
  1204. public:
  1205. /** Creates an empty string.
  1206. @see empty
  1207. */
  1208. String() throw();
  1209. /** Creates a copy of another string. */
  1210. String (const String& other) throw();
  1211. /** Creates a string from a zero-terminated text string.
  1212. The string is assumed to be stored in the default system encoding.
  1213. */
  1214. String (const char* const text) throw();
  1215. /** Creates a string from an string of characters.
  1216. This will use up the the first maxChars characters of the string (or
  1217. less if the string is actually shorter)
  1218. */
  1219. String (const char* const text,
  1220. const int maxChars) throw();
  1221. /** Creates a string from a zero-terminated unicode text string. */
  1222. String (const juce_wchar* const unicodeText) throw();
  1223. /** Creates a string from a unicode text string.
  1224. This will use up the the first maxChars characters of the string (or
  1225. less if the string is actually shorter)
  1226. */
  1227. String (const juce_wchar* const unicodeText,
  1228. const int maxChars) throw();
  1229. /** Creates a string from a single character. */
  1230. static const String charToString (const tchar character) throw();
  1231. /** Destructor. */
  1232. ~String() throw();
  1233. /** This is an empty string that can be used whenever one is needed.
  1234. It's better to use this than String() because it explains what's going on
  1235. and is more efficient.
  1236. */
  1237. static const String empty;
  1238. /** Generates a probably-unique 32-bit hashcode from this string. */
  1239. int hashCode() const throw();
  1240. /** Generates a probably-unique 64-bit hashcode from this string. */
  1241. int64 hashCode64() const throw();
  1242. /** Returns the number of characters in the string. */
  1243. int length() const throw();
  1244. // Assignment and concatenation operators..
  1245. /** Replaces this string's contents with another string. */
  1246. const String& operator= (const tchar* const other) throw();
  1247. /** Replaces this string's contents with another string. */
  1248. const String& operator= (const String& other) throw();
  1249. /** Appends another string at the end of this one. */
  1250. const String& operator+= (const tchar* const textToAppend) throw();
  1251. /** Appends another string at the end of this one. */
  1252. const String& operator+= (const String& stringToAppend) throw();
  1253. /** Appends a character at the end of this string. */
  1254. const String& operator+= (const char characterToAppend) throw();
  1255. /** Appends a character at the end of this string. */
  1256. const String& operator+= (const juce_wchar characterToAppend) throw();
  1257. /** Appends a string at the end of this one.
  1258. @param textToAppend the string to add
  1259. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1260. */
  1261. void append (const tchar* const textToAppend,
  1262. const int maxCharsToTake) throw();
  1263. /** Appends a string at the end of this one.
  1264. @returns the concatenated string
  1265. */
  1266. const String operator+ (const String& stringToAppend) const throw();
  1267. /** Appends a string at the end of this one.
  1268. @returns the concatenated string
  1269. */
  1270. const String operator+ (const tchar* const textToAppend) const throw();
  1271. /** Appends a character at the end of this one.
  1272. @returns the concatenated string
  1273. */
  1274. const String operator+ (const tchar characterToAppend) const throw();
  1275. /** Appends a character at the end of this string. */
  1276. String& operator<< (const char n) throw();
  1277. /** Appends a character at the end of this string. */
  1278. String& operator<< (const juce_wchar n) throw();
  1279. /** Appends another string at the end of this one. */
  1280. String& operator<< (const char* const text) throw();
  1281. /** Appends another string at the end of this one. */
  1282. String& operator<< (const juce_wchar* const text) throw();
  1283. /** Appends another string at the end of this one. */
  1284. String& operator<< (const String& text) throw();
  1285. /** Appends a decimal number at the end of this string. */
  1286. String& operator<< (const short number) throw();
  1287. /** Appends a decimal number at the end of this string. */
  1288. String& operator<< (const int number) throw();
  1289. /** Appends a decimal number at the end of this string. */
  1290. String& operator<< (const unsigned int number) throw();
  1291. /** Appends a decimal number at the end of this string. */
  1292. String& operator<< (const long number) throw();
  1293. /** Appends a decimal number at the end of this string. */
  1294. String& operator<< (const unsigned long number) throw();
  1295. /** Appends a decimal number at the end of this string. */
  1296. String& operator<< (const float number) throw();
  1297. /** Appends a decimal number at the end of this string. */
  1298. String& operator<< (const double number) throw();
  1299. // Comparison methods..
  1300. /** Returns true if the string contains no characters.
  1301. Note that there's also an isNotEmpty() method to help write readable code.
  1302. @see containsNonWhitespaceChars()
  1303. */
  1304. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1305. /** Returns true if the string contains at least one character.
  1306. Note that there's also an isEmpty() method to help write readable code.
  1307. @see containsNonWhitespaceChars()
  1308. */
  1309. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1310. /** Case-sensitive comparison with another string. */
  1311. bool operator== (const String& other) const throw();
  1312. /** Case-sensitive comparison with another string. */
  1313. bool operator== (const tchar* const other) const throw();
  1314. /** Case-sensitive comparison with another string. */
  1315. bool operator!= (const String& other) const throw();
  1316. /** Case-sensitive comparison with another string. */
  1317. bool operator!= (const tchar* const other) const throw();
  1318. /** Case-insensitive comparison with another string. */
  1319. bool equalsIgnoreCase (const String& other) const throw();
  1320. /** Case-insensitive comparison with another string. */
  1321. bool equalsIgnoreCase (const tchar* const other) const throw();
  1322. /** Case-sensitive comparison with another string. */
  1323. bool operator> (const String& other) const throw();
  1324. /** Case-sensitive comparison with another string. */
  1325. bool operator< (const tchar* const other) const throw();
  1326. /** Case-sensitive comparison with another string. */
  1327. bool operator>= (const String& other) const throw();
  1328. /** Case-sensitive comparison with another string. */
  1329. bool operator<= (const tchar* const other) const throw();
  1330. /** Case-sensitive comparison with another string.
  1331. @returns 0 if the two strings are identical; negative if this string
  1332. comes before the other one alphabetically, or positive if it
  1333. comes after it.
  1334. */
  1335. int compare (const tchar* const other) const throw();
  1336. /** Case-insensitive comparison with another string.
  1337. @returns 0 if the two strings are identical; negative if this string
  1338. comes before the other one alphabetically, or positive if it
  1339. comes after it.
  1340. */
  1341. int compareIgnoreCase (const tchar* const other) const throw();
  1342. /** Lexicographic comparison with another string.
  1343. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1344. characters, making it good for sorting human-readable strings.
  1345. @returns 0 if the two strings are identical; negative if this string
  1346. comes before the other one alphabetically, or positive if it
  1347. comes after it.
  1348. */
  1349. int compareLexicographically (const tchar* const other) const throw();
  1350. /** Tests whether the string begins with another string.
  1351. Uses a case-sensitive comparison.
  1352. */
  1353. bool startsWith (const tchar* const text) const throw();
  1354. /** Tests whether the string begins with a particular character.
  1355. Uses a case-sensitive comparison.
  1356. */
  1357. bool startsWithChar (const tchar character) const throw();
  1358. /** Tests whether the string begins with another string.
  1359. Uses a case-insensitive comparison.
  1360. */
  1361. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1362. /** Tests whether the string ends with another string.
  1363. Uses a case-sensitive comparison.
  1364. */
  1365. bool endsWith (const tchar* const text) const throw();
  1366. /** Tests whether the string ends with a particular character.
  1367. Uses a case-sensitive comparison.
  1368. */
  1369. bool endsWithChar (const tchar character) const throw();
  1370. /** Tests whether the string ends with another string.
  1371. Uses a case-insensitive comparison.
  1372. */
  1373. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1374. /** Tests whether the string contains another substring.
  1375. Uses a case-sensitive comparison.
  1376. */
  1377. bool contains (const tchar* const text) const throw();
  1378. /** Tests whether the string contains a particular character.
  1379. Uses a case-sensitive comparison.
  1380. */
  1381. bool containsChar (const tchar character) const throw();
  1382. /** Tests whether the string contains another substring.
  1383. Uses a case-insensitive comparison.
  1384. */
  1385. bool containsIgnoreCase (const tchar* const text) const throw();
  1386. /** Tests whether the string contains another substring as a distict word.
  1387. @returns true if the string contains this word, surrounded by
  1388. non-alphanumeric characters
  1389. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1390. */
  1391. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1392. /** Tests whether the string contains another substring as a distict word.
  1393. @returns true if the string contains this word, surrounded by
  1394. non-alphanumeric characters
  1395. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1396. */
  1397. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1398. /** Finds an instance of another substring if it exists as a distict word.
  1399. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1400. then this will return the index of the start of the substring. If it isn't
  1401. found, then it will return -1
  1402. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1403. */
  1404. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1405. /** Finds an instance of another substring if it exists as a distict word.
  1406. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1407. then this will return the index of the start of the substring. If it isn't
  1408. found, then it will return -1
  1409. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1410. */
  1411. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1412. /** Looks for any of a set of characters in the string.
  1413. Uses a case-sensitive comparison.
  1414. @returns true if the string contains any of the characters from
  1415. the string that is passed in.
  1416. */
  1417. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1418. /** Looks for a set of characters in the string.
  1419. Uses a case-sensitive comparison.
  1420. @returns true if the all the characters in the string are also found in the
  1421. string that is passed in.
  1422. */
  1423. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1424. /** Returns true if this string contains any non-whitespace characters.
  1425. This will return false if the string contains only whitespace characters, or
  1426. if it's empty.
  1427. It is equivalent to calling "myString.trim().isNotEmpty()".
  1428. */
  1429. bool containsNonWhitespaceChars() const throw();
  1430. /** Returns true if the string matches this simple wildcard expression.
  1431. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1432. This isn't a full-blown regex though! The only wildcard characters supported
  1433. are "*" and "?". It's mainly intended for filename pattern matching.
  1434. */
  1435. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1436. // Substring location methods..
  1437. /** Searches for a character inside this string.
  1438. Uses a case-sensitive comparison.
  1439. @returns the index of the first occurrence of the character in this
  1440. string, or -1 if it's not found.
  1441. */
  1442. int indexOfChar (const tchar characterToLookFor) const throw();
  1443. /** Searches for a character inside this string.
  1444. Uses a case-sensitive comparison.
  1445. @param startIndex the index from which the search should proceed
  1446. @param characterToLookFor the character to look for
  1447. @returns the index of the first occurrence of the character in this
  1448. string, or -1 if it's not found.
  1449. */
  1450. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1451. /** Returns the index of the first character that matches one of the characters
  1452. passed-in to this method.
  1453. This scans the string, beginning from the startIndex supplied, and if it finds
  1454. a character that appears in the string charactersToLookFor, it returns its index.
  1455. If none of these characters are found, it returns -1.
  1456. If ignoreCase is true, the comparison will be case-insensitive.
  1457. @see indexOfChar, lastIndexOfAnyOf
  1458. */
  1459. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1460. const int startIndex = 0,
  1461. const bool ignoreCase = false) const throw();
  1462. /** Searches for a substring within this string.
  1463. Uses a case-sensitive comparison.
  1464. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1465. */
  1466. int indexOf (const tchar* const text) const throw();
  1467. /** Searches for a substring within this string.
  1468. Uses a case-sensitive comparison.
  1469. @param startIndex the index from which the search should proceed
  1470. @param textToLookFor the string to search for
  1471. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1472. */
  1473. int indexOf (const int startIndex,
  1474. const tchar* const textToLookFor) const throw();
  1475. /** Searches for a substring within this string.
  1476. Uses a case-insensitive comparison.
  1477. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1478. */
  1479. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1480. /** Searches for a substring within this string.
  1481. Uses a case-insensitive comparison.
  1482. @param startIndex the index from which the search should proceed
  1483. @param textToLookFor the string to search for
  1484. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1485. */
  1486. int indexOfIgnoreCase (const int startIndex,
  1487. const tchar* const textToLookFor) const throw();
  1488. /** Searches for a character inside this string (working backwards from the end of the string).
  1489. Uses a case-sensitive comparison.
  1490. @returns the index of the last occurrence of the character in this
  1491. string, or -1 if it's not found.
  1492. */
  1493. int lastIndexOfChar (const tchar character) const throw();
  1494. /** Searches for a substring inside this string (working backwards from the end of the string).
  1495. Uses a case-sensitive comparison.
  1496. @returns the index of the start of the last occurrence of the
  1497. substring within this string, or -1 if it's not found.
  1498. */
  1499. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1500. /** Searches for a substring inside this string (working backwards from the end of the string).
  1501. Uses a case-insensitive comparison.
  1502. @returns the index of the start of the last occurrence of the
  1503. substring within this string, or -1 if it's not found.
  1504. */
  1505. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1506. /** Returns the index of the last character in this string that matches one of the
  1507. characters passed-in to this method.
  1508. This scans the string backwards, starting from its end, and if it finds
  1509. a character that appears in the string charactersToLookFor, it returns its index.
  1510. If none of these characters are found, it returns -1.
  1511. If ignoreCase is true, the comparison will be case-insensitive.
  1512. @see lastIndexOf, indexOfAnyOf
  1513. */
  1514. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1515. const bool ignoreCase = false) const throw();
  1516. // Substring extraction and manipulation methods..
  1517. /** Returns the character at this index in the string.
  1518. No checks are made to see if the index is within a valid range, so be careful!
  1519. */
  1520. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1521. /** Returns a character from the string such that it can also be altered.
  1522. This can be used as a way of easily changing characters in the string.
  1523. Note that the index passed-in is not checked to see whether it's in-range, so
  1524. be careful when using this.
  1525. */
  1526. tchar& operator[] (const int index) throw();
  1527. /** Returns the final character of the string.
  1528. If the string is empty this will return 0.
  1529. */
  1530. tchar getLastCharacter() const throw();
  1531. /** Returns a subsection of the string.
  1532. If the range specified is beyond the limits of the string, as much as
  1533. possible is returned.
  1534. @param startIndex the index of the start of the substring needed
  1535. @param endIndex all characters from startIndex up to (but not including)
  1536. this index are returned
  1537. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1538. */
  1539. const String substring (int startIndex,
  1540. int endIndex) const throw();
  1541. /** Returns a section of the string, starting from a given position.
  1542. @param startIndex the first character to include. If this is beyond the end
  1543. of the string, an empty string is returned. If it is zero or
  1544. less, the whole string is returned.
  1545. @returns the substring from startIndex up to the end of the string
  1546. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1547. */
  1548. const String substring (const int startIndex) const throw();
  1549. /** Returns a version of this string with a number of characters removed
  1550. from the end.
  1551. @param numberToDrop the number of characters to drop from the end of the
  1552. string. If this is greater than the length of the string,
  1553. an empty string will be returned. If zero or less, the
  1554. original string will be returned.
  1555. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1556. */
  1557. const String dropLastCharacters (const int numberToDrop) const throw();
  1558. /** Returns a number of characters from the end of the string.
  1559. This returns the last numCharacters characters from the end of the string. If the
  1560. string is shorter than numCharacters, the whole string is returned.
  1561. @see substring, dropLastCharacters, getLastCharacter
  1562. */
  1563. const String getLastCharacters (const int numCharacters) const throw();
  1564. /** Returns a section of the string starting from a given substring.
  1565. This will search for the first occurrence of the given substring, and
  1566. return the section of the string starting from the point where this is
  1567. found (optionally not including the substring itself).
  1568. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1569. fromFirstOccurrenceOf ("34", false) would return "56".
  1570. If the substring isn't found, the method will return an empty string.
  1571. If ignoreCase is true, the comparison will be case-insensitive.
  1572. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1573. */
  1574. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1575. const bool includeSubStringInResult,
  1576. const bool ignoreCase) const throw();
  1577. /** Returns a section of the string starting from the last occurrence of a given substring.
  1578. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1579. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1580. return the whole of the original string.
  1581. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1582. */
  1583. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1584. const bool includeSubStringInResult,
  1585. const bool ignoreCase) const throw();
  1586. /** Returns the start of this string, up to the first occurrence of a substring.
  1587. This will search for the first occurrence of a given substring, and then
  1588. return a copy of the string, up to the position of this substring,
  1589. optionally including or excluding the substring itself in the result.
  1590. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1591. upTo ("34", true) would return "1234".
  1592. If the substring isn't found, this will return the whole of the original string.
  1593. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1594. */
  1595. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1596. const bool includeSubStringInResult,
  1597. const bool ignoreCase) const throw();
  1598. /** Returns the start of this string, up to the last occurrence of a substring.
  1599. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1600. If the substring isn't found, this will return an empty string.
  1601. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1602. */
  1603. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1604. const bool includeSubStringInResult,
  1605. const bool ignoreCase) const throw();
  1606. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1607. const String trim() const throw();
  1608. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1609. const String trimStart() const throw();
  1610. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1611. const String trimEnd() const throw();
  1612. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1613. Characters are removed from the start of the string until it finds one that is not in the
  1614. specified set, and then it stops.
  1615. @param charactersToTrim the set of characters to remove. This must not be null.
  1616. @see trim, trimStart, trimCharactersAtEnd
  1617. */
  1618. const String trimCharactersAtStart (const tchar* charactersToTrim) const throw();
  1619. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1620. Characters are removed from the end of the string until it finds one that is not in the
  1621. specified set, and then it stops.
  1622. @param charactersToTrim the set of characters to remove. This must not be null.
  1623. @see trim, trimEnd, trimCharactersAtStart
  1624. */
  1625. const String trimCharactersAtEnd (const tchar* charactersToTrim) const throw();
  1626. /** Returns an upper-case version of this string. */
  1627. const String toUpperCase() const throw();
  1628. /** Returns an lower-case version of this string. */
  1629. const String toLowerCase() const throw();
  1630. /** Replaces a sub-section of the string with another string.
  1631. This will return a copy of this string, with a set of characters
  1632. from startIndex to startIndex + numCharsToReplace removed, and with
  1633. a new string inserted in their place.
  1634. Note that this is a const method, and won't alter the string itself.
  1635. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1636. it will be constrained to a valid range.
  1637. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1638. characters will be taken out.
  1639. @param stringToInsert the new string to insert at startIndex after the characters have been
  1640. removed.
  1641. */
  1642. const String replaceSection (int startIndex,
  1643. int numCharactersToReplace,
  1644. const tchar* const stringToInsert) const throw();
  1645. /** Replaces all occurrences of a substring with another string.
  1646. Returns a copy of this string, with any occurrences of stringToReplace
  1647. swapped for stringToInsertInstead.
  1648. Note that this is a const method, and won't alter the string itself.
  1649. */
  1650. const String replace (const tchar* const stringToReplace,
  1651. const tchar* const stringToInsertInstead,
  1652. const bool ignoreCase = false) const throw();
  1653. /** Returns a string with all occurrences of a character replaced with a different one. */
  1654. const String replaceCharacter (const tchar characterToReplace,
  1655. const tchar characterToInsertInstead) const throw();
  1656. /** Replaces a set of characters with another set.
  1657. Returns a string in which each character from charactersToReplace has been replaced
  1658. by the character at the equivalent position in newCharacters (so the two strings
  1659. passed in must be the same length).
  1660. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1661. Note that this is a const method, and won't affect the string itself.
  1662. */
  1663. const String replaceCharacters (const String& charactersToReplace,
  1664. const tchar* const charactersToInsertInstead) const throw();
  1665. /** Returns a version of this string that only retains a fixed set of characters.
  1666. This will return a copy of this string, omitting any characters which are not
  1667. found in the string passed-in.
  1668. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1669. Note that this is a const method, and won't alter the string itself.
  1670. */
  1671. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1672. /** Returns a version of this string with a set of characters removed.
  1673. This will return a copy of this string, omitting any characters which are
  1674. found in the string passed-in.
  1675. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1676. Note that this is a const method, and won't alter the string itself.
  1677. */
  1678. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1679. /** Returns a section from the start of the string that only contains a certain set of characters.
  1680. This returns the leftmost section of the string, up to (and not including) the
  1681. first character that doesn't appear in the string passed in.
  1682. */
  1683. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1684. /** Returns a section from the start of the string that only contains a certain set of characters.
  1685. This returns the leftmost section of the string, up to (and not including) the
  1686. first character that occurs in the string passed in.
  1687. */
  1688. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1689. /** Checks whether the string might be in quotation marks.
  1690. @returns true if the string begins with a quote character (either a double or single quote).
  1691. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1692. @see unquoted, quoted
  1693. */
  1694. bool isQuotedString() const throw();
  1695. /** Removes quotation marks from around the string, (if there are any).
  1696. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1697. at the ends of the string are not affected. If there aren't any quotes, the original string
  1698. is returned.
  1699. Note that this is a const method, and won't alter the string itself.
  1700. @see isQuotedString, quoted
  1701. */
  1702. const String unquoted() const throw();
  1703. /** Adds quotation marks around a string.
  1704. This will return a copy of the string with a quote at the start and end, (but won't
  1705. add the quote if there's already one there, so it's safe to call this on strings that
  1706. may already have quotes around them).
  1707. Note that this is a const method, and won't alter the string itself.
  1708. @param quoteCharacter the character to add at the start and end
  1709. @see isQuotedString, unquoted
  1710. */
  1711. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1712. /** Writes text into this string, using printf style-arguments.
  1713. This will replace the contents of the string with the output of this
  1714. formatted printf.
  1715. Note that using the %s token with a juce string is probably a bad idea, as
  1716. this may expect differect encodings on different platforms.
  1717. @see formatted
  1718. */
  1719. void printf (const tchar* const format, ...) throw();
  1720. /** Returns a string, created using arguments in the style of printf.
  1721. This will return a string which is the result of a sprintf using the
  1722. arguments passed-in.
  1723. Note that using the %s token with a juce string is probably a bad idea, as
  1724. this may expect differect encodings on different platforms.
  1725. @see printf, vprintf
  1726. */
  1727. static const String formatted (const tchar* const format, ...) throw();
  1728. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1729. This will replace the contents of the string with the output of this
  1730. formatted printf. Used by other methods, this is public in case it's
  1731. useful for other purposes where you want to pass a va_list through directly.
  1732. Note that using the %s token with a juce string is probably a bad idea, as
  1733. this may expect differect encodings on different platforms.
  1734. @see printf, formatted
  1735. */
  1736. void vprintf (const tchar* const format, va_list& args) throw();
  1737. /** Creates a string which is a version of a string repeated and joined together.
  1738. @param stringToRepeat the string to repeat
  1739. @param numberOfTimesToRepeat how many times to repeat it
  1740. */
  1741. static const String repeatedString (const tchar* const stringToRepeat,
  1742. int numberOfTimesToRepeat) throw();
  1743. /** Creates a string from data in an unknown format.
  1744. This looks at some binary data and tries to guess whether it's Unicode
  1745. or 8-bit characters, then returns a string that represents it correctly.
  1746. Should be able to handle Unicode endianness correctly, by looking at
  1747. the first two bytes.
  1748. */
  1749. static const String createStringFromData (const void* const data,
  1750. const int size) throw();
  1751. // Numeric conversions..
  1752. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1753. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1754. */
  1755. explicit String (const int decimalInteger) throw();
  1756. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1757. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1758. */
  1759. explicit String (const unsigned int decimalInteger) throw();
  1760. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1761. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1762. */
  1763. explicit String (const short decimalInteger) throw();
  1764. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1765. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1766. */
  1767. explicit String (const unsigned short decimalInteger) throw();
  1768. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1769. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1770. */
  1771. explicit String (const int64 largeIntegerValue) throw();
  1772. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1773. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1774. */
  1775. explicit String (const uint64 largeIntegerValue) throw();
  1776. /** Creates a string representing this floating-point number.
  1777. @param floatValue the value to convert to a string
  1778. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1779. decimal places, and will not use exponent notation. If 0 or
  1780. less, it will use exponent notation if necessary.
  1781. @see getDoubleValue, getIntValue
  1782. */
  1783. explicit String (const float floatValue,
  1784. const int numberOfDecimalPlaces = 0) throw();
  1785. /** Creates a string representing this floating-point number.
  1786. @param doubleValue the value to convert to a string
  1787. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1788. decimal places, and will not use exponent notation. If 0 or
  1789. less, it will use exponent notation if necessary.
  1790. @see getFloatValue, getIntValue
  1791. */
  1792. explicit String (const double doubleValue,
  1793. const int numberOfDecimalPlaces = 0) throw();
  1794. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1795. @returns the value of the string as a 32 bit signed base-10 integer.
  1796. @see getTrailingIntValue, getHexValue32, getHexValue64
  1797. */
  1798. int getIntValue() const throw();
  1799. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1800. @returns the value of the string as a 64 bit signed base-10 integer.
  1801. */
  1802. int64 getLargeIntValue() const throw();
  1803. /** Parses a decimal number from the end of the string.
  1804. This will look for a value at the end of the string.
  1805. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1806. Negative numbers are not handled, so "xyz-5" returns 5.
  1807. @see getIntValue
  1808. */
  1809. int getTrailingIntValue() const throw();
  1810. /** Parses this string as a floating point number.
  1811. @returns the value of the string as a 32-bit floating point value.
  1812. @see getDoubleValue
  1813. */
  1814. float getFloatValue() const throw();
  1815. /** Parses this string as a floating point number.
  1816. @returns the value of the string as a 64-bit floating point value.
  1817. @see getFloatValue
  1818. */
  1819. double getDoubleValue() const throw();
  1820. /** Parses the string as a hexadecimal number.
  1821. Non-hexadecimal characters in the string are ignored.
  1822. If the string contains too many characters, then the lowest significant
  1823. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1824. @returns a 32-bit number which is the value of the string in hex.
  1825. */
  1826. int getHexValue32() const throw();
  1827. /** Parses the string as a hexadecimal number.
  1828. Non-hexadecimal characters in the string are ignored.
  1829. If the string contains too many characters, then the lowest significant
  1830. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1831. @returns a 64-bit number which is the value of the string in hex.
  1832. */
  1833. int64 getHexValue64() const throw();
  1834. /** Creates a string representing this 32-bit value in hexadecimal. */
  1835. static const String toHexString (const int number) throw();
  1836. /** Creates a string representing this 64-bit value in hexadecimal. */
  1837. static const String toHexString (const int64 number) throw();
  1838. /** Creates a string representing this 16-bit value in hexadecimal. */
  1839. static const String toHexString (const short number) throw();
  1840. /** Creates a string containing a hex dump of a block of binary data.
  1841. @param data the binary data to use as input
  1842. @param size how many bytes of data to use
  1843. @param groupSize how many bytes are grouped together before inserting a
  1844. space into the output. e.g. group size 0 has no spaces,
  1845. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1846. like "bea1 c2ff".
  1847. */
  1848. static const String toHexString (const unsigned char* data,
  1849. const int size,
  1850. const int groupSize = 1) throw();
  1851. // Casting to character arrays..
  1852. #if JUCE_STRINGS_ARE_UNICODE
  1853. /** Returns a version of this string using the default 8-bit system encoding.
  1854. Because it returns a reference to the string's internal data, the pointer
  1855. that is returned must not be stored anywhere, as it can be deleted whenever the
  1856. string changes.
  1857. */
  1858. operator const char*() const throw();
  1859. /** Returns a unicode version of this string.
  1860. Because it returns a reference to the string's internal data, the pointer
  1861. that is returned must not be stored anywhere, as it can be deleted whenever the
  1862. string changes.
  1863. */
  1864. inline operator const juce_wchar*() const throw() { return text->text; }
  1865. #else
  1866. /** Returns a version of this string using the default 8-bit system encoding.
  1867. Because it returns a reference to the string's internal data, the pointer
  1868. that is returned must not be stored anywhere, as it can be deleted whenever the
  1869. string changes.
  1870. */
  1871. inline operator const char*() const throw() { return text->text; }
  1872. /** Returns a unicode version of this string.
  1873. Because it returns a reference to the string's internal data, the pointer
  1874. that is returned must not be stored anywhere, as it can be deleted whenever the
  1875. string changes.
  1876. */
  1877. operator const juce_wchar*() const throw();
  1878. #endif
  1879. /** Copies the string to a buffer.
  1880. @param destBuffer the place to copy it to
  1881. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1882. not including the tailing zero, so this shouldn't be
  1883. larger than the size of your destination buffer - 1
  1884. */
  1885. void copyToBuffer (char* const destBuffer,
  1886. const int maxCharsToCopy) const throw();
  1887. /** Copies the string to a unicode buffer.
  1888. @param destBuffer the place to copy it to
  1889. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1890. not including the tailing zero, so this shouldn't be
  1891. larger than the size of your destination buffer - 1
  1892. */
  1893. void copyToBuffer (juce_wchar* const destBuffer,
  1894. const int maxCharsToCopy) const throw();
  1895. /** Copies the string to a buffer as UTF-8 characters.
  1896. Returns the number of bytes copied to the buffer, including the terminating null
  1897. character.
  1898. @param destBuffer the place to copy it to; if this is a null pointer,
  1899. the method just returns the number of bytes required
  1900. (including the terminating null character).
  1901. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1902. string won't fit, it'll put in as many as it can while
  1903. still allowing for a terminating null char at the end,
  1904. and will return the number of bytes that were actually
  1905. used. If this value is < 0, no limit is used.
  1906. */
  1907. int copyToUTF8 (uint8* const destBuffer, const int maxBufferSizeBytes = 0x7fffffff) const throw();
  1908. /** Returns a pointer to a UTF-8 version of this string.
  1909. Because it returns a reference to the string's internal data, the pointer
  1910. that is returned must not be stored anywhere, as it can be deleted whenever the
  1911. string changes.
  1912. */
  1913. const char* toUTF8() const throw();
  1914. /** Creates a String from a UTF-8 encoded buffer.
  1915. If the size is < 0, it'll keep reading until it hits a zero.
  1916. */
  1917. static const String fromUTF8 (const uint8* const utf8buffer,
  1918. int bufferSizeBytes = -1) throw();
  1919. /** Increases the string's internally allocated storage.
  1920. Although the string's contents won't be affected by this call, it will
  1921. increase the amount of memory allocated internally for the string to grow into.
  1922. If you're about to make a large number of calls to methods such
  1923. as += or <<, it's more efficient to preallocate enough extra space
  1924. beforehand, so that these methods won't have to keep resizing the string
  1925. to append the extra characters.
  1926. @param numCharsNeeded the number of characters to allocate storage for. If this
  1927. value is less than the currently allocated size, it will
  1928. have no effect.
  1929. */
  1930. void preallocateStorage (const int numCharsNeeded) throw();
  1931. /** A helper class to improve performance when concatenating many large strings
  1932. together.
  1933. Because appending one string to another involves measuring the length of
  1934. both strings, repeatedly doing this for many long strings will become
  1935. an exponentially slow operation. This class uses some internal state to
  1936. avoid that, so that each append operation only needs to measure the length
  1937. of the appended string.
  1938. */
  1939. class JUCE_API Concatenator
  1940. {
  1941. public:
  1942. Concatenator (String& stringToAppendTo);
  1943. ~Concatenator();
  1944. void append (const String& s);
  1945. private:
  1946. String& result;
  1947. int nextIndex;
  1948. Concatenator (const Concatenator&);
  1949. const Concatenator& operator= (const Concatenator&);
  1950. };
  1951. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1952. private:
  1953. struct InternalRefCountedStringHolder
  1954. {
  1955. int refCount;
  1956. int allocatedNumChars;
  1957. #if JUCE_STRINGS_ARE_UNICODE
  1958. wchar_t text[1];
  1959. #else
  1960. char text[1];
  1961. #endif
  1962. };
  1963. InternalRefCountedStringHolder* text;
  1964. static InternalRefCountedStringHolder emptyString;
  1965. // internal constructor that preallocates a certain amount of memory
  1966. String (const int numChars, const int dummyVariable) throw();
  1967. void deleteInternal() throw();
  1968. void createInternal (const int numChars) throw();
  1969. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1970. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1971. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1972. void dupeInternalIfMultiplyReferenced() throw();
  1973. };
  1974. /** Global operator to allow a String to be appended to a string literal.
  1975. This allows the use of expressions such as "abc" + String (x)
  1976. @see String
  1977. */
  1978. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1979. const String& string2) throw();
  1980. /** Global operator to allow a String to be appended to a string literal.
  1981. This allows the use of expressions such as "abc" + String (x)
  1982. @see String
  1983. */
  1984. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1985. const String& string2) throw();
  1986. #endif // __JUCE_STRING_JUCEHEADER__
  1987. /********* End of inlined file: juce_String.h *********/
  1988. /**
  1989. Acts as an application-wide logging class.
  1990. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1991. method and this will then be used by all calls to writeToLog.
  1992. The logger class also contains methods for writing messages to the debugger's
  1993. output stream.
  1994. @see FileLogger
  1995. */
  1996. class JUCE_API Logger
  1997. {
  1998. public:
  1999. /** Destructor. */
  2000. virtual ~Logger();
  2001. /** Sets the current logging class to use.
  2002. Note that the object passed in won't be deleted when no longer needed.
  2003. A null pointer can be passed-in to disable any logging.
  2004. If deleteOldLogger is set to true, the existing logger will be
  2005. deleted (if there is one).
  2006. */
  2007. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2008. const bool deleteOldLogger = false);
  2009. /** Writes a string to the current logger.
  2010. This will pass the string to the logger's logMessage() method if a logger
  2011. has been set.
  2012. @see logMessage
  2013. */
  2014. static void JUCE_CALLTYPE writeToLog (const String& message);
  2015. /** Writes a message to the standard error stream.
  2016. This can be called directly, or by using the DBG() macro in
  2017. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2018. */
  2019. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  2020. /** Writes a message to the standard error stream.
  2021. This can be called directly, or by using the DBG_PRINTF() macro in
  2022. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2023. */
  2024. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  2025. protected:
  2026. Logger();
  2027. /** This is overloaded by subclasses to implement custom logging behaviour.
  2028. @see setCurrentLogger
  2029. */
  2030. virtual void logMessage (const String& message) = 0;
  2031. };
  2032. #endif // __JUCE_LOGGER_JUCEHEADER__
  2033. /********* End of inlined file: juce_Logger.h *********/
  2034. END_JUCE_NAMESPACE
  2035. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2036. /********* End of inlined file: juce_StandardHeader.h *********/
  2037. BEGIN_JUCE_NAMESPACE
  2038. #if JUCE_MSVC
  2039. // this is set explicitly in case the app is using a different packing size.
  2040. #pragma pack (push, 8)
  2041. #pragma warning (push)
  2042. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2043. #endif
  2044. #if JUCE_MAC || JUCE_IPHONE
  2045. #pragma align=natural
  2046. #endif
  2047. #define JUCE_PUBLIC_INCLUDES
  2048. // this is where all the class header files get brought in..
  2049. /********* Start of inlined file: juce_core_includes.h *********/
  2050. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2051. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2052. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2053. /********* Start of inlined file: juce_Array.h *********/
  2054. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2055. #define __JUCE_ARRAY_JUCEHEADER__
  2056. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2057. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2058. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2059. /** The default size of chunk in which arrays increase their storage.
  2060. Used by ArrayAllocationBase and its subclasses.
  2061. */
  2062. const int juceDefaultArrayGranularity = 8;
  2063. /**
  2064. Implements some basic array storage allocation functions.
  2065. This class isn't really for public use - it's used by the other
  2066. array classes, but might come in handy for some purposes.
  2067. @see Array, OwnedArray, ReferenceCountedArray
  2068. */
  2069. template <class ElementType>
  2070. class ArrayAllocationBase
  2071. {
  2072. public:
  2073. /** Creates an empty array.
  2074. @param granularity_ this is the size of increment by which the internal storage
  2075. will be increased.
  2076. */
  2077. ArrayAllocationBase (const int granularity_) throw()
  2078. : elements (0),
  2079. numAllocated (0),
  2080. granularity (granularity_)
  2081. {
  2082. jassert (granularity > 0);
  2083. }
  2084. /** Destructor. */
  2085. ~ArrayAllocationBase()
  2086. {
  2087. delete[] elements;
  2088. }
  2089. /** Changes the amount of storage allocated.
  2090. This will retain any data currently held in the array, and either add or
  2091. remove extra space at the end.
  2092. @param numElements the number of elements that are needed
  2093. */
  2094. void setAllocatedSize (const int numElements) throw()
  2095. {
  2096. if (numAllocated != numElements)
  2097. {
  2098. if (numElements > 0)
  2099. {
  2100. ElementType* const newElements = new ElementType [numElements];
  2101. const int itemsToRetain = jmin (numElements, numAllocated);
  2102. for (int i = 0; i < itemsToRetain; ++i)
  2103. newElements[i] = elements[i];
  2104. delete[] elements;
  2105. elements = newElements;
  2106. }
  2107. else
  2108. {
  2109. delete[] elements;
  2110. elements = 0;
  2111. }
  2112. numAllocated = numElements;
  2113. }
  2114. }
  2115. /** Increases the amount of storage allocated if it is less than a given amount.
  2116. This will retain any data currently held in the array, but will add
  2117. extra space at the end to make sure there it's at least as big as the size
  2118. passed in. If it's already bigger, no action is taken.
  2119. @param minNumElements the minimum number of elements that are needed
  2120. */
  2121. void ensureAllocatedSize (int minNumElements) throw()
  2122. {
  2123. if (minNumElements > numAllocated)
  2124. {
  2125. // for arrays with small granularity that get big, start
  2126. // increasing the size in bigger jumps
  2127. if (minNumElements > (granularity << 6))
  2128. {
  2129. minNumElements += (minNumElements / granularity);
  2130. if (minNumElements > (granularity << 8))
  2131. minNumElements += granularity << 6;
  2132. else
  2133. minNumElements += granularity << 5;
  2134. }
  2135. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2136. }
  2137. }
  2138. ElementType* elements;
  2139. int numAllocated, granularity;
  2140. private:
  2141. ArrayAllocationBase (const ArrayAllocationBase&);
  2142. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2143. };
  2144. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2145. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2146. /********* Start of inlined file: juce_ElementComparator.h *********/
  2147. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2148. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2149. /**
  2150. Sorts a range of elements in an array.
  2151. The comparator object that is passed-in must define a public method with the following
  2152. signature:
  2153. @code
  2154. int compareElements (ElementType first, ElementType second);
  2155. @endcode
  2156. ..and this method must return:
  2157. - a value of < 0 if the first comes before the second
  2158. - a value of 0 if the two objects are equivalent
  2159. - a value of > 0 if the second comes before the first
  2160. To improve performance, the compareElements() method can be declared as static or const.
  2161. @param comparator an object which defines a compareElements() method
  2162. @param array the array to sort
  2163. @param firstElement the index of the first element of the range to be sorted
  2164. @param lastElement the index of the last element in the range that needs
  2165. sorting (this is inclusive)
  2166. @param retainOrderOfEquivalentItems if true, the order of items that the
  2167. comparator deems the same will be maintained - this will be
  2168. a slower algorithm than if they are allowed to be moved around.
  2169. @see sortArrayRetainingOrder
  2170. */
  2171. template <class ElementType, class ElementComparator>
  2172. static void sortArray (ElementComparator& comparator,
  2173. ElementType* const array,
  2174. int firstElement,
  2175. int lastElement,
  2176. const bool retainOrderOfEquivalentItems)
  2177. {
  2178. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2179. // avoids getting warning messages about the parameter being unused
  2180. if (lastElement > firstElement)
  2181. {
  2182. if (retainOrderOfEquivalentItems)
  2183. {
  2184. for (int i = firstElement; i < lastElement; ++i)
  2185. {
  2186. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2187. {
  2188. const ElementType temp = array [i];
  2189. array [i] = array[i + 1];
  2190. array [i + 1] = temp;
  2191. if (i > firstElement)
  2192. i -= 2;
  2193. }
  2194. }
  2195. }
  2196. else
  2197. {
  2198. int fromStack[30], toStack[30];
  2199. int stackIndex = 0;
  2200. for (;;)
  2201. {
  2202. const int size = (lastElement - firstElement) + 1;
  2203. if (size <= 8)
  2204. {
  2205. int j = lastElement;
  2206. int maxIndex;
  2207. while (j > firstElement)
  2208. {
  2209. maxIndex = firstElement;
  2210. for (int k = firstElement + 1; k <= j; ++k)
  2211. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2212. maxIndex = k;
  2213. const ElementType temp = array [maxIndex];
  2214. array [maxIndex] = array[j];
  2215. array [j] = temp;
  2216. --j;
  2217. }
  2218. }
  2219. else
  2220. {
  2221. const int mid = firstElement + (size >> 1);
  2222. ElementType temp = array [mid];
  2223. array [mid] = array [firstElement];
  2224. array [firstElement] = temp;
  2225. int i = firstElement;
  2226. int j = lastElement + 1;
  2227. for (;;)
  2228. {
  2229. while (++i <= lastElement
  2230. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2231. {}
  2232. while (--j > firstElement
  2233. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2234. {}
  2235. if (j < i)
  2236. break;
  2237. temp = array[i];
  2238. array[i] = array[j];
  2239. array[j] = temp;
  2240. }
  2241. temp = array [firstElement];
  2242. array [firstElement] = array[j];
  2243. array [j] = temp;
  2244. if (j - 1 - firstElement >= lastElement - i)
  2245. {
  2246. if (firstElement + 1 < j)
  2247. {
  2248. fromStack [stackIndex] = firstElement;
  2249. toStack [stackIndex] = j - 1;
  2250. ++stackIndex;
  2251. }
  2252. if (i < lastElement)
  2253. {
  2254. firstElement = i;
  2255. continue;
  2256. }
  2257. }
  2258. else
  2259. {
  2260. if (i < lastElement)
  2261. {
  2262. fromStack [stackIndex] = i;
  2263. toStack [stackIndex] = lastElement;
  2264. ++stackIndex;
  2265. }
  2266. if (firstElement + 1 < j)
  2267. {
  2268. lastElement = j - 1;
  2269. continue;
  2270. }
  2271. }
  2272. }
  2273. if (--stackIndex < 0)
  2274. break;
  2275. jassert (stackIndex < numElementsInArray (fromStack));
  2276. firstElement = fromStack [stackIndex];
  2277. lastElement = toStack [stackIndex];
  2278. }
  2279. }
  2280. }
  2281. }
  2282. /**
  2283. Searches a sorted array of elements, looking for the index at which a specified value
  2284. should be inserted for it to be in the correct order.
  2285. The comparator object that is passed-in must define a public method with the following
  2286. signature:
  2287. @code
  2288. int compareElements (ElementType first, ElementType second);
  2289. @endcode
  2290. ..and this method must return:
  2291. - a value of < 0 if the first comes before the second
  2292. - a value of 0 if the two objects are equivalent
  2293. - a value of > 0 if the second comes before the first
  2294. To improve performance, the compareElements() method can be declared as static or const.
  2295. @param comparator an object which defines a compareElements() method
  2296. @param array the array to search
  2297. @param newElement the value that is going to be inserted
  2298. @param firstElement the index of the first element to search
  2299. @param lastElement the index of the last element in the range (this is non-inclusive)
  2300. */
  2301. template <class ElementType, class ElementComparator>
  2302. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2303. ElementType* const array,
  2304. const ElementType newElement,
  2305. int firstElement,
  2306. int lastElement)
  2307. {
  2308. jassert (firstElement <= lastElement);
  2309. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2310. // avoids getting warning messages about the parameter being unused
  2311. while (firstElement < lastElement)
  2312. {
  2313. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2314. {
  2315. ++firstElement;
  2316. break;
  2317. }
  2318. else
  2319. {
  2320. const int halfway = (firstElement + lastElement) >> 1;
  2321. if (halfway == firstElement)
  2322. {
  2323. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2324. ++firstElement;
  2325. break;
  2326. }
  2327. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2328. {
  2329. firstElement = halfway;
  2330. }
  2331. else
  2332. {
  2333. lastElement = halfway;
  2334. }
  2335. }
  2336. }
  2337. return firstElement;
  2338. }
  2339. /**
  2340. A simple ElementComparator class that can be used to sort an array of
  2341. integer primitive objects.
  2342. Example: @code
  2343. Array <int> myArray;
  2344. IntegerElementComparator<int> sorter;
  2345. myArray.sort (sorter);
  2346. @endcode
  2347. For floating point values, see the FloatElementComparator class instead.
  2348. @see FloatElementComparator, ElementComparator
  2349. */
  2350. template <class ElementType>
  2351. class IntegerElementComparator
  2352. {
  2353. public:
  2354. static int compareElements (const ElementType first,
  2355. const ElementType second) throw()
  2356. {
  2357. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2358. }
  2359. };
  2360. /**
  2361. A simple ElementComparator class that can be used to sort an array of numeric
  2362. double or floating point primitive objects.
  2363. Example: @code
  2364. Array <double> myArray;
  2365. FloatElementComparator<double> sorter;
  2366. myArray.sort (sorter);
  2367. @endcode
  2368. For integer values, see the IntegerElementComparator class instead.
  2369. @see IntegerElementComparator, ElementComparator
  2370. */
  2371. template <class ElementType>
  2372. class FloatElementComparator
  2373. {
  2374. public:
  2375. static int compareElements (const ElementType first,
  2376. const ElementType second) throw()
  2377. {
  2378. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2379. }
  2380. };
  2381. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2382. /********* End of inlined file: juce_ElementComparator.h *********/
  2383. /********* Start of inlined file: juce_CriticalSection.h *********/
  2384. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2385. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2386. /**
  2387. Prevents multiple threads from accessing shared objects at the same time.
  2388. @see ScopedLock, Thread, InterProcessLock
  2389. */
  2390. class JUCE_API CriticalSection
  2391. {
  2392. public:
  2393. /**
  2394. Creates a CriticalSection object
  2395. */
  2396. CriticalSection() throw();
  2397. /** Destroys a CriticalSection object.
  2398. If the critical section is deleted whilst locked, its subsequent behaviour
  2399. is unpredictable.
  2400. */
  2401. ~CriticalSection() throw();
  2402. /** Locks this critical section.
  2403. If the lock is currently held by another thread, this will wait until it
  2404. becomes free.
  2405. If the lock is already held by the caller thread, the method returns immediately.
  2406. @see exit, ScopedLock
  2407. */
  2408. void enter() const throw();
  2409. /** Attempts to lock this critical section without blocking.
  2410. This method behaves identically to CriticalSection::enter, except that the caller thread
  2411. does not wait if the lock is currently held by another thread but returns false immediately.
  2412. @returns false if the lock is currently held by another thread, true otherwise.
  2413. @see enter
  2414. */
  2415. bool tryEnter() const throw();
  2416. /** Releases the lock.
  2417. If the caller thread hasn't got the lock, this can have unpredictable results.
  2418. If the enter() method has been called multiple times by the thread, each
  2419. call must be matched by a call to exit() before other threads will be allowed
  2420. to take over the lock.
  2421. @see enter, ScopedLock
  2422. */
  2423. void exit() const throw();
  2424. juce_UseDebuggingNewOperator
  2425. private:
  2426. #if JUCE_WIN32
  2427. #if JUCE_64BIT
  2428. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2429. // block of memory here that's big enough to be used internally as a windows critical
  2430. // section object.
  2431. uint8 internal [44];
  2432. #else
  2433. uint8 internal [24];
  2434. #endif
  2435. #else
  2436. mutable pthread_mutex_t internal;
  2437. #endif
  2438. CriticalSection (const CriticalSection&);
  2439. const CriticalSection& operator= (const CriticalSection&);
  2440. };
  2441. /**
  2442. A class that can be used in place of a real CriticalSection object.
  2443. This is currently used by some templated array classes, and should get
  2444. optimised out by the compiler.
  2445. @see Array, OwnedArray, ReferenceCountedArray
  2446. */
  2447. class JUCE_API DummyCriticalSection
  2448. {
  2449. public:
  2450. forcedinline DummyCriticalSection() throw() {}
  2451. forcedinline ~DummyCriticalSection() throw() {}
  2452. forcedinline void enter() const throw() {}
  2453. forcedinline void exit() const throw() {}
  2454. };
  2455. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2456. /********* End of inlined file: juce_CriticalSection.h *********/
  2457. /**
  2458. Holds a list of primitive objects, such as ints, doubles, or pointers.
  2459. Examples of arrays are: Array<int> or Array<MyClass*>
  2460. Note that when holding pointers to objects, the array doesn't take any ownership
  2461. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  2462. If you're using a class or struct as the element type, it must be
  2463. capable of being copied or moved with a straightforward memcpy, rather than
  2464. needing construction and destruction code.
  2465. For holding lists of strings, use the specialised class StringArray.
  2466. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2467. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2468. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2469. */
  2470. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2471. class Array
  2472. {
  2473. public:
  2474. /** Creates an empty array.
  2475. @param granularity this is the size of increment by which the internal storage
  2476. used by the array will grow. Only change it from the default if you know the
  2477. array is going to be very big and needs to be able to grow efficiently.
  2478. */
  2479. Array (const int granularity = juceDefaultArrayGranularity) throw()
  2480. : data (granularity),
  2481. numUsed (0)
  2482. {
  2483. }
  2484. /** Creates a copy of another array.
  2485. @param other the array to copy
  2486. */
  2487. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2488. : data (other.data.granularity)
  2489. {
  2490. other.lockArray();
  2491. numUsed = other.numUsed;
  2492. data.setAllocatedSize (other.numUsed);
  2493. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  2494. other.unlockArray();
  2495. }
  2496. /** Initalises from a null-terminated C array of values.
  2497. @param values the array to copy from
  2498. */
  2499. Array (const ElementType* values) throw()
  2500. : data (juceDefaultArrayGranularity),
  2501. numUsed (0)
  2502. {
  2503. while (*values != 0)
  2504. add (*values++);
  2505. }
  2506. /** Initalises from a C array of values.
  2507. @param values the array to copy from
  2508. @param numValues the number of values in the array
  2509. */
  2510. Array (const ElementType* values, int numValues) throw()
  2511. : data (juceDefaultArrayGranularity),
  2512. numUsed (numValues)
  2513. {
  2514. data.setAllocatedSize (numValues);
  2515. memcpy (data.elements, values, numValues * sizeof (ElementType));
  2516. }
  2517. /** Destructor. */
  2518. ~Array() throw()
  2519. {
  2520. }
  2521. /** Copies another array.
  2522. @param other the array to copy
  2523. */
  2524. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2525. {
  2526. if (this != &other)
  2527. {
  2528. other.lockArray();
  2529. lock.enter();
  2530. data.granularity = other.data.granularity;
  2531. data.ensureAllocatedSize (other.size());
  2532. numUsed = other.numUsed;
  2533. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  2534. minimiseStorageOverheads();
  2535. lock.exit();
  2536. other.unlockArray();
  2537. }
  2538. return *this;
  2539. }
  2540. /** Compares this array to another one.
  2541. Two arrays are considered equal if they both contain the same set of
  2542. elements, in the same order.
  2543. @param other the other array to compare with
  2544. */
  2545. template <class OtherArrayType>
  2546. bool operator== (const OtherArrayType& other) const throw()
  2547. {
  2548. lock.enter();
  2549. if (numUsed != other.numUsed)
  2550. {
  2551. lock.exit();
  2552. return false;
  2553. }
  2554. for (int i = numUsed; --i >= 0;)
  2555. {
  2556. if (data.elements [i] != other.data.elements [i])
  2557. {
  2558. lock.exit();
  2559. return false;
  2560. }
  2561. }
  2562. lock.exit();
  2563. return true;
  2564. }
  2565. /** Compares this array to another one.
  2566. Two arrays are considered equal if they both contain the same set of
  2567. elements, in the same order.
  2568. @param other the other array to compare with
  2569. */
  2570. template <class OtherArrayType>
  2571. bool operator!= (const OtherArrayType& other) const throw()
  2572. {
  2573. return ! operator== (other);
  2574. }
  2575. /** Removes all elements from the array.
  2576. This will remove all the elements, and free any storage that the array is
  2577. using. To clear the array without freeing the storage, use the clearQuick()
  2578. method instead.
  2579. @see clearQuick
  2580. */
  2581. void clear() throw()
  2582. {
  2583. lock.enter();
  2584. data.setAllocatedSize (0);
  2585. numUsed = 0;
  2586. lock.exit();
  2587. }
  2588. /** Removes all elements from the array without freeing the array's allocated storage.
  2589. @see clear
  2590. */
  2591. void clearQuick() throw()
  2592. {
  2593. lock.enter();
  2594. numUsed = 0;
  2595. lock.exit();
  2596. }
  2597. /** Returns the current number of elements in the array.
  2598. */
  2599. inline int size() const throw()
  2600. {
  2601. return numUsed;
  2602. }
  2603. /** Returns one of the elements in the array.
  2604. If the index passed in is beyond the range of valid elements, this
  2605. will return zero.
  2606. If you're certain that the index will always be a valid element, you
  2607. can call getUnchecked() instead, which is faster.
  2608. @param index the index of the element being requested (0 is the first element in the array)
  2609. @see getUnchecked, getFirst, getLast
  2610. */
  2611. inline ElementType operator[] (const int index) const throw()
  2612. {
  2613. lock.enter();
  2614. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  2615. ? data.elements [index]
  2616. : ElementType();
  2617. lock.exit();
  2618. return result;
  2619. }
  2620. /** Returns one of the elements in the array, without checking the index passed in.
  2621. Unlike the operator[] method, this will try to return an element without
  2622. checking that the index is within the bounds of the array, so should only
  2623. be used when you're confident that it will always be a valid index.
  2624. @param index the index of the element being requested (0 is the first element in the array)
  2625. @see operator[], getFirst, getLast
  2626. */
  2627. inline ElementType getUnchecked (const int index) const throw()
  2628. {
  2629. lock.enter();
  2630. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2631. const ElementType result = data.elements [index];
  2632. lock.exit();
  2633. return result;
  2634. }
  2635. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2636. This is like getUnchecked, but returns a direct reference to the element, so that
  2637. you can alter it directly. Obviously this can be dangerous, so only use it when
  2638. absolutely necessary.
  2639. @param index the index of the element being requested (0 is the first element in the array)
  2640. @see operator[], getFirst, getLast
  2641. */
  2642. inline ElementType& getReference (const int index) const throw()
  2643. {
  2644. lock.enter();
  2645. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2646. ElementType& result = data.elements [index];
  2647. lock.exit();
  2648. return result;
  2649. }
  2650. /** Returns the first element in the array, or 0 if the array is empty.
  2651. @see operator[], getUnchecked, getLast
  2652. */
  2653. inline ElementType getFirst() const throw()
  2654. {
  2655. lock.enter();
  2656. const ElementType result = (numUsed > 0) ? data.elements [0]
  2657. : ElementType();
  2658. lock.exit();
  2659. return result;
  2660. }
  2661. /** Returns the last element in the array, or 0 if the array is empty.
  2662. @see operator[], getUnchecked, getFirst
  2663. */
  2664. inline ElementType getLast() const throw()
  2665. {
  2666. lock.enter();
  2667. const ElementType result = (numUsed > 0) ? data.elements [numUsed - 1]
  2668. : ElementType();
  2669. lock.exit();
  2670. return result;
  2671. }
  2672. /** Finds the index of the first element which matches the value passed in.
  2673. This will search the array for the given object, and return the index
  2674. of its first occurrence. If the object isn't found, the method will return -1.
  2675. @param elementToLookFor the value or object to look for
  2676. @returns the index of the object, or -1 if it's not found
  2677. */
  2678. int indexOf (const ElementType elementToLookFor) const throw()
  2679. {
  2680. int result = -1;
  2681. lock.enter();
  2682. const ElementType* e = data.elements;
  2683. for (int i = numUsed; --i >= 0;)
  2684. {
  2685. if (elementToLookFor == *e)
  2686. {
  2687. result = (int) (e - data.elements);
  2688. break;
  2689. }
  2690. ++e;
  2691. }
  2692. lock.exit();
  2693. return result;
  2694. }
  2695. /** Returns true if the array contains at least one occurrence of an object.
  2696. @param elementToLookFor the value or object to look for
  2697. @returns true if the item is found
  2698. */
  2699. bool contains (const ElementType elementToLookFor) const throw()
  2700. {
  2701. lock.enter();
  2702. const ElementType* e = data.elements;
  2703. int num = numUsed;
  2704. while (num >= 4)
  2705. {
  2706. if (*e == elementToLookFor
  2707. || *++e == elementToLookFor
  2708. || *++e == elementToLookFor
  2709. || *++e == elementToLookFor)
  2710. {
  2711. lock.exit();
  2712. return true;
  2713. }
  2714. num -= 4;
  2715. ++e;
  2716. }
  2717. while (num > 0)
  2718. {
  2719. if (elementToLookFor == *e)
  2720. {
  2721. lock.exit();
  2722. return true;
  2723. }
  2724. --num;
  2725. ++e;
  2726. }
  2727. lock.exit();
  2728. return false;
  2729. }
  2730. /** Appends a new element at the end of the array.
  2731. @param newElement the new object to add to the array
  2732. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  2733. */
  2734. void add (const ElementType newElement) throw()
  2735. {
  2736. lock.enter();
  2737. data.ensureAllocatedSize (numUsed + 1);
  2738. data.elements [numUsed++] = newElement;
  2739. lock.exit();
  2740. }
  2741. /** Inserts a new element into the array at a given position.
  2742. If the index is less than 0 or greater than the size of the array, the
  2743. element will be added to the end of the array.
  2744. Otherwise, it will be inserted into the array, moving all the later elements
  2745. along to make room.
  2746. @param indexToInsertAt the index at which the new element should be
  2747. inserted (pass in -1 to add it to the end)
  2748. @param newElement the new object to add to the array
  2749. @see add, addSorted, set
  2750. */
  2751. void insert (int indexToInsertAt, const ElementType newElement) throw()
  2752. {
  2753. lock.enter();
  2754. data.ensureAllocatedSize (numUsed + 1);
  2755. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2756. {
  2757. ElementType* const insertPos = data.elements + indexToInsertAt;
  2758. const int numberToMove = numUsed - indexToInsertAt;
  2759. if (numberToMove > 0)
  2760. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2761. *insertPos = newElement;
  2762. ++numUsed;
  2763. }
  2764. else
  2765. {
  2766. data.elements [numUsed++] = newElement;
  2767. }
  2768. lock.exit();
  2769. }
  2770. /** Inserts multiple copies of an element into the array at a given position.
  2771. If the index is less than 0 or greater than the size of the array, the
  2772. element will be added to the end of the array.
  2773. Otherwise, it will be inserted into the array, moving all the later elements
  2774. along to make room.
  2775. @param indexToInsertAt the index at which the new element should be inserted
  2776. @param newElement the new object to add to the array
  2777. @param numberOfTimesToInsertIt how many copies of the value to insert
  2778. @see insert, add, addSorted, set
  2779. */
  2780. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  2781. int numberOfTimesToInsertIt) throw()
  2782. {
  2783. if (numberOfTimesToInsertIt > 0)
  2784. {
  2785. lock.enter();
  2786. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2787. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2788. {
  2789. ElementType* insertPos = data.elements + indexToInsertAt;
  2790. const int numberToMove = numUsed - indexToInsertAt;
  2791. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2792. numUsed += numberOfTimesToInsertIt;
  2793. while (--numberOfTimesToInsertIt >= 0)
  2794. *insertPos++ = newElement;
  2795. }
  2796. else
  2797. {
  2798. while (--numberOfTimesToInsertIt >= 0)
  2799. data.elements [numUsed++] = newElement;
  2800. }
  2801. lock.exit();
  2802. }
  2803. }
  2804. /** Inserts an array of values into this array at a given position.
  2805. If the index is less than 0 or greater than the size of the array, the
  2806. new elements will be added to the end of the array.
  2807. Otherwise, they will be inserted into the array, moving all the later elements
  2808. along to make room.
  2809. @param indexToInsertAt the index at which the first new element should be inserted
  2810. @param newElements the new values to add to the array
  2811. @param numberOfElements how many items are in the array
  2812. @see insert, add, addSorted, set
  2813. */
  2814. void insertArray (int indexToInsertAt,
  2815. const ElementType* newElements,
  2816. int numberOfElements) throw()
  2817. {
  2818. if (numberOfElements > 0)
  2819. {
  2820. lock.enter();
  2821. data.ensureAllocatedSize (numUsed + numberOfElements);
  2822. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2823. {
  2824. ElementType* insertPos = data.elements + indexToInsertAt;
  2825. const int numberToMove = numUsed - indexToInsertAt;
  2826. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2827. numUsed += numberOfElements;
  2828. while (--numberOfElements >= 0)
  2829. *insertPos++ = *newElements++;
  2830. }
  2831. else
  2832. {
  2833. while (--numberOfElements >= 0)
  2834. data.elements [numUsed++] = *newElements++;
  2835. }
  2836. lock.exit();
  2837. }
  2838. }
  2839. /** Appends a new element at the end of the array as long as the array doesn't
  2840. already contain it.
  2841. If the array already contains an element that matches the one passed in, nothing
  2842. will be done.
  2843. @param newElement the new object to add to the array
  2844. */
  2845. void addIfNotAlreadyThere (const ElementType newElement) throw()
  2846. {
  2847. lock.enter();
  2848. if (! contains (newElement))
  2849. add (newElement);
  2850. lock.exit();
  2851. }
  2852. /** Replaces an element with a new value.
  2853. If the index is less than zero, this method does nothing.
  2854. If the index is beyond the end of the array, the item is added to the end of the array.
  2855. @param indexToChange the index whose value you want to change
  2856. @param newValue the new value to set for this index.
  2857. @see add, insert
  2858. */
  2859. void set (const int indexToChange,
  2860. const ElementType newValue) throw()
  2861. {
  2862. jassert (indexToChange >= 0);
  2863. if (indexToChange >= 0)
  2864. {
  2865. lock.enter();
  2866. if (indexToChange < numUsed)
  2867. {
  2868. data.elements [indexToChange] = newValue;
  2869. }
  2870. else
  2871. {
  2872. data.ensureAllocatedSize (numUsed + 1);
  2873. data.elements [numUsed++] = newValue;
  2874. }
  2875. lock.exit();
  2876. }
  2877. }
  2878. /** Replaces an element with a new value without doing any bounds-checking.
  2879. This just sets a value directly in the array's internal storage, so you'd
  2880. better make sure it's in range!
  2881. @param indexToChange the index whose value you want to change
  2882. @param newValue the new value to set for this index.
  2883. @see set, getUnchecked
  2884. */
  2885. void setUnchecked (const int indexToChange,
  2886. const ElementType newValue) throw()
  2887. {
  2888. lock.enter();
  2889. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  2890. data.elements [indexToChange] = newValue;
  2891. lock.exit();
  2892. }
  2893. /** Adds elements from an array to the end of this array.
  2894. @param elementsToAdd the array of elements to add
  2895. @param numElementsToAdd how many elements are in this other array
  2896. @see add
  2897. */
  2898. void addArray (const ElementType* elementsToAdd,
  2899. int numElementsToAdd) throw()
  2900. {
  2901. lock.enter();
  2902. if (numElementsToAdd > 0)
  2903. {
  2904. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  2905. while (--numElementsToAdd >= 0)
  2906. data.elements [numUsed++] = *elementsToAdd++;
  2907. }
  2908. lock.exit();
  2909. }
  2910. /** This swaps the contents of this array with those of another array.
  2911. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2912. because it just swaps their internal pointers.
  2913. */
  2914. template <class OtherArrayType>
  2915. void swapWithArray (OtherArrayType& otherArray) throw()
  2916. {
  2917. lock.enter();
  2918. otherArray.lock.enter();
  2919. swapVariables <int> (numUsed, otherArray.numUsed);
  2920. swapVariables <ElementType*> (data.elements, otherArray.data.elements);
  2921. swapVariables <int> (data.numAllocated, otherArray.data.numAllocated);
  2922. otherArray.lock.exit();
  2923. lock.exit();
  2924. }
  2925. /** Adds elements from another array to the end of this array.
  2926. @param arrayToAddFrom the array from which to copy the elements
  2927. @param startIndex the first element of the other array to start copying from
  2928. @param numElementsToAdd how many elements to add from the other array. If this
  2929. value is negative or greater than the number of available elements,
  2930. all available elements will be copied.
  2931. @see add
  2932. */
  2933. template <class OtherArrayType>
  2934. void addArray (const OtherArrayType& arrayToAddFrom,
  2935. int startIndex = 0,
  2936. int numElementsToAdd = -1) throw()
  2937. {
  2938. arrayToAddFrom.lockArray();
  2939. lock.enter();
  2940. if (startIndex < 0)
  2941. {
  2942. jassertfalse
  2943. startIndex = 0;
  2944. }
  2945. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  2946. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  2947. while (--numElementsToAdd >= 0)
  2948. add (arrayToAddFrom.getUnchecked (startIndex++));
  2949. lock.exit();
  2950. arrayToAddFrom.unlockArray();
  2951. }
  2952. /** Inserts a new element into the array, assuming that the array is sorted.
  2953. This will use a comparator to find the position at which the new element
  2954. should go. If the array isn't sorted, the behaviour of this
  2955. method will be unpredictable.
  2956. @param comparator the comparator to use to compare the elements - see the sort()
  2957. method for details about the form this object should take
  2958. @param newElement the new element to insert to the array
  2959. @see add, sort
  2960. */
  2961. template <class ElementComparator>
  2962. void addSorted (ElementComparator& comparator,
  2963. const ElementType newElement) throw()
  2964. {
  2965. lock.enter();
  2966. insert (findInsertIndexInSortedArray (comparator, data.elements, newElement, 0, numUsed), newElement);
  2967. lock.exit();
  2968. }
  2969. /** Finds the index of an element in the array, assuming that the array is sorted.
  2970. This will use a comparator to do a binary-chop to find the index of the given
  2971. element, if it exists. If the array isn't sorted, the behaviour of this
  2972. method will be unpredictable.
  2973. @param comparator the comparator to use to compare the elements - see the sort()
  2974. method for details about the form this object should take
  2975. @param elementToLookFor the element to search for
  2976. @returns the index of the element, or -1 if it's not found
  2977. @see addSorted, sort
  2978. */
  2979. template <class ElementComparator>
  2980. int indexOfSorted (ElementComparator& comparator,
  2981. const ElementType elementToLookFor) const throw()
  2982. {
  2983. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2984. // avoids getting warning messages about the parameter being unused
  2985. lock.enter();
  2986. int start = 0;
  2987. int end = numUsed;
  2988. for (;;)
  2989. {
  2990. if (start >= end)
  2991. {
  2992. lock.exit();
  2993. return -1;
  2994. }
  2995. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  2996. {
  2997. lock.exit();
  2998. return start;
  2999. }
  3000. else
  3001. {
  3002. const int halfway = (start + end) >> 1;
  3003. if (halfway == start)
  3004. {
  3005. lock.exit();
  3006. return -1;
  3007. }
  3008. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3009. start = halfway;
  3010. else
  3011. end = halfway;
  3012. }
  3013. }
  3014. }
  3015. /** Removes an element from the array.
  3016. This will remove the element at a given index, and move back
  3017. all the subsequent elements to close the gap.
  3018. If the index passed in is out-of-range, nothing will happen.
  3019. @param indexToRemove the index of the element to remove
  3020. @returns the element that has been removed
  3021. @see removeValue, removeRange
  3022. */
  3023. ElementType remove (const int indexToRemove) throw()
  3024. {
  3025. lock.enter();
  3026. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3027. {
  3028. --numUsed;
  3029. ElementType* const e = data.elements + indexToRemove;
  3030. ElementType const removed = *e;
  3031. const int numberToShift = numUsed - indexToRemove;
  3032. if (numberToShift > 0)
  3033. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3034. if ((numUsed << 1) < data.numAllocated)
  3035. minimiseStorageOverheads();
  3036. lock.exit();
  3037. return removed;
  3038. }
  3039. else
  3040. {
  3041. lock.exit();
  3042. return ElementType();
  3043. }
  3044. }
  3045. /** Removes an item from the array.
  3046. This will remove the first occurrence of the given element from the array.
  3047. If the item isn't found, no action is taken.
  3048. @param valueToRemove the object to try to remove
  3049. @see remove, removeRange
  3050. */
  3051. void removeValue (const ElementType valueToRemove) throw()
  3052. {
  3053. lock.enter();
  3054. ElementType* e = data.elements;
  3055. for (int i = numUsed; --i >= 0;)
  3056. {
  3057. if (valueToRemove == *e)
  3058. {
  3059. remove ((int) (e - data.elements));
  3060. break;
  3061. }
  3062. ++e;
  3063. }
  3064. lock.exit();
  3065. }
  3066. /** Removes a range of elements from the array.
  3067. This will remove a set of elements, starting from the given index,
  3068. and move subsequent elements down to close the gap.
  3069. If the range extends beyond the bounds of the array, it will
  3070. be safely clipped to the size of the array.
  3071. @param startIndex the index of the first element to remove
  3072. @param numberToRemove how many elements should be removed
  3073. @see remove, removeValue
  3074. */
  3075. void removeRange (int startIndex,
  3076. const int numberToRemove) throw()
  3077. {
  3078. lock.enter();
  3079. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3080. startIndex = jlimit (0, numUsed, startIndex);
  3081. if (endIndex > startIndex)
  3082. {
  3083. const int rangeSize = endIndex - startIndex;
  3084. ElementType* e = data.elements + startIndex;
  3085. int numToShift = numUsed - endIndex;
  3086. numUsed -= rangeSize;
  3087. while (--numToShift >= 0)
  3088. {
  3089. *e = e [rangeSize];
  3090. ++e;
  3091. }
  3092. if ((numUsed << 1) < data.numAllocated)
  3093. minimiseStorageOverheads();
  3094. }
  3095. lock.exit();
  3096. }
  3097. /** Removes the last n elements from the array.
  3098. @param howManyToRemove how many elements to remove from the end of the array
  3099. @see remove, removeValue, removeRange
  3100. */
  3101. void removeLast (const int howManyToRemove = 1) throw()
  3102. {
  3103. lock.enter();
  3104. numUsed = jmax (0, numUsed - howManyToRemove);
  3105. if ((numUsed << 1) < data.numAllocated)
  3106. minimiseStorageOverheads();
  3107. lock.exit();
  3108. }
  3109. /** Removes any elements which are also in another array.
  3110. @param otherArray the other array in which to look for elements to remove
  3111. @see removeValuesNotIn, remove, removeValue, removeRange
  3112. */
  3113. template <class OtherArrayType>
  3114. void removeValuesIn (const OtherArrayType& otherArray) throw()
  3115. {
  3116. otherArray.lockArray();
  3117. lock.enter();
  3118. if (this == &otherArray)
  3119. {
  3120. clear();
  3121. }
  3122. else
  3123. {
  3124. if (otherArray.size() > 0)
  3125. {
  3126. for (int i = numUsed; --i >= 0;)
  3127. if (otherArray.contains (data.elements [i]))
  3128. remove (i);
  3129. }
  3130. }
  3131. lock.exit();
  3132. otherArray.unlockArray();
  3133. }
  3134. /** Removes any elements which are not found in another array.
  3135. Only elements which occur in this other array will be retained.
  3136. @param otherArray the array in which to look for elements NOT to remove
  3137. @see removeValuesIn, remove, removeValue, removeRange
  3138. */
  3139. template <class OtherArrayType>
  3140. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  3141. {
  3142. otherArray.lockArray();
  3143. lock.enter();
  3144. if (this != &otherArray)
  3145. {
  3146. if (otherArray.size() <= 0)
  3147. {
  3148. clear();
  3149. }
  3150. else
  3151. {
  3152. for (int i = numUsed; --i >= 0;)
  3153. if (! otherArray.contains (data.elements [i]))
  3154. remove (i);
  3155. }
  3156. }
  3157. lock.exit();
  3158. otherArray.unlockArray();
  3159. }
  3160. /** Swaps over two elements in the array.
  3161. This swaps over the elements found at the two indexes passed in.
  3162. If either index is out-of-range, this method will do nothing.
  3163. @param index1 index of one of the elements to swap
  3164. @param index2 index of the other element to swap
  3165. */
  3166. void swap (const int index1,
  3167. const int index2) throw()
  3168. {
  3169. lock.enter();
  3170. if (((unsigned int) index1) < (unsigned int) numUsed
  3171. && ((unsigned int) index2) < (unsigned int) numUsed)
  3172. {
  3173. swapVariables (data.elements [index1],
  3174. data.elements [index2]);
  3175. }
  3176. lock.exit();
  3177. }
  3178. /** Moves one of the values to a different position.
  3179. This will move the value to a specified index, shuffling along
  3180. any intervening elements as required.
  3181. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3182. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3183. @param currentIndex the index of the value to be moved. If this isn't a
  3184. valid index, then nothing will be done
  3185. @param newIndex the index at which you'd like this value to end up. If this
  3186. is less than zero, the value will be moved to the end
  3187. of the array
  3188. */
  3189. void move (const int currentIndex,
  3190. int newIndex) throw()
  3191. {
  3192. if (currentIndex != newIndex)
  3193. {
  3194. lock.enter();
  3195. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3196. {
  3197. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3198. newIndex = numUsed - 1;
  3199. const ElementType value = data.elements [currentIndex];
  3200. if (newIndex > currentIndex)
  3201. {
  3202. memmove (data.elements + currentIndex,
  3203. data.elements + currentIndex + 1,
  3204. (newIndex - currentIndex) * sizeof (ElementType));
  3205. }
  3206. else
  3207. {
  3208. memmove (data.elements + newIndex + 1,
  3209. data.elements + newIndex,
  3210. (currentIndex - newIndex) * sizeof (ElementType));
  3211. }
  3212. data.elements [newIndex] = value;
  3213. }
  3214. lock.exit();
  3215. }
  3216. }
  3217. /** Reduces the amount of storage being used by the array.
  3218. Arrays typically allocate slightly more storage than they need, and after
  3219. removing elements, they may have quite a lot of unused space allocated.
  3220. This method will reduce the amount of allocated storage to a minimum.
  3221. */
  3222. void minimiseStorageOverheads() throw()
  3223. {
  3224. lock.enter();
  3225. if (numUsed == 0)
  3226. {
  3227. data.setAllocatedSize (0);
  3228. }
  3229. else
  3230. {
  3231. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  3232. if (newAllocation < data.numAllocated)
  3233. data.setAllocatedSize (newAllocation);
  3234. }
  3235. lock.exit();
  3236. }
  3237. /** Increases the array's internal storage to hold a minimum number of elements.
  3238. Calling this before adding a large known number of elements means that
  3239. the array won't have to keep dynamically resizing itself as the elements
  3240. are added, and it'll therefore be more efficient.
  3241. */
  3242. void ensureStorageAllocated (const int minNumElements) throw()
  3243. {
  3244. data.ensureAllocatedSize (minNumElements);
  3245. }
  3246. /** Sorts the elements in the array.
  3247. This will use a comparator object to sort the elements into order. The object
  3248. passed must have a method of the form:
  3249. @code
  3250. int compareElements (ElementType first, ElementType second);
  3251. @endcode
  3252. ..and this method must return:
  3253. - a value of < 0 if the first comes before the second
  3254. - a value of 0 if the two objects are equivalent
  3255. - a value of > 0 if the second comes before the first
  3256. To improve performance, the compareElements() method can be declared as static or const.
  3257. @param comparator the comparator to use for comparing elements.
  3258. @param retainOrderOfEquivalentItems if this is true, then items
  3259. which the comparator says are equivalent will be
  3260. kept in the order in which they currently appear
  3261. in the array. This is slower to perform, but may
  3262. be important in some cases. If it's false, a faster
  3263. algorithm is used, but equivalent elements may be
  3264. rearranged.
  3265. @see addSorted, indexOfSorted, sortArray
  3266. */
  3267. template <class ElementComparator>
  3268. void sort (ElementComparator& comparator,
  3269. const bool retainOrderOfEquivalentItems = false) const throw()
  3270. {
  3271. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3272. // avoids getting warning messages about the parameter being unused
  3273. lock.enter();
  3274. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3275. lock.exit();
  3276. }
  3277. /** Locks the array's CriticalSection.
  3278. Of course if the type of section used is a DummyCriticalSection, this won't
  3279. have any effect.
  3280. @see unlockArray
  3281. */
  3282. void lockArray() const throw()
  3283. {
  3284. lock.enter();
  3285. }
  3286. /** Unlocks the array's CriticalSection.
  3287. Of course if the type of section used is a DummyCriticalSection, this won't
  3288. have any effect.
  3289. @see lockArray
  3290. */
  3291. void unlockArray() const throw()
  3292. {
  3293. lock.exit();
  3294. }
  3295. juce_UseDebuggingNewOperator
  3296. private:
  3297. ArrayAllocationBase <ElementType> data;
  3298. int numUsed;
  3299. TypeOfCriticalSectionToUse lock;
  3300. };
  3301. #endif // __JUCE_ARRAY_JUCEHEADER__
  3302. /********* End of inlined file: juce_Array.h *********/
  3303. #endif
  3304. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3305. #endif
  3306. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  3307. /********* Start of inlined file: juce_BitArray.h *********/
  3308. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  3309. #define __JUCE_BITARRAY_JUCEHEADER__
  3310. /********* Start of inlined file: juce_HeapBlock.h *********/
  3311. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  3312. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  3313. /**
  3314. Very simple container class to hold a pointer to some data on the heap.
  3315. When you need to allocate some heap storage for something, always try to use
  3316. this class instead of allocating the memory directly using malloc/free.
  3317. A HeapBlock<char> object can be treated in pretty much exactly the same way
  3318. as an char*, but as long as you allocate it on the stack or as a class member,
  3319. it's almost impossible for it to leak memory.
  3320. It also makes your code much more concise and readable than doing the same thing
  3321. using direct allocations,
  3322. E.g. instead of this:
  3323. @code
  3324. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  3325. memcpy (temp, xyz, 1024 * sizeof (int));
  3326. juce_free (temp);
  3327. temp = (int*) juce_calloc (2048 * sizeof (int));
  3328. temp[0] = 1234;
  3329. memcpy (foobar, temp, 2048 * sizeof (int));
  3330. juce_free (temp);
  3331. @endcode
  3332. ..you could just write this:
  3333. @code
  3334. HeapBlock <int> temp (1024);
  3335. memcpy (temp, xyz, 1024 * sizeof (int));
  3336. temp.calloc (2048);
  3337. temp[0] = 1234;
  3338. memcpy (foobar, temp, 2048 * sizeof (int));
  3339. @endcode
  3340. The class is extremely lightweight, containing only a pointer to the
  3341. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  3342. as their less object-oriented counterparts. Despite adding safety, you probably
  3343. won't sacrifice any performance by using this in place of normal pointers.
  3344. @see Array, OwnedArray, MemoryBlock
  3345. */
  3346. template <class ElementType>
  3347. class HeapBlock
  3348. {
  3349. public:
  3350. /** Creates a HeapBlock which is initially just a null pointer.
  3351. After creation, you can resize the array using the malloc(), calloc(),
  3352. or realloc() methods.
  3353. */
  3354. HeapBlock() : data (0)
  3355. {
  3356. }
  3357. /** Creates a HeapBlock containing a number of elements.
  3358. The contents of the block are undefined, as it will have been created by a
  3359. malloc call.
  3360. If you want an array of zero values, you can use the calloc() method instead.
  3361. */
  3362. HeapBlock (const int numElements)
  3363. : data ((ElementType*) ::juce_malloc (numElements * sizeof (ElementType)))
  3364. {
  3365. }
  3366. /** Destructor.
  3367. This will free the data, if any has been allocated.
  3368. */
  3369. ~HeapBlock()
  3370. {
  3371. ::juce_free (data);
  3372. }
  3373. /** Returns a raw pointer to the allocated data.
  3374. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  3375. freed by calling the free() method.
  3376. */
  3377. inline operator ElementType*() const { return data; }
  3378. /** Returns a void pointer to the allocated data.
  3379. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  3380. freed by calling the free() method.
  3381. */
  3382. inline operator void*() const { return (void*) data; }
  3383. /** Lets you use indirect calls to the first element in the array.
  3384. Obviously this will cause problems if the array hasn't been initialised, because it'll
  3385. be referencing a null pointer.
  3386. */
  3387. inline ElementType* operator->() const { return data; }
  3388. /** Returns a pointer to the data by casting it to any type you need.
  3389. */
  3390. template <class CastType>
  3391. inline operator CastType*() const { return (CastType*) data; }
  3392. /** Returns a reference to one of the data elements.
  3393. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  3394. has no idea of the size it currently has allocated.
  3395. */
  3396. template <typename IndexType>
  3397. inline ElementType& operator[] (IndexType index) const { return data [index]; }
  3398. /** Returns a pointer to a data element at an offset from the start of the array.
  3399. This is the same as doing pointer arithmetic on the raw pointer itself.
  3400. */
  3401. template <typename IndexType>
  3402. inline ElementType* operator+ (IndexType index) const { return data + index; }
  3403. /** Returns a reference to the raw data pointer.
  3404. Beware that the pointer returned here will become invalid as soon as you call
  3405. any of the allocator methods on this object!
  3406. */
  3407. inline ElementType** operator&() const { return (ElementType**) &data; }
  3408. /** Compares the pointer with another pointer.
  3409. This can be handy for checking whether this is a null pointer.
  3410. */
  3411. inline bool operator== (const ElementType* const otherPointer) const { return otherPointer == data; }
  3412. /** Compares the pointer with another pointer.
  3413. This can be handy for checking whether this is a null pointer.
  3414. */
  3415. inline bool operator!= (const ElementType* const otherPointer) const { return otherPointer != data; }
  3416. /** Allocates a specified amount of memory.
  3417. This uses the normal malloc to allocate an amount of memory for this object.
  3418. Any previously allocated memory will be freed by this method.
  3419. The number of bytes allocated will be (newNumElements * elementSize). Normally
  3420. you wouldn't need to specify the second parameter, but it can be handy if you need
  3421. to allocate a size in bytes rather than in terms of the number of elements.
  3422. The data that is allocated will be freed when this object is deleted, or when you
  3423. call free() or any of the allocation methods.
  3424. */
  3425. void malloc (const int newNumElements, const unsigned int elementSize = sizeof (ElementType))
  3426. {
  3427. ::juce_free (data);
  3428. data = (ElementType*) ::juce_malloc (newNumElements * elementSize);
  3429. }
  3430. /** Allocates a specified amount of memory and clears it.
  3431. This does the same job as the malloc() method, but clears the memory that it allocates.
  3432. */
  3433. void calloc (const int newNumElements, const unsigned int elementSize = sizeof (ElementType))
  3434. {
  3435. ::juce_free (data);
  3436. data = (ElementType*) ::juce_calloc (newNumElements * elementSize);
  3437. }
  3438. /** Allocates a specified amount of memory and optionally clears it.
  3439. This does the same job as either malloc() or calloc(), depending on the
  3440. initialiseToZero parameter.
  3441. */
  3442. void allocate (const int newNumElements, const bool initialiseToZero)
  3443. {
  3444. ::juce_free (data);
  3445. if (initialiseToZero)
  3446. data = (ElementType*) ::juce_calloc (newNumElements * sizeof (ElementType));
  3447. else
  3448. data = (ElementType*) ::juce_malloc (newNumElements * sizeof (ElementType));
  3449. }
  3450. /** Re-allocates a specified amount of memory.
  3451. The semantics of this method are the same as malloc() and calloc(), but it
  3452. uses realloc() to keep as much of the existing data as possible.
  3453. */
  3454. void realloc (const int newNumElements, const unsigned int elementSize = sizeof (ElementType))
  3455. {
  3456. if (data == 0)
  3457. data = (ElementType*) ::juce_malloc (newNumElements * elementSize);
  3458. else
  3459. data = (ElementType*) ::juce_realloc (data, newNumElements * elementSize);
  3460. }
  3461. /** Frees any currently-allocated data.
  3462. This will free the data and reset this object to be a null pointer.
  3463. */
  3464. void free()
  3465. {
  3466. ::juce_free (data);
  3467. data = 0;
  3468. }
  3469. /** Swaps this object's data with the data of another HeapBlock.
  3470. The two objects simply exchange their data pointers.
  3471. */
  3472. void swapWith (HeapBlock <ElementType>& other)
  3473. {
  3474. swapVariables (data, other.data);
  3475. }
  3476. private:
  3477. ElementType* data;
  3478. HeapBlock (const HeapBlock&);
  3479. const HeapBlock& operator= (const HeapBlock&);
  3480. };
  3481. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  3482. /********* End of inlined file: juce_HeapBlock.h *********/
  3483. class MemoryBlock;
  3484. /**
  3485. An array of on/off bits, also usable to store large binary integers.
  3486. A BitArray acts like an arbitrarily large integer whose bits can be set or
  3487. cleared, and some basic mathematical operations can be done on the number as
  3488. a whole.
  3489. */
  3490. class JUCE_API BitArray
  3491. {
  3492. public:
  3493. /** Creates an empty BitArray */
  3494. BitArray() throw();
  3495. /** Creates a BitArray containing an integer value in its low bits.
  3496. The low 32 bits of the array are initialised with this value.
  3497. */
  3498. BitArray (const unsigned int value) throw();
  3499. /** Creates a BitArray containing an integer value in its low bits.
  3500. The low 32 bits of the array are initialised with the absolute value
  3501. passed in, and its sign is set to reflect the sign of the number.
  3502. */
  3503. BitArray (const int value) throw();
  3504. /** Creates a BitArray containing an integer value in its low bits.
  3505. The low 64 bits of the array are initialised with the absolute value
  3506. passed in, and its sign is set to reflect the sign of the number.
  3507. */
  3508. BitArray (int64 value) throw();
  3509. /** Creates a copy of another BitArray. */
  3510. BitArray (const BitArray& other) throw();
  3511. /** Destructor. */
  3512. ~BitArray() throw();
  3513. /** Copies another BitArray onto this one. */
  3514. const BitArray& operator= (const BitArray& other) throw();
  3515. /** Two arrays are the same if the same bits are set. */
  3516. bool operator== (const BitArray& other) const throw();
  3517. /** Two arrays are the same if the same bits are set. */
  3518. bool operator!= (const BitArray& other) const throw();
  3519. /** Clears all bits in the BitArray to 0. */
  3520. void clear() throw();
  3521. /** Clears a particular bit in the array. */
  3522. void clearBit (const int bitNumber) throw();
  3523. /** Sets a specified bit to 1.
  3524. If the bit number is high, this will grow the array to accomodate it.
  3525. */
  3526. void setBit (const int bitNumber) throw();
  3527. /** Sets or clears a specified bit. */
  3528. void setBit (const int bitNumber,
  3529. const bool shouldBeSet) throw();
  3530. /** Sets a range of bits to be either on or off.
  3531. @param startBit the first bit to change
  3532. @param numBits the number of bits to change
  3533. @param shouldBeSet whether to turn these bits on or off
  3534. */
  3535. void setRange (int startBit,
  3536. int numBits,
  3537. const bool shouldBeSet) throw();
  3538. /** Inserts a bit an a given position, shifting up any bits above it. */
  3539. void insertBit (const int bitNumber,
  3540. const bool shouldBeSet) throw();
  3541. /** Returns the value of a specified bit in the array.
  3542. If the index is out-of-range, the result will be false.
  3543. */
  3544. bool operator[] (const int bit) const throw();
  3545. /** Returns true if no bits are set. */
  3546. bool isEmpty() const throw();
  3547. /** Returns a range of bits in the array as a new BitArray.
  3548. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3549. @see getBitRangeAsInt
  3550. */
  3551. const BitArray getBitRange (int startBit, int numBits) const throw();
  3552. /** Returns a range of bits in the array as an integer value.
  3553. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3554. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3555. getBitRange().
  3556. */
  3557. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3558. /** Sets a range of bits in the array based on an integer value.
  3559. Copies the given integer into the array, starting at startBit,
  3560. and only using up to numBits of the available bits.
  3561. */
  3562. void setBitRangeAsInt (int startBit, int numBits,
  3563. unsigned int valueToSet) throw();
  3564. /** Performs a bitwise OR with another BitArray.
  3565. The result ends up in this array.
  3566. */
  3567. void orWith (const BitArray& other) throw();
  3568. /** Performs a bitwise AND with another BitArray.
  3569. The result ends up in this array.
  3570. */
  3571. void andWith (const BitArray& other) throw();
  3572. /** Performs a bitwise XOR with another BitArray.
  3573. The result ends up in this array.
  3574. */
  3575. void xorWith (const BitArray& other) throw();
  3576. /** Adds another BitArray's value to this one.
  3577. Treating the two arrays as large positive integers, this
  3578. adds them up and puts the result in this array.
  3579. */
  3580. void add (const BitArray& other) throw();
  3581. /** Subtracts another BitArray's value from this one.
  3582. Treating the two arrays as large positive integers, this
  3583. subtracts them and puts the result in this array.
  3584. Note that if the result should be negative, this won't be
  3585. handled correctly.
  3586. */
  3587. void subtract (const BitArray& other) throw();
  3588. /** Multiplies another BitArray's value with this one.
  3589. Treating the two arrays as large positive integers, this
  3590. multiplies them and puts the result in this array.
  3591. */
  3592. void multiplyBy (const BitArray& other) throw();
  3593. /** Divides another BitArray's value into this one and also produces a remainder.
  3594. Treating the two arrays as large positive integers, this
  3595. divides this value by the other, leaving the quotient in this
  3596. array, and the remainder is copied into the other BitArray passed in.
  3597. */
  3598. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  3599. /** Returns the largest value that will divide both this value and the one
  3600. passed-in.
  3601. */
  3602. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  3603. /** Performs a modulo operation on this value.
  3604. The result is stored in this value.
  3605. */
  3606. void modulo (const BitArray& divisor) throw();
  3607. /** Performs a combined exponent and modulo operation.
  3608. This BitArray's value becomes (this ^ exponent) % modulus.
  3609. */
  3610. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  3611. /** Performs an inverse modulo on the value.
  3612. i.e. the result is (this ^ -1) mod (modulus).
  3613. */
  3614. void inverseModulo (const BitArray& modulus) throw();
  3615. /** Shifts a section of bits left or right.
  3616. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3617. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3618. */
  3619. void shiftBits (int howManyBitsLeft,
  3620. int startBit = 0) throw();
  3621. /** Does a signed comparison of two BitArrays.
  3622. Return values are:
  3623. - 0 if the numbers are the same
  3624. - < 0 if this number is smaller than the other
  3625. - > 0 if this number is bigger than the other
  3626. */
  3627. int compare (const BitArray& other) const throw();
  3628. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  3629. Return values are:
  3630. - 0 if the numbers are the same
  3631. - < 0 if this number is smaller than the other
  3632. - > 0 if this number is bigger than the other
  3633. */
  3634. int compareAbsolute (const BitArray& other) const throw();
  3635. /** Returns true if the value is less than zero.
  3636. @see setNegative, negate
  3637. */
  3638. bool isNegative() const throw();
  3639. /** Changes the sign of the number to be positive or negative.
  3640. @see isNegative, negate
  3641. */
  3642. void setNegative (const bool shouldBeNegative) throw();
  3643. /** Inverts the sign of the number.
  3644. @see isNegative, setNegative
  3645. */
  3646. void negate() throw();
  3647. /** Counts the total number of set bits in the array. */
  3648. int countNumberOfSetBits() const throw();
  3649. /** Looks for the index of the next set bit after a given starting point.
  3650. searches from startIndex (inclusive) upwards for the first set bit,
  3651. and returns its index.
  3652. If no set bits are found, it returns -1.
  3653. */
  3654. int findNextSetBit (int startIndex = 0) const throw();
  3655. /** Looks for the index of the next clear bit after a given starting point.
  3656. searches from startIndex (inclusive) upwards for the first clear bit,
  3657. and returns its index.
  3658. */
  3659. int findNextClearBit (int startIndex = 0) const throw();
  3660. /** Returns the index of the highest set bit in the array.
  3661. If the array is empty, this will return -1.
  3662. */
  3663. int getHighestBit() const throw();
  3664. /** Converts the array to a number string.
  3665. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3666. If minuimumNumCharacters is greater than 0, the returned string will be
  3667. padded with leading zeros to reach at least that length.
  3668. */
  3669. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  3670. /** Converts a number string to an array.
  3671. Any non-valid characters will be ignored.
  3672. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3673. */
  3674. void parseString (const String& text,
  3675. const int base) throw();
  3676. /** Turns the array into a block of binary data.
  3677. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3678. of the array, and so on.
  3679. @see loadFromMemoryBlock
  3680. */
  3681. const MemoryBlock toMemoryBlock() const throw();
  3682. /** Copies a block of raw data onto this array.
  3683. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3684. of the array, and so on.
  3685. @see toMemoryBlock
  3686. */
  3687. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  3688. juce_UseDebuggingNewOperator
  3689. private:
  3690. void ensureSize (const int numVals) throw();
  3691. HeapBlock <unsigned int> values;
  3692. int numValues, highestBit;
  3693. bool negative;
  3694. };
  3695. #endif // __JUCE_BITARRAY_JUCEHEADER__
  3696. /********* End of inlined file: juce_BitArray.h *********/
  3697. #endif
  3698. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  3699. #endif
  3700. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  3701. #endif
  3702. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3703. /********* Start of inlined file: juce_MemoryBlock.h *********/
  3704. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3705. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3706. /**
  3707. A class to hold a resizable block of raw data.
  3708. */
  3709. class JUCE_API MemoryBlock
  3710. {
  3711. public:
  3712. /** Create an uninitialised block with 0 size. */
  3713. MemoryBlock() throw();
  3714. /** Creates a memory block with a given initial size.
  3715. @param initialSize the size of block to create
  3716. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3717. */
  3718. MemoryBlock (const int initialSize,
  3719. const bool initialiseToZero = false) throw();
  3720. /** Creates a copy of another memory block. */
  3721. MemoryBlock (const MemoryBlock& other) throw();
  3722. /** Creates a memory block using a copy of a block of data.
  3723. @param dataToInitialiseFrom some data to copy into this block
  3724. @param sizeInBytes how much space to use
  3725. */
  3726. MemoryBlock (const void* const dataToInitialiseFrom,
  3727. const int sizeInBytes) throw();
  3728. /** Destructor. */
  3729. ~MemoryBlock() throw();
  3730. /** Copies another memory block onto this one.
  3731. This block will be resized and copied to exactly match the other one.
  3732. */
  3733. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  3734. /** Compares two memory blocks.
  3735. @returns true only if the two blocks are the same size and have identical contents.
  3736. */
  3737. bool operator== (const MemoryBlock& other) const throw();
  3738. /** Compares two memory blocks.
  3739. @returns true if the two blocks are different sizes or have different contents.
  3740. */
  3741. bool operator!= (const MemoryBlock& other) const throw();
  3742. /** Returns a pointer to the data, casting it to any type of primitive data required.
  3743. Note that the pointer returned will probably become invalid when the
  3744. block is resized.
  3745. */
  3746. template <class DataType>
  3747. operator DataType*() const throw() { return (DataType*) data; }
  3748. /** Returns a void pointer to the data.
  3749. Note that the pointer returned will probably become invalid when the
  3750. block is resized.
  3751. */
  3752. void* getData() const throw() { return data; }
  3753. /** Returns a byte from the memory block.
  3754. This returns a reference, so you can also use it to set a byte.
  3755. */
  3756. char& operator[] (const int offset) const throw() { return data [offset]; }
  3757. /** Returns the block's current allocated size, in bytes. */
  3758. int getSize() const throw() { return size; }
  3759. /** Resizes the memory block.
  3760. This will try to keep as much of the block's current content as it can,
  3761. and can optionally be made to clear any new space that gets allocated at
  3762. the end of the block.
  3763. @param newSize the new desired size for the block
  3764. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3765. whether to clear the new section or just leave it
  3766. uninitialised
  3767. @see ensureSize
  3768. */
  3769. void setSize (const int newSize,
  3770. const bool initialiseNewSpaceToZero = false) throw();
  3771. /** Increases the block's size only if it's smaller than a given size.
  3772. @param minimumSize if the block is already bigger than this size, no action
  3773. will be taken; otherwise it will be increased to this size
  3774. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3775. whether to clear the new section or just leave it
  3776. uninitialised
  3777. @see setSize
  3778. */
  3779. void ensureSize (const int minimumSize,
  3780. const bool initialiseNewSpaceToZero = false) throw();
  3781. /** Fills the entire memory block with a repeated byte value.
  3782. This is handy for clearing a block of memory to zero.
  3783. */
  3784. void fillWith (const uint8 valueToUse) throw();
  3785. /** Adds another block of data to the end of this one.
  3786. This block's size will be increased accordingly.
  3787. */
  3788. void append (const void* const data,
  3789. const int numBytes) throw();
  3790. /** Copies data into this MemoryBlock from a memory address.
  3791. @param srcData the memory location of the data to copy into this block
  3792. @param destinationOffset the offset in this block at which the data being copied should begin
  3793. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3794. it will be clipped so not to do anything nasty)
  3795. */
  3796. void copyFrom (const void* srcData,
  3797. int destinationOffset,
  3798. int numBytes) throw();
  3799. /** Copies data from this MemoryBlock to a memory address.
  3800. @param destData the memory location to write to
  3801. @param sourceOffset the offset within this block from which the copied data will be read
  3802. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3803. zeros will be used for that portion of the data)
  3804. */
  3805. void copyTo (void* destData,
  3806. int sourceOffset,
  3807. int numBytes) const throw();
  3808. /** Chops out a section of the block.
  3809. This will remove a section of the memory block and close the gap around it,
  3810. shifting any subsequent data downwards and reducing the size of the block.
  3811. If the range specified goes beyond the size of the block, it will be clipped.
  3812. */
  3813. void removeSection (int startByte, int numBytesToRemove) throw();
  3814. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3815. characters in the system's default encoding. */
  3816. const String toString() const throw();
  3817. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3818. The block will be resized to the number of valid bytes read from the string.
  3819. Non-hex characters in the string will be ignored.
  3820. @see String::toHexString()
  3821. */
  3822. void loadFromHexString (const String& sourceHexString) throw();
  3823. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3824. void setBitRange (int bitRangeStart,
  3825. int numBits,
  3826. int binaryNumberToApply) throw();
  3827. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3828. int getBitRange (int bitRangeStart,
  3829. int numBitsToRead) const throw();
  3830. /** Returns a string of characters that represent the binary contents of this block.
  3831. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3832. of simple non-extended characters, e.g. for storage in XML.
  3833. @see fromBase64Encoding
  3834. */
  3835. const String toBase64Encoding() const throw();
  3836. /** Takes a string of encoded characters and turns it into binary data.
  3837. The string passed in must have been created by to64BitEncoding(), and this
  3838. block will be resized to recreate the original data block.
  3839. @see toBase64Encoding
  3840. */
  3841. bool fromBase64Encoding (const String& encodedString) throw();
  3842. juce_UseDebuggingNewOperator
  3843. private:
  3844. HeapBlock <char> data;
  3845. int size;
  3846. };
  3847. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3848. /********* End of inlined file: juce_MemoryBlock.h *********/
  3849. #endif
  3850. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  3851. /********* Start of inlined file: juce_OwnedArray.h *********/
  3852. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  3853. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  3854. /********* Start of inlined file: juce_ScopedPointer.h *********/
  3855. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  3856. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  3857. /**
  3858. This class holds a pointer which is automatically deleted when this object goes
  3859. out of scope.
  3860. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  3861. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  3862. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  3863. created objects.
  3864. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  3865. to an object. If you use the assignment operator to assign a different object to a
  3866. ScopedPointer, the old one will be automatically deleted.
  3867. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  3868. can use the release() method.
  3869. */
  3870. template <class ObjectType>
  3871. class JUCE_API ScopedPointer
  3872. {
  3873. public:
  3874. /** Creates a ScopedPointer containing a null pointer. */
  3875. inline ScopedPointer() : object (0)
  3876. {
  3877. }
  3878. /** Creates a ScopedPointer that owns the specified object. */
  3879. inline ScopedPointer (ObjectType* const objectToTakePossessionOf)
  3880. : object (objectToTakePossessionOf)
  3881. {
  3882. }
  3883. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  3884. Because a pointer can only belong to one ScopedPointer, this transfers
  3885. the pointer from the other object to this one, and the other object is reset to
  3886. be a null pointer.
  3887. */
  3888. ScopedPointer (ScopedPointer& objectToTransferFrom)
  3889. : object (objectToTransferFrom.object)
  3890. {
  3891. objectToTransferFrom.object = 0;
  3892. }
  3893. /** Destructor.
  3894. This will delete the object that this ScopedPointer currently refers to.
  3895. */
  3896. inline ~ScopedPointer() { delete object; }
  3897. /** Changes this ScopedPointer to point to a new object.
  3898. Because a pointer can only belong to one ScopedPointer, this transfers
  3899. the pointer from the other object to this one, and the other object is reset to
  3900. be a null pointer.
  3901. If this ScopedPointer already points to an object, that object
  3902. will first be deleted.
  3903. */
  3904. const ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  3905. {
  3906. if (this != objectToTransferFrom.getAddress())
  3907. {
  3908. // Two ScopedPointers should never be able to refer to the same object - if
  3909. // this happens, you must have done something dodgy!
  3910. jassert (object != objectToTransferFrom.object);
  3911. ObjectType* const oldObject = object;
  3912. object = objectToTransferFrom.object;
  3913. objectToTransferFrom.object = 0;
  3914. delete oldObject;
  3915. }
  3916. return *this;
  3917. }
  3918. /** Changes this ScopedPointer to point to a new object.
  3919. If this ScopedPointer already points to an object, that object
  3920. will first be deleted.
  3921. The pointer that you pass is may be null.
  3922. */
  3923. const ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  3924. {
  3925. if (object != newObjectToTakePossessionOf)
  3926. {
  3927. ObjectType* const oldObject = object;
  3928. object = newObjectToTakePossessionOf;
  3929. delete oldObject;
  3930. }
  3931. return *this;
  3932. }
  3933. /** Returns the object that this ScopedPointer refers to.
  3934. */
  3935. inline operator ObjectType*() const { return object; }
  3936. /** Returns the object that this ScopedPointer refers to.
  3937. */
  3938. inline ObjectType& operator*() const { return *object; }
  3939. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  3940. inline ObjectType* operator->() const { return object; }
  3941. /** Returns a pointer to the object by casting it to whatever type you need. */
  3942. template <class CastType>
  3943. inline operator CastType*() const { return static_cast <CastType*> (object); }
  3944. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  3945. inline ObjectType** operator&() const { return (ObjectType**) &object; }
  3946. /** Removes the current object from this ScopedPointer without deleting it.
  3947. This will return the current object, and set the ScopedPointer to a null pointer.
  3948. */
  3949. ObjectType* release() { ObjectType* const o = object; object = 0; return o; }
  3950. /** Compares the pointer with another pointer.
  3951. This can be handy for checking whether this is a null pointer.
  3952. */
  3953. inline bool operator== (const ObjectType* const otherPointer) const { return otherPointer == object; }
  3954. /** Compares the pointer with another pointer.
  3955. This can be handy for checking whether this is a null pointer.
  3956. */
  3957. inline bool operator!= (const ObjectType* const otherPointer) const { return otherPointer != object; }
  3958. /** Swaps this object with that of another ScopedPointer.
  3959. The two objects simply exchange their pointers.
  3960. */
  3961. void swapWith (ScopedPointer <ObjectType>& other)
  3962. {
  3963. // Two ScopedPointers should never be able to refer to the same object - if
  3964. // this happens, you must have done something dodgy!
  3965. jassert (object != other.object);
  3966. swapVariables (object, other.object);
  3967. }
  3968. private:
  3969. ObjectType* object;
  3970. // (Required as an alternative to the overloaded & operator).
  3971. ScopedPointer* getAddress() { return this; }
  3972. };
  3973. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  3974. /********* End of inlined file: juce_ScopedPointer.h *********/
  3975. /** An array designed for holding objects.
  3976. This holds a list of pointers to objects, and will automatically
  3977. delete the objects when they are removed from the array, or when the
  3978. array is itself deleted.
  3979. Declare it in the form: OwnedArray<MyObjectClass>
  3980. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  3981. After adding objects, they are 'owned' by the array and will be deleted when
  3982. removed or replaced.
  3983. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3984. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3985. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  3986. */
  3987. template <class ObjectClass,
  3988. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3989. class OwnedArray
  3990. {
  3991. public:
  3992. /** Creates an empty array.
  3993. @param granularity this is the size of increment by which the internal storage
  3994. used by the array will grow. Only change it from the default if you know the
  3995. array is going to be very big and needs to be able to grow efficiently.
  3996. */
  3997. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  3998. : data (granularity),
  3999. numUsed (0)
  4000. {
  4001. }
  4002. /** Deletes the array and also deletes any objects inside it.
  4003. To get rid of the array without deleting its objects, use its
  4004. clear (false) method before deleting it.
  4005. */
  4006. ~OwnedArray()
  4007. {
  4008. clear (true);
  4009. }
  4010. /** Clears the array, optionally deleting the objects inside it first. */
  4011. void clear (const bool deleteObjects = true)
  4012. {
  4013. lock.enter();
  4014. if (deleteObjects)
  4015. {
  4016. while (numUsed > 0)
  4017. delete data.elements [--numUsed];
  4018. }
  4019. data.setAllocatedSize (0);
  4020. numUsed = 0;
  4021. lock.exit();
  4022. }
  4023. /** Returns the number of items currently in the array.
  4024. @see operator[]
  4025. */
  4026. inline int size() const throw()
  4027. {
  4028. return numUsed;
  4029. }
  4030. /** Returns a pointer to the object at this index in the array.
  4031. If the index is out-of-range, this will return a null pointer, (and
  4032. it could be null anyway, because it's ok for the array to hold null
  4033. pointers as well as objects).
  4034. @see getUnchecked
  4035. */
  4036. inline ObjectClass* operator[] (const int index) const throw()
  4037. {
  4038. lock.enter();
  4039. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  4040. ? data.elements [index]
  4041. : (ObjectClass*) 0;
  4042. lock.exit();
  4043. return result;
  4044. }
  4045. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  4046. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  4047. it can be used when you're sure the index if always going to be legal.
  4048. */
  4049. inline ObjectClass* getUnchecked (const int index) const throw()
  4050. {
  4051. lock.enter();
  4052. jassert (((unsigned int) index) < (unsigned int) numUsed);
  4053. ObjectClass* const result = data.elements [index];
  4054. lock.exit();
  4055. return result;
  4056. }
  4057. /** Returns a pointer to the first object in the array.
  4058. This will return a null pointer if the array's empty.
  4059. @see getLast
  4060. */
  4061. inline ObjectClass* getFirst() const throw()
  4062. {
  4063. lock.enter();
  4064. ObjectClass* const result = (numUsed > 0) ? data.elements [0]
  4065. : (ObjectClass*) 0;
  4066. lock.exit();
  4067. return result;
  4068. }
  4069. /** Returns a pointer to the last object in the array.
  4070. This will return a null pointer if the array's empty.
  4071. @see getFirst
  4072. */
  4073. inline ObjectClass* getLast() const throw()
  4074. {
  4075. lock.enter();
  4076. ObjectClass* const result = (numUsed > 0) ? data.elements [numUsed - 1]
  4077. : (ObjectClass*) 0;
  4078. lock.exit();
  4079. return result;
  4080. }
  4081. /** Finds the index of an object which might be in the array.
  4082. @param objectToLookFor the object to look for
  4083. @returns the index at which the object was found, or -1 if it's not found
  4084. */
  4085. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  4086. {
  4087. int result = -1;
  4088. lock.enter();
  4089. ObjectClass* const* e = data.elements;
  4090. for (int i = numUsed; --i >= 0;)
  4091. {
  4092. if (objectToLookFor == *e)
  4093. {
  4094. result = (int) (e - data.elements);
  4095. break;
  4096. }
  4097. ++e;
  4098. }
  4099. lock.exit();
  4100. return result;
  4101. }
  4102. /** Returns true if the array contains a specified object.
  4103. @param objectToLookFor the object to look for
  4104. @returns true if the object is in the array
  4105. */
  4106. bool contains (const ObjectClass* const objectToLookFor) const throw()
  4107. {
  4108. lock.enter();
  4109. ObjectClass* const* e = data.elements;
  4110. int i = numUsed;
  4111. while (i >= 4)
  4112. {
  4113. if (objectToLookFor == *e
  4114. || objectToLookFor == *++e
  4115. || objectToLookFor == *++e
  4116. || objectToLookFor == *++e)
  4117. {
  4118. lock.exit();
  4119. return true;
  4120. }
  4121. i -= 4;
  4122. ++e;
  4123. }
  4124. while (i > 0)
  4125. {
  4126. if (objectToLookFor == *e)
  4127. {
  4128. lock.exit();
  4129. return true;
  4130. }
  4131. --i;
  4132. ++e;
  4133. }
  4134. lock.exit();
  4135. return false;
  4136. }
  4137. /** Appends a new object to the end of the array.
  4138. Note that the this object will be deleted by the OwnedArray when it
  4139. is removed, so be careful not to delete it somewhere else.
  4140. Also be careful not to add the same object to the array more than once,
  4141. as this will obviously cause deletion of dangling pointers.
  4142. @param newObject the new object to add to the array
  4143. @see set, insert, addIfNotAlreadyThere, addSorted
  4144. */
  4145. void add (const ObjectClass* const newObject) throw()
  4146. {
  4147. lock.enter();
  4148. data.ensureAllocatedSize (numUsed + 1);
  4149. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  4150. lock.exit();
  4151. }
  4152. /** Inserts a new object into the array at the given index.
  4153. Note that the this object will be deleted by the OwnedArray when it
  4154. is removed, so be careful not to delete it somewhere else.
  4155. If the index is less than 0 or greater than the size of the array, the
  4156. element will be added to the end of the array.
  4157. Otherwise, it will be inserted into the array, moving all the later elements
  4158. along to make room.
  4159. Be careful not to add the same object to the array more than once,
  4160. as this will obviously cause deletion of dangling pointers.
  4161. @param indexToInsertAt the index at which the new element should be inserted
  4162. @param newObject the new object to add to the array
  4163. @see add, addSorted, addIfNotAlreadyThere, set
  4164. */
  4165. void insert (int indexToInsertAt,
  4166. const ObjectClass* const newObject) throw()
  4167. {
  4168. if (indexToInsertAt >= 0)
  4169. {
  4170. lock.enter();
  4171. if (indexToInsertAt > numUsed)
  4172. indexToInsertAt = numUsed;
  4173. data.ensureAllocatedSize (numUsed + 1);
  4174. ObjectClass** const e = data.elements + indexToInsertAt;
  4175. const int numToMove = numUsed - indexToInsertAt;
  4176. if (numToMove > 0)
  4177. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  4178. *e = const_cast <ObjectClass*> (newObject);
  4179. ++numUsed;
  4180. lock.exit();
  4181. }
  4182. else
  4183. {
  4184. add (newObject);
  4185. }
  4186. }
  4187. /** Appends a new object at the end of the array as long as the array doesn't
  4188. already contain it.
  4189. If the array already contains a matching object, nothing will be done.
  4190. @param newObject the new object to add to the array
  4191. */
  4192. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  4193. {
  4194. lock.enter();
  4195. if (! contains (newObject))
  4196. add (newObject);
  4197. lock.exit();
  4198. }
  4199. /** Replaces an object in the array with a different one.
  4200. If the index is less than zero, this method does nothing.
  4201. If the index is beyond the end of the array, the new object is added to the end of the array.
  4202. Be careful not to add the same object to the array more than once,
  4203. as this will obviously cause deletion of dangling pointers.
  4204. @param indexToChange the index whose value you want to change
  4205. @param newObject the new value to set for this index.
  4206. @param deleteOldElement whether to delete the object that's being replaced with the new one
  4207. @see add, insert, remove
  4208. */
  4209. void set (const int indexToChange,
  4210. const ObjectClass* const newObject,
  4211. const bool deleteOldElement = true)
  4212. {
  4213. if (indexToChange >= 0)
  4214. {
  4215. ScopedPointer <ObjectClass> toDelete;
  4216. lock.enter();
  4217. if (indexToChange < numUsed)
  4218. {
  4219. if (deleteOldElement)
  4220. {
  4221. toDelete = data.elements [indexToChange];
  4222. if (toDelete == newObject)
  4223. toDelete = 0;
  4224. }
  4225. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  4226. }
  4227. else
  4228. {
  4229. data.ensureAllocatedSize (numUsed + 1);
  4230. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  4231. }
  4232. lock.exit();
  4233. }
  4234. }
  4235. /** Inserts a new object into the array assuming that the array is sorted.
  4236. This will use a comparator to find the position at which the new object
  4237. should go. If the array isn't sorted, the behaviour of this
  4238. method will be unpredictable.
  4239. @param comparator the comparator to use to compare the elements - see the sort method
  4240. for details about this object's structure
  4241. @param newObject the new object to insert to the array
  4242. @see add, sort, indexOfSorted
  4243. */
  4244. template <class ElementComparator>
  4245. void addSorted (ElementComparator& comparator,
  4246. ObjectClass* const newObject) throw()
  4247. {
  4248. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4249. // avoids getting warning messages about the parameter being unused
  4250. lock.enter();
  4251. insert (findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed), newObject);
  4252. lock.exit();
  4253. }
  4254. /** Finds the index of an object in the array, assuming that the array is sorted.
  4255. This will use a comparator to do a binary-chop to find the index of the given
  4256. element, if it exists. If the array isn't sorted, the behaviour of this
  4257. method will be unpredictable.
  4258. @param comparator the comparator to use to compare the elements - see the sort()
  4259. method for details about the form this object should take
  4260. @param objectToLookFor the object to search for
  4261. @returns the index of the element, or -1 if it's not found
  4262. @see addSorted, sort
  4263. */
  4264. template <class ElementComparator>
  4265. int indexOfSorted (ElementComparator& comparator,
  4266. const ObjectClass* const objectToLookFor) const throw()
  4267. {
  4268. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4269. // avoids getting warning messages about the parameter being unused
  4270. lock.enter();
  4271. int start = 0;
  4272. int end = numUsed;
  4273. for (;;)
  4274. {
  4275. if (start >= end)
  4276. {
  4277. lock.exit();
  4278. return -1;
  4279. }
  4280. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  4281. {
  4282. lock.exit();
  4283. return start;
  4284. }
  4285. else
  4286. {
  4287. const int halfway = (start + end) >> 1;
  4288. if (halfway == start)
  4289. {
  4290. lock.exit();
  4291. return -1;
  4292. }
  4293. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  4294. start = halfway;
  4295. else
  4296. end = halfway;
  4297. }
  4298. }
  4299. }
  4300. /** Removes an object from the array.
  4301. This will remove the object at a given index (optionally also
  4302. deleting it) and move back all the subsequent objects to close the gap.
  4303. If the index passed in is out-of-range, nothing will happen.
  4304. @param indexToRemove the index of the element to remove
  4305. @param deleteObject whether to delete the object that is removed
  4306. @see removeObject, removeRange
  4307. */
  4308. void remove (const int indexToRemove,
  4309. const bool deleteObject = true)
  4310. {
  4311. ScopedPointer <ObjectClass> toDelete;
  4312. lock.enter();
  4313. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4314. {
  4315. ObjectClass** const e = data.elements + indexToRemove;
  4316. if (deleteObject)
  4317. toDelete = *e;
  4318. --numUsed;
  4319. const int numToShift = numUsed - indexToRemove;
  4320. if (numToShift > 0)
  4321. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  4322. if ((numUsed << 1) < data.numAllocated)
  4323. minimiseStorageOverheads();
  4324. }
  4325. lock.exit();
  4326. }
  4327. /** Removes a specified object from the array.
  4328. If the item isn't found, no action is taken.
  4329. @param objectToRemove the object to try to remove
  4330. @param deleteObject whether to delete the object (if it's found)
  4331. @see remove, removeRange
  4332. */
  4333. void removeObject (const ObjectClass* const objectToRemove,
  4334. const bool deleteObject = true)
  4335. {
  4336. lock.enter();
  4337. ObjectClass** e = data.elements;
  4338. for (int i = numUsed; --i >= 0;)
  4339. {
  4340. if (objectToRemove == *e)
  4341. {
  4342. remove ((int) (e - data.elements), deleteObject);
  4343. break;
  4344. }
  4345. ++e;
  4346. }
  4347. lock.exit();
  4348. }
  4349. /** Removes a range of objects from the array.
  4350. This will remove a set of objects, starting from the given index,
  4351. and move any subsequent elements down to close the gap.
  4352. If the range extends beyond the bounds of the array, it will
  4353. be safely clipped to the size of the array.
  4354. @param startIndex the index of the first object to remove
  4355. @param numberToRemove how many objects should be removed
  4356. @param deleteObjects whether to delete the objects that get removed
  4357. @see remove, removeObject
  4358. */
  4359. void removeRange (int startIndex,
  4360. const int numberToRemove,
  4361. const bool deleteObjects = true)
  4362. {
  4363. lock.enter();
  4364. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4365. startIndex = jlimit (0, numUsed, startIndex);
  4366. if (endIndex > startIndex)
  4367. {
  4368. if (deleteObjects)
  4369. {
  4370. for (int i = startIndex; i < endIndex; ++i)
  4371. {
  4372. delete data.elements [i];
  4373. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  4374. }
  4375. }
  4376. const int rangeSize = endIndex - startIndex;
  4377. ObjectClass** e = data.elements + startIndex;
  4378. int numToShift = numUsed - endIndex;
  4379. numUsed -= rangeSize;
  4380. while (--numToShift >= 0)
  4381. {
  4382. *e = e [rangeSize];
  4383. ++e;
  4384. }
  4385. if ((numUsed << 1) < data.numAllocated)
  4386. minimiseStorageOverheads();
  4387. }
  4388. lock.exit();
  4389. }
  4390. /** Removes the last n objects from the array.
  4391. @param howManyToRemove how many objects to remove from the end of the array
  4392. @param deleteObjects whether to also delete the objects that are removed
  4393. @see remove, removeObject, removeRange
  4394. */
  4395. void removeLast (int howManyToRemove = 1,
  4396. const bool deleteObjects = true)
  4397. {
  4398. lock.enter();
  4399. if (howManyToRemove >= numUsed)
  4400. {
  4401. clear (deleteObjects);
  4402. }
  4403. else
  4404. {
  4405. while (--howManyToRemove >= 0)
  4406. remove (numUsed - 1, deleteObjects);
  4407. }
  4408. lock.exit();
  4409. }
  4410. /** Swaps a pair of objects in the array.
  4411. If either of the indexes passed in is out-of-range, nothing will happen,
  4412. otherwise the two objects at these positions will be exchanged.
  4413. */
  4414. void swap (const int index1,
  4415. const int index2) throw()
  4416. {
  4417. lock.enter();
  4418. if (((unsigned int) index1) < (unsigned int) numUsed
  4419. && ((unsigned int) index2) < (unsigned int) numUsed)
  4420. {
  4421. swapVariables (data.elements [index1],
  4422. data.elements [index2]);
  4423. }
  4424. lock.exit();
  4425. }
  4426. /** Moves one of the objects to a different position.
  4427. This will move the object to a specified index, shuffling along
  4428. any intervening elements as required.
  4429. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4430. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4431. @param currentIndex the index of the object to be moved. If this isn't a
  4432. valid index, then nothing will be done
  4433. @param newIndex the index at which you'd like this object to end up. If this
  4434. is less than zero, it will be moved to the end of the array
  4435. */
  4436. void move (const int currentIndex,
  4437. int newIndex) throw()
  4438. {
  4439. if (currentIndex != newIndex)
  4440. {
  4441. lock.enter();
  4442. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4443. {
  4444. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4445. newIndex = numUsed - 1;
  4446. ObjectClass* const value = data.elements [currentIndex];
  4447. if (newIndex > currentIndex)
  4448. {
  4449. memmove (data.elements + currentIndex,
  4450. data.elements + currentIndex + 1,
  4451. (newIndex - currentIndex) * sizeof (ObjectClass*));
  4452. }
  4453. else
  4454. {
  4455. memmove (data.elements + newIndex + 1,
  4456. data.elements + newIndex,
  4457. (currentIndex - newIndex) * sizeof (ObjectClass*));
  4458. }
  4459. data.elements [newIndex] = value;
  4460. }
  4461. lock.exit();
  4462. }
  4463. }
  4464. /** This swaps the contents of this array with those of another array.
  4465. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  4466. because it just swaps their internal pointers.
  4467. */
  4468. template <class OtherArrayType>
  4469. void swapWithArray (OtherArrayType& otherArray) throw()
  4470. {
  4471. lock.enter();
  4472. otherArray.lock.enter();
  4473. swapVariables <int> (numUsed, otherArray.numUsed);
  4474. swapVariables <ObjectClass**> (data.elements, otherArray.data.elements);
  4475. swapVariables <int> (data.numAllocated, otherArray.data.numAllocated);
  4476. otherArray.lock.exit();
  4477. lock.exit();
  4478. }
  4479. /** Reduces the amount of storage being used by the array.
  4480. Arrays typically allocate slightly more storage than they need, and after
  4481. removing elements, they may have quite a lot of unused space allocated.
  4482. This method will reduce the amount of allocated storage to a minimum.
  4483. */
  4484. void minimiseStorageOverheads() throw()
  4485. {
  4486. lock.enter();
  4487. if (numUsed == 0)
  4488. {
  4489. data.setAllocatedSize (0);
  4490. }
  4491. else
  4492. {
  4493. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  4494. if (newAllocation < data.numAllocated)
  4495. data.setAllocatedSize (newAllocation);
  4496. }
  4497. lock.exit();
  4498. }
  4499. /** Increases the array's internal storage to hold a minimum number of elements.
  4500. Calling this before adding a large known number of elements means that
  4501. the array won't have to keep dynamically resizing itself as the elements
  4502. are added, and it'll therefore be more efficient.
  4503. */
  4504. void ensureStorageAllocated (const int minNumElements) throw()
  4505. {
  4506. data.ensureAllocatedSize (minNumElements);
  4507. }
  4508. /** Sorts the elements in the array.
  4509. This will use a comparator object to sort the elements into order. The object
  4510. passed must have a method of the form:
  4511. @code
  4512. int compareElements (ElementType first, ElementType second);
  4513. @endcode
  4514. ..and this method must return:
  4515. - a value of < 0 if the first comes before the second
  4516. - a value of 0 if the two objects are equivalent
  4517. - a value of > 0 if the second comes before the first
  4518. To improve performance, the compareElements() method can be declared as static or const.
  4519. @param comparator the comparator to use for comparing elements.
  4520. @param retainOrderOfEquivalentItems if this is true, then items
  4521. which the comparator says are equivalent will be
  4522. kept in the order in which they currently appear
  4523. in the array. This is slower to perform, but may
  4524. be important in some cases. If it's false, a faster
  4525. algorithm is used, but equivalent elements may be
  4526. rearranged.
  4527. @see sortArray, indexOfSorted
  4528. */
  4529. template <class ElementComparator>
  4530. void sort (ElementComparator& comparator,
  4531. const bool retainOrderOfEquivalentItems = false) const throw()
  4532. {
  4533. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4534. // avoids getting warning messages about the parameter being unused
  4535. lock.enter();
  4536. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4537. lock.exit();
  4538. }
  4539. /** Locks the array's CriticalSection.
  4540. Of course if the type of section used is a DummyCriticalSection, this won't
  4541. have any effect.
  4542. @see unlockArray
  4543. */
  4544. void lockArray() const throw()
  4545. {
  4546. lock.enter();
  4547. }
  4548. /** Unlocks the array's CriticalSection.
  4549. Of course if the type of section used is a DummyCriticalSection, this won't
  4550. have any effect.
  4551. @see lockArray
  4552. */
  4553. void unlockArray() const throw()
  4554. {
  4555. lock.exit();
  4556. }
  4557. juce_UseDebuggingNewOperator
  4558. private:
  4559. ArrayAllocationBase <ObjectClass*> data;
  4560. int numUsed;
  4561. TypeOfCriticalSectionToUse lock;
  4562. // disallow copy constructor and assignment
  4563. OwnedArray (const OwnedArray&);
  4564. const OwnedArray& operator= (const OwnedArray&);
  4565. };
  4566. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  4567. /********* End of inlined file: juce_OwnedArray.h *********/
  4568. #endif
  4569. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  4570. /********* Start of inlined file: juce_PropertySet.h *********/
  4571. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  4572. #define __JUCE_PROPERTYSET_JUCEHEADER__
  4573. /********* Start of inlined file: juce_StringPairArray.h *********/
  4574. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  4575. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  4576. /********* Start of inlined file: juce_StringArray.h *********/
  4577. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  4578. #define __JUCE_STRINGARRAY_JUCEHEADER__
  4579. #ifndef DOXYGEN
  4580. // (used in StringArray::appendNumbersToDuplicates)
  4581. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4582. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4583. #endif
  4584. /**
  4585. A special array for holding a list of strings.
  4586. @see String, StringPairArray
  4587. */
  4588. class JUCE_API StringArray
  4589. {
  4590. public:
  4591. /** Creates an empty string array */
  4592. StringArray() throw();
  4593. /** Creates a copy of another string array */
  4594. StringArray (const StringArray& other) throw();
  4595. /** Creates a copy of an array of string literals.
  4596. @param strings an array of strings to add. Null pointers in the array will be
  4597. treated as empty strings
  4598. @param numberOfStrings how many items there are in the array
  4599. */
  4600. StringArray (const juce_wchar** const strings,
  4601. const int numberOfStrings) throw();
  4602. /** Creates a copy of an array of string literals.
  4603. @param strings an array of strings to add. Null pointers in the array will be
  4604. treated as empty strings
  4605. @param numberOfStrings how many items there are in the array
  4606. */
  4607. StringArray (const char** const strings,
  4608. const int numberOfStrings) throw();
  4609. /** Creates a copy of a null-terminated array of string literals.
  4610. Each item from the array passed-in is added, until it encounters a null pointer,
  4611. at which point it stops.
  4612. */
  4613. StringArray (const juce_wchar** const strings) throw();
  4614. /** Creates a copy of a null-terminated array of string literals.
  4615. Each item from the array passed-in is added, until it encounters a null pointer,
  4616. at which point it stops.
  4617. */
  4618. StringArray (const char** const strings) throw();
  4619. /** Destructor. */
  4620. virtual ~StringArray() throw();
  4621. /** Copies the contents of another string array into this one */
  4622. const StringArray& operator= (const StringArray& other) throw();
  4623. /** Compares two arrays.
  4624. Comparisons are case-sensitive.
  4625. @returns true only if the other array contains exactly the same strings in the same order
  4626. */
  4627. bool operator== (const StringArray& other) const throw();
  4628. /** Compares two arrays.
  4629. Comparisons are case-sensitive.
  4630. @returns false if the other array contains exactly the same strings in the same order
  4631. */
  4632. bool operator!= (const StringArray& other) const throw();
  4633. /** Returns the number of strings in the array */
  4634. inline int size() const throw() { return strings.size(); };
  4635. /** Returns one of the strings from the array.
  4636. If the index is out-of-range, an empty string is returned.
  4637. Obviously the reference returned shouldn't be stored for later use, as the
  4638. string it refers to may disappear when the array changes.
  4639. */
  4640. const String& operator[] (const int index) const throw();
  4641. /** Searches for a string in the array.
  4642. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4643. @returns true if the string is found inside the array
  4644. */
  4645. bool contains (const String& stringToLookFor,
  4646. const bool ignoreCase = false) const throw();
  4647. /** Searches for a string in the array.
  4648. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4649. @param stringToLookFor the string to try to find
  4650. @param ignoreCase whether the comparison should be case-insensitive
  4651. @param startIndex the first index to start searching from
  4652. @returns the index of the first occurrence of the string in this array,
  4653. or -1 if it isn't found.
  4654. */
  4655. int indexOf (const String& stringToLookFor,
  4656. const bool ignoreCase = false,
  4657. int startIndex = 0) const throw();
  4658. /** Appends a string at the end of the array. */
  4659. void add (const String& stringToAdd) throw();
  4660. /** Inserts a string into the array.
  4661. This will insert a string into the array at the given index, moving
  4662. up the other elements to make room for it.
  4663. If the index is less than zero or greater than the size of the array,
  4664. the new string will be added to the end of the array.
  4665. */
  4666. void insert (const int index,
  4667. const String& stringToAdd) throw();
  4668. /** Adds a string to the array as long as it's not already in there.
  4669. The search can optionally be case-insensitive.
  4670. */
  4671. void addIfNotAlreadyThere (const String& stringToAdd,
  4672. const bool ignoreCase = false) throw();
  4673. /** Replaces one of the strings in the array with another one.
  4674. If the index is higher than the array's size, the new string will be
  4675. added to the end of the array; if it's less than zero nothing happens.
  4676. */
  4677. void set (const int index,
  4678. const String& newString) throw();
  4679. /** Appends some strings from another array to the end of this one.
  4680. @param other the array to add
  4681. @param startIndex the first element of the other array to add
  4682. @param numElementsToAdd the maximum number of elements to add (if this is
  4683. less than zero, they are all added)
  4684. */
  4685. void addArray (const StringArray& other,
  4686. int startIndex = 0,
  4687. int numElementsToAdd = -1) throw();
  4688. /** Breaks up a string into tokens and adds them to this array.
  4689. This will tokenise the given string using whitespace characters as the
  4690. token delimiters, and will add these tokens to the end of the array.
  4691. @returns the number of tokens added
  4692. */
  4693. int addTokens (const tchar* const stringToTokenise,
  4694. const bool preserveQuotedStrings) throw();
  4695. /** Breaks up a string into tokens and adds them to this array.
  4696. This will tokenise the given string (using the string passed in to define the
  4697. token delimiters), and will add these tokens to the end of the array.
  4698. @param stringToTokenise the string to tokenise
  4699. @param breakCharacters a string of characters, any of which will be considered
  4700. to be a token delimiter.
  4701. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4702. which are treated as quotes. Any text occurring
  4703. between quotes is not broken up into tokens.
  4704. @returns the number of tokens added
  4705. */
  4706. int addTokens (const tchar* const stringToTokenise,
  4707. const tchar* breakCharacters,
  4708. const tchar* quoteCharacters) throw();
  4709. /** Breaks up a string into lines and adds them to this array.
  4710. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4711. to the array. Line-break characters are omitted from the strings that are added to
  4712. the array.
  4713. */
  4714. int addLines (const tchar* stringToBreakUp) throw();
  4715. /** Removes all elements from the array. */
  4716. void clear() throw();
  4717. /** Removes a string from the array.
  4718. If the index is out-of-range, no action will be taken.
  4719. */
  4720. void remove (const int index) throw();
  4721. /** Finds a string in the array and removes it.
  4722. This will remove the first occurrence of the given string from the array. The
  4723. comparison may be case-insensitive depending on the ignoreCase parameter.
  4724. */
  4725. void removeString (const String& stringToRemove,
  4726. const bool ignoreCase = false) throw();
  4727. /** Removes any duplicated elements from the array.
  4728. If any string appears in the array more than once, only the first occurrence of
  4729. it will be retained.
  4730. @param ignoreCase whether to use a case-insensitive comparison
  4731. */
  4732. void removeDuplicates (const bool ignoreCase) throw();
  4733. /** Removes empty strings from the array.
  4734. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4735. characters will also be removed
  4736. */
  4737. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4738. /** Moves one of the strings to a different position.
  4739. This will move the string to a specified index, shuffling along
  4740. any intervening elements as required.
  4741. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4742. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4743. @param currentIndex the index of the value to be moved. If this isn't a
  4744. valid index, then nothing will be done
  4745. @param newIndex the index at which you'd like this value to end up. If this
  4746. is less than zero, the value will be moved to the end
  4747. of the array
  4748. */
  4749. void move (const int currentIndex, int newIndex) throw();
  4750. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4751. void trim() throw();
  4752. /** Adds numbers to the strings in the array, to make each string unique.
  4753. This will add numbers to the ends of groups of similar strings.
  4754. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4755. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4756. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4757. also has a number appended to it.
  4758. @param preNumberString when adding a number, this string is added before the number
  4759. @param postNumberString this string is appended after any numbers that are added
  4760. */
  4761. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4762. const bool appendNumberToFirstInstance,
  4763. const tchar* const preNumberString = defaultPreNumberString,
  4764. const tchar* const postNumberString = defaultPostNumberString) throw();
  4765. /** Joins the strings in the array together into one string.
  4766. This will join a range of elements from the array into a string, separating
  4767. them with a given string.
  4768. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4769. @param separatorString the string to insert between all the strings
  4770. @param startIndex the first element to join
  4771. @param numberOfElements how many elements to join together. If this is less
  4772. than zero, all available elements will be used.
  4773. */
  4774. const String joinIntoString (const String& separatorString,
  4775. int startIndex = 0,
  4776. int numberOfElements = -1) const throw();
  4777. /** Sorts the array into alphabetical order.
  4778. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4779. */
  4780. void sort (const bool ignoreCase) throw();
  4781. /** Reduces the amount of storage being used by the array.
  4782. Arrays typically allocate slightly more storage than they need, and after
  4783. removing elements, they may have quite a lot of unused space allocated.
  4784. This method will reduce the amount of allocated storage to a minimum.
  4785. */
  4786. void minimiseStorageOverheads() throw();
  4787. juce_UseDebuggingNewOperator
  4788. private:
  4789. OwnedArray <String> strings;
  4790. };
  4791. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4792. /********* End of inlined file: juce_StringArray.h *********/
  4793. /**
  4794. A container for holding a set of strings which are keyed by another string.
  4795. @see StringArray
  4796. */
  4797. class JUCE_API StringPairArray
  4798. {
  4799. public:
  4800. /** Creates an empty array */
  4801. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  4802. /** Creates a copy of another array */
  4803. StringPairArray (const StringPairArray& other) throw();
  4804. /** Destructor. */
  4805. ~StringPairArray() throw();
  4806. /** Copies the contents of another string array into this one */
  4807. const StringPairArray& operator= (const StringPairArray& other) throw();
  4808. /** Compares two arrays.
  4809. Comparisons are case-sensitive.
  4810. @returns true only if the other array contains exactly the same strings with the same keys
  4811. */
  4812. bool operator== (const StringPairArray& other) const throw();
  4813. /** Compares two arrays.
  4814. Comparisons are case-sensitive.
  4815. @returns false if the other array contains exactly the same strings with the same keys
  4816. */
  4817. bool operator!= (const StringPairArray& other) const throw();
  4818. /** Finds the value corresponding to a key string.
  4819. If no such key is found, this will just return an empty string. To check whether
  4820. a given key actually exists (because it might actually be paired with an empty string), use
  4821. the getAllKeys() method to obtain a list.
  4822. Obviously the reference returned shouldn't be stored for later use, as the
  4823. string it refers to may disappear when the array changes.
  4824. @see getValue
  4825. */
  4826. const String& operator[] (const String& key) const throw();
  4827. /** Finds the value corresponding to a key string.
  4828. If no such key is found, this will just return the value provided as a default.
  4829. @see operator[]
  4830. */
  4831. const String getValue (const String& key, const String& defaultReturnValue) const;
  4832. /** Returns a list of all keys in the array. */
  4833. const StringArray& getAllKeys() const throw() { return keys; }
  4834. /** Returns a list of all values in the array. */
  4835. const StringArray& getAllValues() const throw() { return values; }
  4836. /** Returns the number of strings in the array */
  4837. inline int size() const throw() { return keys.size(); };
  4838. /** Adds or amends a key/value pair.
  4839. If a value already exists with this key, its value will be overwritten,
  4840. otherwise the key/value pair will be added to the array.
  4841. */
  4842. void set (const String& key,
  4843. const String& value) throw();
  4844. /** Adds the items from another array to this one.
  4845. This is equivalent to using set() to add each of the pairs from the other array.
  4846. */
  4847. void addArray (const StringPairArray& other);
  4848. /** Removes all elements from the array. */
  4849. void clear() throw();
  4850. /** Removes a string from the array based on its key.
  4851. If the key isn't found, nothing will happen.
  4852. */
  4853. void remove (const String& key) throw();
  4854. /** Removes a string from the array based on its index.
  4855. If the index is out-of-range, no action will be taken.
  4856. */
  4857. void remove (const int index) throw();
  4858. /** Indicates whether to use a case-insensitive search when looking up a key string.
  4859. */
  4860. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  4861. /** Returns a descriptive string containing the items.
  4862. This is handy for dumping the contents of an array.
  4863. */
  4864. const String getDescription() const;
  4865. /** Reduces the amount of storage being used by the array.
  4866. Arrays typically allocate slightly more storage than they need, and after
  4867. removing elements, they may have quite a lot of unused space allocated.
  4868. This method will reduce the amount of allocated storage to a minimum.
  4869. */
  4870. void minimiseStorageOverheads() throw();
  4871. juce_UseDebuggingNewOperator
  4872. private:
  4873. StringArray keys, values;
  4874. bool ignoreCase;
  4875. };
  4876. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  4877. /********* End of inlined file: juce_StringPairArray.h *********/
  4878. /********* Start of inlined file: juce_XmlElement.h *********/
  4879. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  4880. #define __JUCE_XMLELEMENT_JUCEHEADER__
  4881. /********* Start of inlined file: juce_OutputStream.h *********/
  4882. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4883. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4884. /********* Start of inlined file: juce_InputStream.h *********/
  4885. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  4886. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  4887. /** The base class for streams that read data.
  4888. Input and output streams are used throughout the library - subclasses can override
  4889. some or all of the virtual functions to implement their behaviour.
  4890. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  4891. */
  4892. class JUCE_API InputStream
  4893. {
  4894. public:
  4895. /** Destructor. */
  4896. virtual ~InputStream() {}
  4897. /** Returns the total number of bytes available for reading in this stream.
  4898. Note that this is the number of bytes available from the start of the
  4899. stream, not from the current position.
  4900. If the size of the stream isn't actually known, this may return -1.
  4901. */
  4902. virtual int64 getTotalLength() = 0;
  4903. /** Returns true if the stream has no more data to read. */
  4904. virtual bool isExhausted() = 0;
  4905. /** Reads a set of bytes from the stream into a memory buffer.
  4906. This is the only read method that subclasses actually need to implement, as the
  4907. InputStream base class implements the other read methods in terms of this one (although
  4908. it's often more efficient for subclasses to implement them directly).
  4909. @param destBuffer the destination buffer for the data
  4910. @param maxBytesToRead the maximum number of bytes to read - make sure the
  4911. memory block passed in is big enough to contain this
  4912. many bytes.
  4913. @returns the actual number of bytes that were read, which may be less than
  4914. maxBytesToRead if the stream is exhausted before it gets that far
  4915. */
  4916. virtual int read (void* destBuffer,
  4917. int maxBytesToRead) = 0;
  4918. /** Reads a byte from the stream.
  4919. If the stream is exhausted, this will return zero.
  4920. @see OutputStream::writeByte
  4921. */
  4922. virtual char readByte();
  4923. /** Reads a boolean from the stream.
  4924. The bool is encoded as a single byte - 1 for true, 0 for false.
  4925. If the stream is exhausted, this will return false.
  4926. @see OutputStream::writeBool
  4927. */
  4928. virtual bool readBool();
  4929. /** Reads two bytes from the stream as a little-endian 16-bit value.
  4930. If the next two bytes read are byte1 and byte2, this returns
  4931. (byte1 | (byte2 << 8)).
  4932. If the stream is exhausted partway through reading the bytes, this will return zero.
  4933. @see OutputStream::writeShort, readShortBigEndian
  4934. */
  4935. virtual short readShort();
  4936. /** Reads two bytes from the stream as a little-endian 16-bit value.
  4937. If the next two bytes read are byte1 and byte2, this returns
  4938. (byte2 | (byte1 << 8)).
  4939. If the stream is exhausted partway through reading the bytes, this will return zero.
  4940. @see OutputStream::writeShortBigEndian, readShort
  4941. */
  4942. virtual short readShortBigEndian();
  4943. /** Reads four bytes from the stream as a little-endian 32-bit value.
  4944. If the next four bytes are byte1 to byte4, this returns
  4945. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  4946. If the stream is exhausted partway through reading the bytes, this will return zero.
  4947. @see OutputStream::writeInt, readIntBigEndian
  4948. */
  4949. virtual int readInt();
  4950. /** Reads four bytes from the stream as a big-endian 32-bit value.
  4951. If the next four bytes are byte1 to byte4, this returns
  4952. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  4953. If the stream is exhausted partway through reading the bytes, this will return zero.
  4954. @see OutputStream::writeIntBigEndian, readInt
  4955. */
  4956. virtual int readIntBigEndian();
  4957. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  4958. If the next eight bytes are byte1 to byte8, this returns
  4959. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  4960. If the stream is exhausted partway through reading the bytes, this will return zero.
  4961. @see OutputStream::writeInt64, readInt64BigEndian
  4962. */
  4963. virtual int64 readInt64();
  4964. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  4965. If the next eight bytes are byte1 to byte8, this returns
  4966. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  4967. If the stream is exhausted partway through reading the bytes, this will return zero.
  4968. @see OutputStream::writeInt64BigEndian, readInt64
  4969. */
  4970. virtual int64 readInt64BigEndian();
  4971. /** Reads four bytes as a 32-bit floating point value.
  4972. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  4973. If the stream is exhausted partway through reading the bytes, this will return zero.
  4974. @see OutputStream::writeFloat, readDouble
  4975. */
  4976. virtual float readFloat();
  4977. /** Reads four bytes as a 32-bit floating point value.
  4978. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  4979. If the stream is exhausted partway through reading the bytes, this will return zero.
  4980. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  4981. */
  4982. virtual float readFloatBigEndian();
  4983. /** Reads eight bytes as a 64-bit floating point value.
  4984. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  4985. If the stream is exhausted partway through reading the bytes, this will return zero.
  4986. @see OutputStream::writeDouble, readFloat
  4987. */
  4988. virtual double readDouble();
  4989. /** Reads eight bytes as a 64-bit floating point value.
  4990. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4991. If the stream is exhausted partway through reading the bytes, this will return zero.
  4992. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4993. */
  4994. virtual double readDoubleBigEndian();
  4995. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4996. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4997. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4998. @see OutputStream::writeCompressedInt()
  4999. */
  5000. virtual int readCompressedInt();
  5001. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  5002. This will read up to the next "\n" or "\r\n" or end-of-stream.
  5003. After this call, the stream's position will be left pointing to the next character
  5004. following the line-feed, but the linefeeds aren't included in the string that
  5005. is returned.
  5006. */
  5007. virtual const String readNextLine();
  5008. /** Reads a zero-terminated UTF8 string from the stream.
  5009. This will read characters from the stream until it hits a zero character or
  5010. end-of-stream.
  5011. @see OutputStream::writeString, readEntireStreamAsString
  5012. */
  5013. virtual const String readString();
  5014. /** Tries to read the whole stream and turn it into a string.
  5015. This will read from the stream's current position until the end-of-stream, and
  5016. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  5017. */
  5018. virtual const String readEntireStreamAsString();
  5019. /** Reads from the stream and appends the data to a MemoryBlock.
  5020. @param destBlock the block to append the data onto
  5021. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  5022. of bytes that will be read - if it's negative, data
  5023. will be read until the stream is exhausted.
  5024. @returns the number of bytes that were added to the memory block
  5025. */
  5026. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  5027. int maxNumBytesToRead = -1);
  5028. /** Returns the offset of the next byte that will be read from the stream.
  5029. @see setPosition
  5030. */
  5031. virtual int64 getPosition() = 0;
  5032. /** Tries to move the current read position of the stream.
  5033. The position is an absolute number of bytes from the stream's start.
  5034. Some streams might not be able to do this, in which case they should do
  5035. nothing and return false. Others might be able to manage it by resetting
  5036. themselves and skipping to the correct position, although this is
  5037. obviously a bit slow.
  5038. @returns true if the stream manages to reposition itself correctly
  5039. @see getPosition
  5040. */
  5041. virtual bool setPosition (int64 newPosition) = 0;
  5042. /** Reads and discards a number of bytes from the stream.
  5043. Some input streams might implement this efficiently, but the base
  5044. class will just keep reading data until the requisite number of bytes
  5045. have been done.
  5046. */
  5047. virtual void skipNextBytes (int64 numBytesToSkip);
  5048. juce_UseDebuggingNewOperator
  5049. protected:
  5050. InputStream() throw() {}
  5051. };
  5052. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  5053. /********* End of inlined file: juce_InputStream.h *********/
  5054. /**
  5055. The base class for streams that write data to some kind of destination.
  5056. Input and output streams are used throughout the library - subclasses can override
  5057. some or all of the virtual functions to implement their behaviour.
  5058. @see InputStream, MemoryOutputStream, FileOutputStream
  5059. */
  5060. class JUCE_API OutputStream
  5061. {
  5062. public:
  5063. /** Destructor.
  5064. Some subclasses might want to do things like call flush() during their
  5065. destructors.
  5066. */
  5067. virtual ~OutputStream();
  5068. /** If the stream is using a buffer, this will ensure it gets written
  5069. out to the destination. */
  5070. virtual void flush() = 0;
  5071. /** Tries to move the stream's output position.
  5072. Not all streams will be able to seek to a new position - this will return
  5073. false if it fails to work.
  5074. @see getPosition
  5075. */
  5076. virtual bool setPosition (int64 newPosition) = 0;
  5077. /** Returns the stream's current position.
  5078. @see setPosition
  5079. */
  5080. virtual int64 getPosition() = 0;
  5081. /** Writes a block of data to the stream.
  5082. When creating a subclass of OutputStream, this is the only write method
  5083. that needs to be overloaded - the base class has methods for writing other
  5084. types of data which use this to do the work.
  5085. @returns false if the write operation fails for some reason
  5086. */
  5087. virtual bool write (const void* dataToWrite,
  5088. int howManyBytes) = 0;
  5089. /** Writes a single byte to the stream.
  5090. @see InputStream::readByte
  5091. */
  5092. virtual void writeByte (char byte);
  5093. /** Writes a boolean to the stream.
  5094. This is encoded as a byte - either 1 or 0.
  5095. @see InputStream::readBool
  5096. */
  5097. virtual void writeBool (bool boolValue);
  5098. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  5099. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  5100. @see InputStream::readShort
  5101. */
  5102. virtual void writeShort (short value);
  5103. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  5104. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  5105. @see InputStream::readShortBigEndian
  5106. */
  5107. virtual void writeShortBigEndian (short value);
  5108. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  5109. @see InputStream::readInt
  5110. */
  5111. virtual void writeInt (int value);
  5112. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  5113. @see InputStream::readIntBigEndian
  5114. */
  5115. virtual void writeIntBigEndian (int value);
  5116. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  5117. @see InputStream::readInt64
  5118. */
  5119. virtual void writeInt64 (int64 value);
  5120. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  5121. @see InputStream::readInt64BigEndian
  5122. */
  5123. virtual void writeInt64BigEndian (int64 value);
  5124. /** Writes a 32-bit floating point value to the stream.
  5125. The binary 32-bit encoding of the float is written as a little-endian int.
  5126. @see InputStream::readFloat
  5127. */
  5128. virtual void writeFloat (float value);
  5129. /** Writes a 32-bit floating point value to the stream.
  5130. The binary 32-bit encoding of the float is written as a big-endian int.
  5131. @see InputStream::readFloatBigEndian
  5132. */
  5133. virtual void writeFloatBigEndian (float value);
  5134. /** Writes a 64-bit floating point value to the stream.
  5135. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  5136. @see InputStream::readDouble
  5137. */
  5138. virtual void writeDouble (double value);
  5139. /** Writes a 64-bit floating point value to the stream.
  5140. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  5141. @see InputStream::readDoubleBigEndian
  5142. */
  5143. virtual void writeDoubleBigEndian (double value);
  5144. /** Writes a condensed encoding of a 32-bit integer.
  5145. If you're storing a lot of integers which are unlikely to have very large values,
  5146. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  5147. under 0xffff only 3 bytes, etc.
  5148. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  5149. @see InputStream::readCompressedInt
  5150. */
  5151. virtual void writeCompressedInt (int value);
  5152. /** Stores a string in the stream.
  5153. This isn't the method to use if you're trying to append text to the end of a
  5154. text-file! It's intended for storing a string for later retrieval
  5155. by InputStream::readString.
  5156. It writes the string to the stream as UTF8, with a null character terminating it.
  5157. For appending text to a file, instead use writeText, printf, or operator<<
  5158. @see InputStream::readString, writeText, printf, operator<<
  5159. */
  5160. virtual void writeString (const String& text);
  5161. /** Writes a string of text to the stream.
  5162. It can either write it as 8-bit system-encoded characters, or as unicode, and
  5163. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  5164. should only be done at the start of a file).
  5165. The method also replaces '\\n' characters in the text with '\\r\\n'.
  5166. */
  5167. virtual void writeText (const String& text,
  5168. const bool asUnicode,
  5169. const bool writeUnicodeHeaderBytes);
  5170. /** Writes a string of text to the stream.
  5171. @see writeText
  5172. */
  5173. virtual void printf (const char* format, ...);
  5174. /** Reads data from an input stream and writes it to this stream.
  5175. @param source the stream to read from
  5176. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  5177. less than zero, it will keep reading until the input
  5178. is exhausted)
  5179. */
  5180. virtual int writeFromInputStream (InputStream& source,
  5181. int maxNumBytesToWrite);
  5182. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  5183. virtual OutputStream& operator<< (const int number);
  5184. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  5185. virtual OutputStream& operator<< (const double number);
  5186. /** Writes a character to the stream. */
  5187. virtual OutputStream& operator<< (const char character);
  5188. /** Writes a null-terminated string to the stream. */
  5189. virtual OutputStream& operator<< (const char* const text);
  5190. /** Writes a null-terminated unicode text string to the stream, converting it
  5191. to 8-bit characters in the default system encoding. */
  5192. virtual OutputStream& operator<< (const juce_wchar* const text);
  5193. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  5194. virtual OutputStream& operator<< (const String& text);
  5195. juce_UseDebuggingNewOperator
  5196. protected:
  5197. OutputStream() throw();
  5198. };
  5199. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  5200. /********* End of inlined file: juce_OutputStream.h *********/
  5201. /********* Start of inlined file: juce_File.h *********/
  5202. #ifndef __JUCE_FILE_JUCEHEADER__
  5203. #define __JUCE_FILE_JUCEHEADER__
  5204. /********* Start of inlined file: juce_Time.h *********/
  5205. #ifndef __JUCE_TIME_JUCEHEADER__
  5206. #define __JUCE_TIME_JUCEHEADER__
  5207. /********* Start of inlined file: juce_RelativeTime.h *********/
  5208. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5209. #define __JUCE_RELATIVETIME_JUCEHEADER__
  5210. /** A relative measure of time.
  5211. The time is stored as a number of seconds, at double-precision floating
  5212. point accuracy, and may be positive or negative.
  5213. If you need an absolute time, (i.e. a date + time), see the Time class.
  5214. */
  5215. class JUCE_API RelativeTime
  5216. {
  5217. public:
  5218. /** Creates a RelativeTime.
  5219. @param seconds the number of seconds, which may be +ve or -ve.
  5220. @see milliseconds, minutes, hours, days, weeks
  5221. */
  5222. explicit RelativeTime (const double seconds = 0.0) throw();
  5223. /** Copies another relative time. */
  5224. RelativeTime (const RelativeTime& other) throw();
  5225. /** Copies another relative time. */
  5226. const RelativeTime& operator= (const RelativeTime& other) throw();
  5227. /** Destructor. */
  5228. ~RelativeTime() throw();
  5229. /** Creates a new RelativeTime object representing a number of milliseconds.
  5230. @see minutes, hours, days, weeks
  5231. */
  5232. static const RelativeTime milliseconds (const int milliseconds) throw();
  5233. /** Creates a new RelativeTime object representing a number of milliseconds.
  5234. @see minutes, hours, days, weeks
  5235. */
  5236. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  5237. /** Creates a new RelativeTime object representing a number of minutes.
  5238. @see milliseconds, hours, days, weeks
  5239. */
  5240. static const RelativeTime minutes (const double numberOfMinutes) throw();
  5241. /** Creates a new RelativeTime object representing a number of hours.
  5242. @see milliseconds, minutes, days, weeks
  5243. */
  5244. static const RelativeTime hours (const double numberOfHours) throw();
  5245. /** Creates a new RelativeTime object representing a number of days.
  5246. @see milliseconds, minutes, hours, weeks
  5247. */
  5248. static const RelativeTime days (const double numberOfDays) throw();
  5249. /** Creates a new RelativeTime object representing a number of weeks.
  5250. @see milliseconds, minutes, hours, days
  5251. */
  5252. static const RelativeTime weeks (const double numberOfWeeks) throw();
  5253. /** Returns the number of milliseconds this time represents.
  5254. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5255. */
  5256. int64 inMilliseconds() const throw();
  5257. /** Returns the number of seconds this time represents.
  5258. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  5259. */
  5260. double inSeconds() const throw() { return seconds; }
  5261. /** Returns the number of minutes this time represents.
  5262. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  5263. */
  5264. double inMinutes() const throw();
  5265. /** Returns the number of hours this time represents.
  5266. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  5267. */
  5268. double inHours() const throw();
  5269. /** Returns the number of days this time represents.
  5270. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  5271. */
  5272. double inDays() const throw();
  5273. /** Returns the number of weeks this time represents.
  5274. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  5275. */
  5276. double inWeeks() const throw();
  5277. /** Returns a readable textual description of the time.
  5278. The exact format of the string returned will depend on
  5279. the magnitude of the time - e.g.
  5280. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  5281. so that only the two most significant units are printed.
  5282. The returnValueForZeroTime value is the result that is returned if the
  5283. length is zero. Depending on your application you might want to use this
  5284. to return something more relevant like "empty" or "0 secs", etc.
  5285. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5286. */
  5287. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  5288. /** Compares two RelativeTimes. */
  5289. bool operator== (const RelativeTime& other) const throw();
  5290. /** Compares two RelativeTimes. */
  5291. bool operator!= (const RelativeTime& other) const throw();
  5292. /** Compares two RelativeTimes. */
  5293. bool operator> (const RelativeTime& other) const throw();
  5294. /** Compares two RelativeTimes. */
  5295. bool operator< (const RelativeTime& other) const throw();
  5296. /** Compares two RelativeTimes. */
  5297. bool operator>= (const RelativeTime& other) const throw();
  5298. /** Compares two RelativeTimes. */
  5299. bool operator<= (const RelativeTime& other) const throw();
  5300. /** Adds another RelativeTime to this one and returns the result. */
  5301. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  5302. /** Subtracts another RelativeTime from this one and returns the result. */
  5303. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  5304. /** Adds a number of seconds to this RelativeTime and returns the result. */
  5305. const RelativeTime operator+ (const double secondsToAdd) const throw();
  5306. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  5307. const RelativeTime operator- (const double secondsToSubtract) const throw();
  5308. /** Adds another RelativeTime to this one. */
  5309. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  5310. /** Subtracts another RelativeTime from this one. */
  5311. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  5312. /** Adds a number of seconds to this time. */
  5313. const RelativeTime& operator+= (const double secondsToAdd) throw();
  5314. /** Subtracts a number of seconds from this time. */
  5315. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  5316. juce_UseDebuggingNewOperator
  5317. private:
  5318. double seconds;
  5319. };
  5320. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  5321. /********* End of inlined file: juce_RelativeTime.h *********/
  5322. /**
  5323. Holds an absolute date and time.
  5324. Internally, the time is stored at millisecond precision.
  5325. @see RelativeTime
  5326. */
  5327. class JUCE_API Time
  5328. {
  5329. public:
  5330. /** Creates a Time object.
  5331. This default constructor creates a time of 1st January 1970, (which is
  5332. represented internally as 0ms).
  5333. To create a time object representing the current time, use getCurrentTime().
  5334. @see getCurrentTime
  5335. */
  5336. Time() throw();
  5337. /** Creates a copy of another Time object. */
  5338. Time (const Time& other) throw();
  5339. /** Creates a time based on a number of milliseconds.
  5340. The internal millisecond count is set to 0 (1st January 1970). To create a
  5341. time object set to the current time, use getCurrentTime().
  5342. @param millisecondsSinceEpoch the number of milliseconds since the unix
  5343. 'epoch' (midnight Jan 1st 1970).
  5344. @see getCurrentTime, currentTimeMillis
  5345. */
  5346. Time (const int64 millisecondsSinceEpoch) throw();
  5347. /** Creates a time from a set of date components.
  5348. The timezone is assumed to be whatever the system is using as its locale.
  5349. @param year the year, in 4-digit format, e.g. 2004
  5350. @param month the month, in the range 0 to 11
  5351. @param day the day of the month, in the range 1 to 31
  5352. @param hours hours in 24-hour clock format, 0 to 23
  5353. @param minutes minutes 0 to 59
  5354. @param seconds seconds 0 to 59
  5355. @param milliseconds milliseconds 0 to 999
  5356. @param useLocalTime if true, encode using the current machine's local time; if
  5357. false, it will always work in GMT.
  5358. */
  5359. Time (const int year,
  5360. const int month,
  5361. const int day,
  5362. const int hours,
  5363. const int minutes,
  5364. const int seconds = 0,
  5365. const int milliseconds = 0,
  5366. const bool useLocalTime = true) throw();
  5367. /** Destructor. */
  5368. ~Time() throw();
  5369. /** Copies this time from another one. */
  5370. const Time& operator= (const Time& other) throw();
  5371. /** Returns a Time object that is set to the current system time.
  5372. @see currentTimeMillis
  5373. */
  5374. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  5375. /** Returns the time as a number of milliseconds.
  5376. @returns the number of milliseconds this Time object represents, since
  5377. midnight jan 1st 1970.
  5378. @see getMilliseconds
  5379. */
  5380. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  5381. /** Returns the year.
  5382. A 4-digit format is used, e.g. 2004.
  5383. */
  5384. int getYear() const throw();
  5385. /** Returns the number of the month.
  5386. The value returned is in the range 0 to 11.
  5387. @see getMonthName
  5388. */
  5389. int getMonth() const throw();
  5390. /** Returns the name of the month.
  5391. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  5392. it'll return the long form, e.g. "January"
  5393. @see getMonth
  5394. */
  5395. const String getMonthName (const bool threeLetterVersion) const throw();
  5396. /** Returns the day of the month.
  5397. The value returned is in the range 1 to 31.
  5398. */
  5399. int getDayOfMonth() const throw();
  5400. /** Returns the number of the day of the week.
  5401. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  5402. */
  5403. int getDayOfWeek() const throw();
  5404. /** Returns the name of the weekday.
  5405. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  5406. false, it'll return the full version, e.g. "Tuesday".
  5407. */
  5408. const String getWeekdayName (const bool threeLetterVersion) const throw();
  5409. /** Returns the number of hours since midnight.
  5410. This is in 24-hour clock format, in the range 0 to 23.
  5411. @see getHoursInAmPmFormat, isAfternoon
  5412. */
  5413. int getHours() const throw();
  5414. /** Returns true if the time is in the afternoon.
  5415. So it returns true for "PM", false for "AM".
  5416. @see getHoursInAmPmFormat, getHours
  5417. */
  5418. bool isAfternoon() const throw();
  5419. /** Returns the hours in 12-hour clock format.
  5420. This will return a value 1 to 12 - use isAfternoon() to find out
  5421. whether this is in the afternoon or morning.
  5422. @see getHours, isAfternoon
  5423. */
  5424. int getHoursInAmPmFormat() const throw();
  5425. /** Returns the number of minutes, 0 to 59. */
  5426. int getMinutes() const throw();
  5427. /** Returns the number of seconds, 0 to 59. */
  5428. int getSeconds() const throw();
  5429. /** Returns the number of milliseconds, 0 to 999.
  5430. Unlike toMilliseconds(), this just returns the position within the
  5431. current second rather than the total number since the epoch.
  5432. @see toMilliseconds
  5433. */
  5434. int getMilliseconds() const throw();
  5435. /** Returns true if the local timezone uses a daylight saving correction. */
  5436. bool isDaylightSavingTime() const throw();
  5437. /** Returns a 3-character string to indicate the local timezone. */
  5438. const String getTimeZone() const throw();
  5439. /** Quick way of getting a string version of a date and time.
  5440. For a more powerful way of formatting the date and time, see the formatted() method.
  5441. @param includeDate whether to include the date in the string
  5442. @param includeTime whether to include the time in the string
  5443. @param includeSeconds if the time is being included, this provides an option not to include
  5444. the seconds in it
  5445. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  5446. hour notation.
  5447. @see formatted
  5448. */
  5449. const String toString (const bool includeDate,
  5450. const bool includeTime,
  5451. const bool includeSeconds = true,
  5452. const bool use24HourClock = false) const throw();
  5453. /** Converts this date/time to a string with a user-defined format.
  5454. This uses the C strftime() function to format this time as a string. To save you
  5455. looking it up, these are the escape codes that strftime uses (other codes might
  5456. work on some platforms and not others, but these are the common ones):
  5457. %a is replaced by the locale's abbreviated weekday name.
  5458. %A is replaced by the locale's full weekday name.
  5459. %b is replaced by the locale's abbreviated month name.
  5460. %B is replaced by the locale's full month name.
  5461. %c is replaced by the locale's appropriate date and time representation.
  5462. %d is replaced by the day of the month as a decimal number [01,31].
  5463. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  5464. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  5465. %j is replaced by the day of the year as a decimal number [001,366].
  5466. %m is replaced by the month as a decimal number [01,12].
  5467. %M is replaced by the minute as a decimal number [00,59].
  5468. %p is replaced by the locale's equivalent of either a.m. or p.m.
  5469. %S is replaced by the second as a decimal number [00,61].
  5470. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  5471. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  5472. %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.
  5473. %x is replaced by the locale's appropriate date representation.
  5474. %X is replaced by the locale's appropriate time representation.
  5475. %y is replaced by the year without century as a decimal number [00,99].
  5476. %Y is replaced by the year with century as a decimal number.
  5477. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  5478. %% is replaced by %.
  5479. @see toString
  5480. */
  5481. const String formatted (const tchar* const format) const throw();
  5482. /** Adds a RelativeTime to this time and returns the result. */
  5483. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  5484. /** Subtracts a RelativeTime from this time and returns the result. */
  5485. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  5486. /** Returns the relative time difference between this time and another one. */
  5487. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  5488. /** Compares two Time objects. */
  5489. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  5490. /** Compares two Time objects. */
  5491. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  5492. /** Compares two Time objects. */
  5493. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  5494. /** Compares two Time objects. */
  5495. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  5496. /** Compares two Time objects. */
  5497. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  5498. /** Compares two Time objects. */
  5499. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  5500. /** Tries to set the computer's clock.
  5501. @returns true if this succeeds, although depending on the system, the
  5502. application might not have sufficient privileges to do this.
  5503. */
  5504. bool setSystemTimeToThisTime() const throw();
  5505. /** Returns the name of a day of the week.
  5506. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  5507. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  5508. false, it'll return the full version, e.g. "Tuesday".
  5509. */
  5510. static const String getWeekdayName (int dayNumber,
  5511. const bool threeLetterVersion) throw();
  5512. /** Returns the name of one of the months.
  5513. @param monthNumber the month, 0 to 11
  5514. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  5515. it'll return the long form, e.g. "January"
  5516. */
  5517. static const String getMonthName (int monthNumber,
  5518. const bool threeLetterVersion) throw();
  5519. // Static methods for getting system timers directly..
  5520. /** Returns the current system time.
  5521. Returns the number of milliseconds since midnight jan 1st 1970.
  5522. Should be accurate to within a few millisecs, depending on platform,
  5523. hardware, etc.
  5524. */
  5525. static int64 currentTimeMillis() throw();
  5526. /** Returns the number of millisecs since system startup.
  5527. Should be accurate to within a few millisecs, depending on platform,
  5528. hardware, etc.
  5529. @see getApproximateMillisecondCounter
  5530. */
  5531. static uint32 getMillisecondCounter() throw();
  5532. /** Returns the number of millisecs since system startup.
  5533. Same as getMillisecondCounter(), but returns a more accurate value, using
  5534. the high-res timer.
  5535. @see getMillisecondCounter
  5536. */
  5537. static double getMillisecondCounterHiRes() throw();
  5538. /** Waits until the getMillisecondCounter() reaches a given value.
  5539. This will make the thread sleep as efficiently as it can while it's waiting.
  5540. */
  5541. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  5542. /** Less-accurate but faster version of getMillisecondCounter().
  5543. This will return the last value that getMillisecondCounter() returned, so doesn't
  5544. need to make a system call, but is less accurate - it shouldn't be more than
  5545. 100ms away from the correct time, though, so is still accurate enough for a
  5546. lot of purposes.
  5547. @see getMillisecondCounter
  5548. */
  5549. static uint32 getApproximateMillisecondCounter() throw();
  5550. // High-resolution timers..
  5551. /** Returns the current high-resolution counter's tick-count.
  5552. This is a similar idea to getMillisecondCounter(), but with a higher
  5553. resolution.
  5554. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  5555. secondsToHighResolutionTicks
  5556. */
  5557. static int64 getHighResolutionTicks() throw();
  5558. /** Returns the resolution of the high-resolution counter in ticks per second.
  5559. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  5560. secondsToHighResolutionTicks
  5561. */
  5562. static int64 getHighResolutionTicksPerSecond() throw();
  5563. /** Converts a number of high-resolution ticks into seconds.
  5564. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  5565. secondsToHighResolutionTicks
  5566. */
  5567. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  5568. /** Converts a number seconds into high-resolution ticks.
  5569. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  5570. highResolutionTicksToSeconds
  5571. */
  5572. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  5573. private:
  5574. int64 millisSinceEpoch;
  5575. };
  5576. #endif // __JUCE_TIME_JUCEHEADER__
  5577. /********* End of inlined file: juce_Time.h *********/
  5578. class FileInputStream;
  5579. class FileOutputStream;
  5580. /**
  5581. Represents a local file or directory.
  5582. This class encapsulates the absolute pathname of a file or directory, and
  5583. has methods for finding out about the file and changing its properties.
  5584. To read or write to the file, there are methods for returning an input or
  5585. output stream.
  5586. @see FileInputStream, FileOutputStream
  5587. */
  5588. class JUCE_API File
  5589. {
  5590. public:
  5591. /** Creates an (invalid) file object.
  5592. The file is initially set to an empty path, so getFullPath() will return
  5593. an empty string, and comparing the file to File::nonexistent will return
  5594. true.
  5595. You can use its operator= method to point it at a proper file.
  5596. */
  5597. File() {}
  5598. /** Creates a file from an absolute path.
  5599. If the path supplied is a relative path, it is taken to be relative
  5600. to the current working directory (see File::getCurrentWorkingDirectory()),
  5601. but this isn't a recommended way of creating a file, because you
  5602. never know what the CWD is going to be.
  5603. On the Mac/Linux, the path can include "~" notation for referring to
  5604. user home directories.
  5605. */
  5606. File (const String& path);
  5607. /** Creates a copy of another file object. */
  5608. File (const File& other);
  5609. /** Destructor. */
  5610. ~File() {}
  5611. /** Sets the file based on an absolute pathname.
  5612. If the path supplied is a relative path, it is taken to be relative
  5613. to the current working directory (see File::getCurrentWorkingDirectory()),
  5614. but this isn't a recommended way of creating a file, because you
  5615. never know what the CWD is going to be.
  5616. On the Mac/Linux, the path can include "~" notation for referring to
  5617. user home directories.
  5618. */
  5619. const File& operator= (const String& newFilePath);
  5620. /** Copies from another file object. */
  5621. const File& operator= (const File& otherFile);
  5622. /** This static constant is used for referring to an 'invalid' file. */
  5623. static const File nonexistent;
  5624. /** Checks whether the file actually exists.
  5625. @returns true if the file exists, either as a file or a directory.
  5626. @see existsAsFile, isDirectory
  5627. */
  5628. bool exists() const;
  5629. /** Checks whether the file exists and is a file rather than a directory.
  5630. @returns true only if this is a real file, false if it's a directory
  5631. or doesn't exist
  5632. @see exists, isDirectory
  5633. */
  5634. bool existsAsFile() const;
  5635. /** Checks whether the file is a directory that exists.
  5636. @returns true only if the file is a directory which actually exists, so
  5637. false if it's a file or doesn't exist at all
  5638. @see exists, existsAsFile
  5639. */
  5640. bool isDirectory() const;
  5641. /** Returns the size of the file in bytes.
  5642. @returns the number of bytes in the file, or 0 if it doesn't exist.
  5643. */
  5644. int64 getSize() const;
  5645. /** Utility function to convert a file size in bytes to a neat string description.
  5646. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  5647. 2000000 would produce "2 MB", etc.
  5648. */
  5649. static const String descriptionOfSizeInBytes (const int64 bytes);
  5650. /** Returns the complete, absolute path of this file.
  5651. This includes the filename and all its parent folders. On Windows it'll
  5652. also include the drive letter prefix; on Mac or Linux it'll be a complete
  5653. path starting from the root folder.
  5654. If you just want the file's name, you should use getFileName() or
  5655. getFileNameWithoutExtension().
  5656. @see getFileName, getRelativePathFrom
  5657. */
  5658. const String& getFullPathName() const { return fullPath; }
  5659. /** Returns the last section of the pathname.
  5660. Returns just the final part of the path - e.g. if the whole path
  5661. is "/moose/fish/foo.txt" this will return "foo.txt".
  5662. For a directory, it returns the final part of the path - e.g. for the
  5663. directory "/moose/fish" it'll return "fish".
  5664. If the filename begins with a dot, it'll return the whole filename, e.g. for
  5665. "/moose/.fish", it'll return ".fish"
  5666. @see getFullPathName, getFileNameWithoutExtension
  5667. */
  5668. const String getFileName() const;
  5669. /** Creates a relative path that refers to a file relatively to a given directory.
  5670. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  5671. would return "../../foo.txt".
  5672. If it's not possible to navigate from one file to the other, an absolute
  5673. path is returned. If the paths are invalid, an empty string may also be
  5674. returned.
  5675. @param directoryToBeRelativeTo the directory which the resultant string will
  5676. be relative to. If this is actually a file rather than
  5677. a directory, its parent directory will be used instead.
  5678. If it doesn't exist, it's assumed to be a directory.
  5679. @see getChildFile, isAbsolutePath
  5680. */
  5681. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  5682. /** Returns the file's extension.
  5683. Returns the file extension of this file, also including the dot.
  5684. e.g. "/moose/fish/foo.txt" would return ".txt"
  5685. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  5686. */
  5687. const String getFileExtension() const;
  5688. /** Checks whether the file has a given extension.
  5689. @param extensionToTest the extension to look for - it doesn't matter whether or
  5690. not this string has a dot at the start, so ".wav" and "wav"
  5691. will have the same effect. The comparison used is
  5692. case-insensitve. To compare with multiple extensions, this
  5693. parameter can contain multiple strings, separated by semi-colons -
  5694. so, for example: hasFileExtension (".jpeg;png;gif") would return
  5695. true if the file has any of those three extensions.
  5696. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  5697. */
  5698. bool hasFileExtension (const String& extensionToTest) const;
  5699. /** Returns a version of this file with a different file extension.
  5700. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  5701. @param newExtension the new extension, either with or without a dot at the start (this
  5702. doesn't make any difference). To get remove a file's extension altogether,
  5703. pass an empty string into this function.
  5704. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  5705. */
  5706. const File withFileExtension (const String& newExtension) const;
  5707. /** Returns the last part of the filename, without its file extension.
  5708. e.g. for "/moose/fish/foo.txt" this will return "foo".
  5709. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  5710. */
  5711. const String getFileNameWithoutExtension() const;
  5712. /** Returns a 32-bit hash-code that identifies this file.
  5713. This is based on the filename. Obviously it's possible, although unlikely, that
  5714. two files will have the same hash-code.
  5715. */
  5716. int hashCode() const;
  5717. /** Returns a 64-bit hash-code that identifies this file.
  5718. This is based on the filename. Obviously it's possible, although unlikely, that
  5719. two files will have the same hash-code.
  5720. */
  5721. int64 hashCode64() const;
  5722. /** Returns a file based on a relative path.
  5723. This will find a child file or directory of the current object.
  5724. e.g.
  5725. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  5726. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  5727. If the string is actually an absolute path, it will be treated as such, e.g.
  5728. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  5729. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  5730. */
  5731. const File getChildFile (String relativePath) const;
  5732. /** Returns a file which is in the same directory as this one.
  5733. This is equivalent to getParentDirectory().getChildFile (name).
  5734. @see getChildFile, getParentDirectory
  5735. */
  5736. const File getSiblingFile (const String& siblingFileName) const;
  5737. /** Returns the directory that contains this file or directory.
  5738. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  5739. */
  5740. const File getParentDirectory() const;
  5741. /** Checks whether a file is somewhere inside a directory.
  5742. Returns true if this file is somewhere inside a subdirectory of the directory
  5743. that is passed in. Neither file actually has to exist, because the function
  5744. just checks the paths for similarities.
  5745. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  5746. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  5747. */
  5748. bool isAChildOf (const File& potentialParentDirectory) const;
  5749. /** Chooses a filename relative to this one that doesn't already exist.
  5750. If this file is a directory, this will return a child file of this
  5751. directory that doesn't exist, by adding numbers to a prefix and suffix until
  5752. it finds one that isn't already there.
  5753. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  5754. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  5755. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  5756. @param prefix the string to use for the filename before the number
  5757. @param suffix the string to add to the filename after the number
  5758. @param putNumbersInBrackets if true, this will create filenames in the
  5759. format "prefix(number)suffix", if false, it will leave the
  5760. brackets out.
  5761. */
  5762. const File getNonexistentChildFile (const String& prefix,
  5763. const String& suffix,
  5764. bool putNumbersInBrackets = true) const;
  5765. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  5766. If this file doesn't exist, this will just return itself, otherwise it
  5767. will return an appropriate sibling that doesn't exist, e.g. if a file
  5768. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  5769. @param putNumbersInBrackets whether to add brackets around the numbers that
  5770. get appended to the new filename.
  5771. */
  5772. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const;
  5773. /** Compares the pathnames for two files. */
  5774. bool operator== (const File& otherFile) const;
  5775. /** Compares the pathnames for two files. */
  5776. bool operator!= (const File& otherFile) const;
  5777. /** Checks whether a file can be created or written to.
  5778. @returns true if it's possible to create and write to this file. If the file
  5779. doesn't already exist, this will check its parent directory to
  5780. see if writing is allowed.
  5781. @see setReadOnly
  5782. */
  5783. bool hasWriteAccess() const;
  5784. /** Changes the write-permission of a file or directory.
  5785. @param shouldBeReadOnly whether to add or remove write-permission
  5786. @param applyRecursively if the file is a directory and this is true, it will
  5787. recurse through all the subfolders changing the permissions
  5788. of all files
  5789. @returns true if it manages to change the file's permissions.
  5790. @see hasWriteAccess
  5791. */
  5792. bool setReadOnly (const bool shouldBeReadOnly,
  5793. const bool applyRecursively = false) const;
  5794. /** Returns true if this file is a hidden or system file.
  5795. The criteria for deciding whether a file is hidden are platform-dependent.
  5796. */
  5797. bool isHidden() const;
  5798. /** If this file is a link, this returns the file that it points to.
  5799. If this file isn't actually link, it'll just return itself.
  5800. */
  5801. const File getLinkedTarget() const;
  5802. /** Returns the last modification time of this file.
  5803. @returns the time, or an invalid time if the file doesn't exist.
  5804. @see setLastModificationTime, getLastAccessTime, getCreationTime
  5805. */
  5806. const Time getLastModificationTime() const;
  5807. /** Returns the last time this file was accessed.
  5808. @returns the time, or an invalid time if the file doesn't exist.
  5809. @see setLastAccessTime, getLastModificationTime, getCreationTime
  5810. */
  5811. const Time getLastAccessTime() const;
  5812. /** Returns the time that this file was created.
  5813. @returns the time, or an invalid time if the file doesn't exist.
  5814. @see getLastModificationTime, getLastAccessTime
  5815. */
  5816. const Time getCreationTime() const;
  5817. /** Changes the modification time for this file.
  5818. @param newTime the time to apply to the file
  5819. @returns true if it manages to change the file's time.
  5820. @see getLastModificationTime, setLastAccessTime, setCreationTime
  5821. */
  5822. bool setLastModificationTime (const Time& newTime) const;
  5823. /** Changes the last-access time for this file.
  5824. @param newTime the time to apply to the file
  5825. @returns true if it manages to change the file's time.
  5826. @see getLastAccessTime, setLastModificationTime, setCreationTime
  5827. */
  5828. bool setLastAccessTime (const Time& newTime) const;
  5829. /** Changes the creation date for this file.
  5830. @param newTime the time to apply to the file
  5831. @returns true if it manages to change the file's time.
  5832. @see getCreationTime, setLastModificationTime, setLastAccessTime
  5833. */
  5834. bool setCreationTime (const Time& newTime) const;
  5835. /** If possible, this will try to create a version string for the given file.
  5836. The OS may be able to look at the file and give a version for it - e.g. with
  5837. executables, bundles, dlls, etc. If no version is available, this will
  5838. return an empty string.
  5839. */
  5840. const String getVersion() const;
  5841. /** Creates an empty file if it doesn't already exist.
  5842. If the file that this object refers to doesn't exist, this will create a file
  5843. of zero size.
  5844. If it already exists or is a directory, this method will do nothing.
  5845. @returns true if the file has been created (or if it already existed).
  5846. @see createDirectory
  5847. */
  5848. bool create() const;
  5849. /** Creates a new directory for this filename.
  5850. This will try to create the file as a directory, and fill also create
  5851. any parent directories it needs in order to complete the operation.
  5852. @returns true if the directory has been created successfully, (or if it
  5853. already existed beforehand).
  5854. @see create
  5855. */
  5856. bool createDirectory() const;
  5857. /** Deletes a file.
  5858. If this file is actually a directory, it may not be deleted correctly if it
  5859. contains files. See deleteRecursively() as a better way of deleting directories.
  5860. @returns true if the file has been successfully deleted (or if it didn't exist to
  5861. begin with).
  5862. @see deleteRecursively
  5863. */
  5864. bool deleteFile() const;
  5865. /** Deletes a file or directory and all its subdirectories.
  5866. If this file is a directory, this will try to delete it and all its subfolders. If
  5867. it's just a file, it will just try to delete the file.
  5868. @returns true if the file and all its subfolders have been successfully deleted
  5869. (or if it didn't exist to begin with).
  5870. @see deleteFile
  5871. */
  5872. bool deleteRecursively() const;
  5873. /** Moves this file or folder to the trash.
  5874. @returns true if the operation succeeded. It could fail if the trash is full, or
  5875. if the file is write-protected, so you should check the return value
  5876. and act appropriately.
  5877. */
  5878. bool moveToTrash() const;
  5879. /** Moves or renames a file.
  5880. Tries to move a file to a different location.
  5881. If the target file already exists, this will attempt to delete it first, and
  5882. will fail if this can't be done.
  5883. Note that the destination file isn't the directory to put it in, it's the actual
  5884. filename that you want the new file to have.
  5885. @returns true if the operation succeeds
  5886. */
  5887. bool moveFileTo (const File& targetLocation) const;
  5888. /** Copies a file.
  5889. Tries to copy a file to a different location.
  5890. If the target file already exists, this will attempt to delete it first, and
  5891. will fail if this can't be done.
  5892. @returns true if the operation succeeds
  5893. */
  5894. bool copyFileTo (const File& targetLocation) const;
  5895. /** Copies a directory.
  5896. Tries to copy an entire directory, recursively.
  5897. If this file isn't a directory or if any target files can't be created, this
  5898. will return false.
  5899. @param newDirectory the directory that this one should be copied to. Note that this
  5900. is the name of the actual directory to create, not the directory
  5901. into which the new one should be placed, so there must be enough
  5902. write privileges to create it if it doesn't exist. Any files inside
  5903. it will be overwritten by similarly named ones that are copied.
  5904. */
  5905. bool copyDirectoryTo (const File& newDirectory) const;
  5906. /** Used in file searching, to specify whether to return files, directories, or both.
  5907. */
  5908. enum TypesOfFileToFind
  5909. {
  5910. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5911. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5912. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5913. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5914. };
  5915. /** Searches inside a directory for files matching a wildcard pattern.
  5916. Assuming that this file is a directory, this method will search it
  5917. for either files or subdirectories whose names match a filename pattern.
  5918. @param results an array to which File objects will be added for the
  5919. files that the search comes up with
  5920. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5921. return files, directories, or both. If the ignoreHiddenFiles flag
  5922. is also added to this value, hidden files won't be returned
  5923. @param searchRecursively if true, all subdirectories will be recursed into to do
  5924. an exhaustive search
  5925. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5926. @returns the number of results that have been found
  5927. @see getNumberOfChildFiles, DirectoryIterator
  5928. */
  5929. int findChildFiles (OwnedArray<File>& results,
  5930. const int whatToLookFor,
  5931. const bool searchRecursively,
  5932. const String& wildCardPattern = JUCE_T("*")) const;
  5933. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5934. Assuming that this file is a directory, this method will search it
  5935. for either files or subdirectories whose names match a filename pattern,
  5936. and will return the number of matches found.
  5937. This isn't a recursive call, and will only search this directory, not
  5938. its children.
  5939. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5940. count files, directories, or both. If the ignoreHiddenFiles flag
  5941. is also added to this value, hidden files won't be counted
  5942. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5943. @returns the number of matches found
  5944. @see findChildFiles, DirectoryIterator
  5945. */
  5946. int getNumberOfChildFiles (const int whatToLookFor,
  5947. const String& wildCardPattern = JUCE_T("*")) const;
  5948. /** Returns true if this file is a directory that contains one or more subdirectories.
  5949. @see isDirectory, findChildFiles
  5950. */
  5951. bool containsSubDirectories() const;
  5952. /** Creates a stream to read from this file.
  5953. @returns a stream that will read from this file (initially positioned at the
  5954. start of the file), or 0 if the file can't be opened for some reason
  5955. @see createOutputStream, loadFileAsData
  5956. */
  5957. FileInputStream* createInputStream() const;
  5958. /** Creates a stream to write to this file.
  5959. If the file exists, the stream that is returned will be positioned ready for
  5960. writing at the end of the file, so you might want to use deleteFile() first
  5961. to write to an empty file.
  5962. @returns a stream that will write to this file (initially positioned at the
  5963. end of the file), or 0 if the file can't be opened for some reason
  5964. @see createInputStream, printf, appendData, appendText
  5965. */
  5966. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const;
  5967. /** Loads a file's contents into memory as a block of binary data.
  5968. Of course, trying to load a very large file into memory will blow up, so
  5969. it's better to check first.
  5970. @param result the data block to which the file's contents should be appended - note
  5971. that if the memory block might already contain some data, you
  5972. might want to clear it first
  5973. @returns true if the file could all be read into memory
  5974. */
  5975. bool loadFileAsData (MemoryBlock& result) const;
  5976. /** Reads a file into memory as a string.
  5977. Attempts to load the entire file as a zero-terminated string.
  5978. This makes use of InputStream::readEntireStreamAsString, which should
  5979. automatically cope with unicode/acsii file formats.
  5980. */
  5981. const String loadFileAsString() const;
  5982. /** Writes text to the end of the file.
  5983. This will try to do a printf to the file.
  5984. @returns false if it can't write to the file for some reason
  5985. */
  5986. bool printf (const tchar* format, ...) const;
  5987. /** Appends a block of binary data to the end of the file.
  5988. This will try to write the given buffer to the end of the file.
  5989. @returns false if it can't write to the file for some reason
  5990. */
  5991. bool appendData (const void* const dataToAppend,
  5992. const int numberOfBytes) const;
  5993. /** Replaces this file's contents with a given block of data.
  5994. This will delete the file and replace it with the given data.
  5995. A nice feature of this method is that it's safe - instead of deleting
  5996. the file first and then re-writing it, it creates a new temporary file,
  5997. writes the data to that, and then moves the new file to replace the existing
  5998. file. This means that if the power gets pulled out or something crashes,
  5999. you're a lot less likely to end up with an empty file..
  6000. Returns true if the operation succeeds, or false if it fails.
  6001. @see appendText
  6002. */
  6003. bool replaceWithData (const void* const dataToWrite,
  6004. const int numberOfBytes) const;
  6005. /** Appends a string to the end of the file.
  6006. This will try to append a text string to the file, as either 16-bit unicode
  6007. or 8-bit characters in the default system encoding.
  6008. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6009. the endianness of the file.
  6010. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6011. @see replaceWithText
  6012. */
  6013. bool appendText (const String& textToAppend,
  6014. const bool asUnicode = false,
  6015. const bool writeUnicodeHeaderBytes = false) const;
  6016. /** Replaces this file's contents with a given text string.
  6017. This will delete the file and replace it with the given text.
  6018. A nice feature of this method is that it's safe - instead of deleting
  6019. the file first and then re-writing it, it creates a new temporary file,
  6020. writes the text to that, and then moves the new file to replace the existing
  6021. file. This means that if the power gets pulled out or something crashes,
  6022. you're a lot less likely to end up with an empty file..
  6023. For an explanation of the parameters here, see the appendText() method.
  6024. Returns true if the operation succeeds, or false if it fails.
  6025. @see appendText
  6026. */
  6027. bool replaceWithText (const String& textToWrite,
  6028. const bool asUnicode = false,
  6029. const bool writeUnicodeHeaderBytes = false) const;
  6030. /** Creates a set of files to represent each file root.
  6031. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6032. to which ones are available. On the Mac/Linux, this will probably
  6033. just add a single entry for "/".
  6034. */
  6035. static void findFileSystemRoots (OwnedArray<File>& results);
  6036. /** Finds the name of the drive on which this file lives.
  6037. @returns the volume label of the drive, or an empty string if this isn't possible
  6038. */
  6039. const String getVolumeLabel() const;
  6040. /** Returns the serial number of the volume on which this file lives.
  6041. @returns the serial number, or zero if there's a problem doing this
  6042. */
  6043. int getVolumeSerialNumber() const;
  6044. /** Returns the number of bytes free on the drive that this file lives on.
  6045. @returns the number of bytes free, or 0 if there's a problem finding this out
  6046. @see getVolumeTotalSize
  6047. */
  6048. int64 getBytesFreeOnVolume() const;
  6049. /** Returns the total size of the drive that contains this file.
  6050. @returns the total number of bytes that the volume can hold
  6051. @see getBytesFreeOnVolume
  6052. */
  6053. int64 getVolumeTotalSize() const;
  6054. /** Returns true if this file is on a CD or DVD drive. */
  6055. bool isOnCDRomDrive() const;
  6056. /** Returns true if this file is on a hard disk.
  6057. This will fail if it's a network drive, but will still be true for
  6058. removable hard-disks.
  6059. */
  6060. bool isOnHardDisk() const;
  6061. /** Returns true if this file is on a removable disk drive.
  6062. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6063. */
  6064. bool isOnRemovableDrive() const;
  6065. /** Launches the file as a process.
  6066. - if the file is executable, this will run it.
  6067. - if it's a document of some kind, it will launch the document with its
  6068. default viewer application.
  6069. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6070. @see revealToUser
  6071. */
  6072. bool startAsProcess (const String& parameters = String::empty) const;
  6073. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6074. @see startAsProcess
  6075. */
  6076. void revealToUser() const;
  6077. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6078. */
  6079. enum SpecialLocationType
  6080. {
  6081. /** The user's home folder. This is the same as using File ("~"). */
  6082. userHomeDirectory,
  6083. /** The user's default documents folder. On Windows, this might be the user's
  6084. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6085. doesn't tend to have one of these, so it might just return their home folder.
  6086. */
  6087. userDocumentsDirectory,
  6088. /** The folder that contains the user's desktop objects. */
  6089. userDesktopDirectory,
  6090. /** The folder in which applications store their persistent user-specific settings.
  6091. On Windows, this might be "\Documents and Settings\username\Application Data".
  6092. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6093. always create your own sub-folder to put them in, to avoid making a mess.
  6094. */
  6095. userApplicationDataDirectory,
  6096. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6097. of the computer, rather than just the current user.
  6098. On the Mac it'll be "/Library", on Windows, it could be something like
  6099. "\Documents and Settings\All Users\Application Data".
  6100. Depending on the setup, this folder may be read-only.
  6101. */
  6102. commonApplicationDataDirectory,
  6103. /** The folder that should be used for temporary files.
  6104. Always delete them when you're finished, to keep the user's computer tidy!
  6105. */
  6106. tempDirectory,
  6107. /** Returns this application's executable file.
  6108. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6109. host app.
  6110. On the mac this will return the unix binary, not the package folder - see
  6111. currentApplicationFile for that.
  6112. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6113. file link, invokedExecutableFile will return the name of the link.
  6114. */
  6115. currentExecutableFile,
  6116. /** Returns this application's location.
  6117. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6118. host app.
  6119. On the mac this will return the package folder (if it's in one), not the unix binary
  6120. that's inside it - compare with currentExecutableFile.
  6121. */
  6122. currentApplicationFile,
  6123. /** Returns the file that was invoked to launch this executable.
  6124. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6125. will return the name of the link that was used, whereas currentExecutableFile will return
  6126. the actual location of the target executable.
  6127. */
  6128. invokedExecutableFile,
  6129. /** The directory in which applications normally get installed.
  6130. So on windows, this would be something like "c:\program files", on the
  6131. Mac "/Applications", or "/usr" on linux.
  6132. */
  6133. globalApplicationsDirectory,
  6134. /** The most likely place where a user might store their music files.
  6135. */
  6136. userMusicDirectory,
  6137. /** The most likely place where a user might store their movie files.
  6138. */
  6139. userMoviesDirectory,
  6140. };
  6141. /** Finds the location of a special type of file or directory, such as a home folder or
  6142. documents folder.
  6143. @see SpecialLocationType
  6144. */
  6145. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6146. /** Returns a temporary file in the system's temp directory.
  6147. This will try to return the name of a non-existent temp file.
  6148. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6149. */
  6150. static const File createTempFile (const String& fileNameEnding);
  6151. /** Returns the current working directory.
  6152. @see setAsCurrentWorkingDirectory
  6153. */
  6154. static const File getCurrentWorkingDirectory();
  6155. /** Sets the current working directory to be this file.
  6156. For this to work the file must point to a valid directory.
  6157. @returns true if the current directory has been changed.
  6158. @see getCurrentWorkingDirectory
  6159. */
  6160. bool setAsCurrentWorkingDirectory() const;
  6161. /** The system-specific file separator character.
  6162. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6163. */
  6164. static const tchar separator;
  6165. /** The system-specific file separator character, as a string.
  6166. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6167. */
  6168. static const tchar* separatorString;
  6169. /** Removes illegal characters from a filename.
  6170. This will return a copy of the given string after removing characters
  6171. that are not allowed in a legal filename, and possibly shortening the
  6172. string if it's too long.
  6173. Because this will remove slashes, don't use it on an absolute pathname.
  6174. @see createLegalPathName
  6175. */
  6176. static const String createLegalFileName (const String& fileNameToFix);
  6177. /** Removes illegal characters from a pathname.
  6178. Similar to createLegalFileName(), but this won't remove slashes, so can
  6179. be used on a complete pathname.
  6180. @see createLegalFileName
  6181. */
  6182. static const String createLegalPathName (const String& pathNameToFix);
  6183. /** Indicates whether filenames are case-sensitive on the current operating system.
  6184. */
  6185. static bool areFileNamesCaseSensitive();
  6186. /** Returns true if the string seems to be a fully-specified absolute path.
  6187. */
  6188. static bool isAbsolutePath (const String& path);
  6189. juce_UseDebuggingNewOperator
  6190. private:
  6191. String fullPath;
  6192. // internal way of contructing a file without checking the path
  6193. friend class DirectoryIterator;
  6194. File (const String&, int);
  6195. const String getPathUpToLastSlash() const;
  6196. };
  6197. #endif // __JUCE_FILE_JUCEHEADER__
  6198. /********* End of inlined file: juce_File.h *********/
  6199. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6200. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6201. will be the name of a pointer to each child element.
  6202. E.g. @code
  6203. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6204. forEachXmlChildElement (*myParentXml, child)
  6205. {
  6206. if (child->hasTagName (T("FOO")))
  6207. doSomethingWithXmlElement (child);
  6208. }
  6209. @endcode
  6210. @see forEachXmlChildElementWithTagName
  6211. */
  6212. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6213. \
  6214. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6215. childElementVariableName != 0; \
  6216. childElementVariableName = childElementVariableName->getNextElement())
  6217. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6218. which have a specified tag.
  6219. This does the same job as the forEachXmlChildElement macro, but only for those
  6220. elements that have a particular tag name.
  6221. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6222. will be the name of a pointer to each child element. The requiredTagName is the
  6223. tag name to match.
  6224. E.g. @code
  6225. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6226. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6227. {
  6228. // the child object is now guaranteed to be a <MYTAG> element..
  6229. doSomethingWithMYTAGElement (child);
  6230. }
  6231. @endcode
  6232. @see forEachXmlChildElement
  6233. */
  6234. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6235. \
  6236. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6237. childElementVariableName != 0; \
  6238. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6239. /** Used to build a tree of elements representing an XML document.
  6240. An XML document can be parsed into a tree of XmlElements, each of which
  6241. represents an XML tag structure, and which may itself contain other
  6242. nested elements.
  6243. An XmlElement can also be converted back into a text document, and has
  6244. lots of useful methods for manipulating its attributes and sub-elements,
  6245. so XmlElements can actually be used as a handy general-purpose data
  6246. structure.
  6247. Here's an example of parsing some elements: @code
  6248. // check we're looking at the right kind of document..
  6249. if (myElement->hasTagName (T("ANIMALS")))
  6250. {
  6251. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6252. forEachXmlChildElement (*myElement, e)
  6253. {
  6254. if (e->hasTagName (T("GIRAFFE")))
  6255. {
  6256. // found a giraffe, so use some of its attributes..
  6257. String giraffeName = e->getStringAttribute ("name");
  6258. int giraffeAge = e->getIntAttribute ("age");
  6259. bool isFriendly = e->getBoolAttribute ("friendly");
  6260. }
  6261. }
  6262. }
  6263. @endcode
  6264. And here's an example of how to create an XML document from scratch: @code
  6265. // create an outer node called "ANIMALS"
  6266. XmlElement animalsList ("ANIMALS");
  6267. for (int i = 0; i < numAnimals; ++i)
  6268. {
  6269. // create an inner element..
  6270. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6271. giraffe->setAttribute ("name", "nigel");
  6272. giraffe->setAttribute ("age", 10);
  6273. giraffe->setAttribute ("friendly", true);
  6274. // ..and add our new element to the parent node
  6275. animalsList.addChildElement (giraffe);
  6276. }
  6277. // now we can turn the whole thing into a text document..
  6278. String myXmlDoc = animalsList.createDocument (String::empty);
  6279. @endcode
  6280. @see XmlDocument
  6281. */
  6282. class JUCE_API XmlElement
  6283. {
  6284. public:
  6285. /** Creates an XmlElement with this tag name. */
  6286. XmlElement (const String& tagName) throw();
  6287. /** Creates a (deep) copy of another element. */
  6288. XmlElement (const XmlElement& other) throw();
  6289. /** Creates a (deep) copy of another element. */
  6290. const XmlElement& operator= (const XmlElement& other) throw();
  6291. /** Deleting an XmlElement will also delete all its child elements. */
  6292. ~XmlElement() throw();
  6293. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6294. The elements are only considered equivalent if they contain the same attiributes
  6295. with the same values, and have the same sub-nodes.
  6296. @param other the other element to compare to
  6297. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6298. same attributes in a different order will be
  6299. considered the same; if false, the attributes must
  6300. be in the same order as well
  6301. */
  6302. bool isEquivalentTo (const XmlElement* const other,
  6303. const bool ignoreOrderOfAttributes) const throw();
  6304. /** Returns an XML text document that represents this element.
  6305. The string returned can be parsed to recreate the same XmlElement that
  6306. was used to create it.
  6307. @param dtdToUse the DTD to add to the document
  6308. @param allOnOneLine if true, this means that the document will not contain any
  6309. linefeeds, so it'll be smaller but not very easy to read.
  6310. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6311. document
  6312. @param encodingType the character encoding format string to put into the xml
  6313. header
  6314. @param lineWrapLength the line length that will be used before items get placed on
  6315. a new line. This isn't an absolute maximum length, it just
  6316. determines how lists of attributes get broken up
  6317. @see writeToStream, writeToFile
  6318. */
  6319. const String createDocument (const String& dtdToUse,
  6320. const bool allOnOneLine = false,
  6321. const bool includeXmlHeader = true,
  6322. const tchar* const encodingType = JUCE_T("UTF-8"),
  6323. const int lineWrapLength = 60) const throw();
  6324. /** Writes the document to a stream as UTF-8.
  6325. @param output the stream to write to
  6326. @param dtdToUse the DTD to add to the document
  6327. @param allOnOneLine if true, this means that the document will not contain any
  6328. linefeeds, so it'll be smaller but not very easy to read.
  6329. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6330. document
  6331. @param encodingType the character encoding format string to put into the xml
  6332. header
  6333. @param lineWrapLength the line length that will be used before items get placed on
  6334. a new line. This isn't an absolute maximum length, it just
  6335. determines how lists of attributes get broken up
  6336. @see writeToFile, createDocument
  6337. */
  6338. void writeToStream (OutputStream& output,
  6339. const String& dtdToUse,
  6340. const bool allOnOneLine = false,
  6341. const bool includeXmlHeader = true,
  6342. const tchar* const encodingType = JUCE_T("UTF-8"),
  6343. const int lineWrapLength = 60) const throw();
  6344. /** Writes the element to a file as an XML document.
  6345. To improve safety in case something goes wrong while writing the file, this
  6346. will actually write the document to a new temporary file in the same
  6347. directory as the destination file, and if this succeeds, it will rename this
  6348. new file as the destination file (overwriting any existing file that was there).
  6349. @param destinationFile the file to write to. If this already exists, it will be
  6350. overwritten.
  6351. @param dtdToUse the DTD to add to the document
  6352. @param encodingType the character encoding format string to put into the xml
  6353. header
  6354. @param lineWrapLength the line length that will be used before items get placed on
  6355. a new line. This isn't an absolute maximum length, it just
  6356. determines how lists of attributes get broken up
  6357. @returns true if the file is written successfully; false if something goes wrong
  6358. in the process
  6359. @see createDocument
  6360. */
  6361. bool writeToFile (const File& destinationFile,
  6362. const String& dtdToUse,
  6363. const tchar* const encodingType = JUCE_T("UTF-8"),
  6364. const int lineWrapLength = 60) const throw();
  6365. /** Returns this element's tag type name.
  6366. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6367. "MOOSE".
  6368. @see hasTagName
  6369. */
  6370. inline const String& getTagName() const throw() { return tagName; }
  6371. /** Tests whether this element has a particular tag name.
  6372. @param possibleTagName the tag name you're comparing it with
  6373. @see getTagName
  6374. */
  6375. bool hasTagName (const tchar* const possibleTagName) const throw();
  6376. /** Returns the number of XML attributes this element contains.
  6377. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6378. return 2.
  6379. */
  6380. int getNumAttributes() const throw();
  6381. /** Returns the name of one of the elements attributes.
  6382. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6383. getAttributeName(1) would return "antlers".
  6384. @see getAttributeValue, getStringAttribute
  6385. */
  6386. const String& getAttributeName (const int attributeIndex) const throw();
  6387. /** Returns the value of one of the elements attributes.
  6388. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6389. getAttributeName(1) would return "2".
  6390. @see getAttributeName, getStringAttribute
  6391. */
  6392. const String& getAttributeValue (const int attributeIndex) const throw();
  6393. // Attribute-handling methods..
  6394. /** Checks whether the element contains an attribute with a certain name. */
  6395. bool hasAttribute (const tchar* const attributeName) const throw();
  6396. /** Returns the value of a named attribute.
  6397. @param attributeName the name of the attribute to look up
  6398. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6399. with this name
  6400. */
  6401. const String getStringAttribute (const tchar* const attributeName,
  6402. const tchar* const defaultReturnValue = 0) const throw();
  6403. /** Compares the value of a named attribute with a value passed-in.
  6404. @param attributeName the name of the attribute to look up
  6405. @param stringToCompareAgainst the value to compare it with
  6406. @param ignoreCase whether the comparison should be case-insensitive
  6407. @returns true if the value of the attribute is the same as the string passed-in;
  6408. false if it's different (or if no such attribute exists)
  6409. */
  6410. bool compareAttribute (const tchar* const attributeName,
  6411. const tchar* const stringToCompareAgainst,
  6412. const bool ignoreCase = false) const throw();
  6413. /** Returns the value of a named attribute as an integer.
  6414. This will try to find the attribute and convert it to an integer (using
  6415. the String::getIntValue() method).
  6416. @param attributeName the name of the attribute to look up
  6417. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6418. with this name
  6419. @see setAttribute (const tchar* const, int)
  6420. */
  6421. int getIntAttribute (const tchar* const attributeName,
  6422. const int defaultReturnValue = 0) const throw();
  6423. /** Returns the value of a named attribute as floating-point.
  6424. This will try to find the attribute and convert it to an integer (using
  6425. the String::getDoubleValue() method).
  6426. @param attributeName the name of the attribute to look up
  6427. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6428. with this name
  6429. @see setAttribute (const tchar* const, double)
  6430. */
  6431. double getDoubleAttribute (const tchar* const attributeName,
  6432. const double defaultReturnValue = 0.0) const throw();
  6433. /** Returns the value of a named attribute as a boolean.
  6434. This will try to find the attribute and interpret it as a boolean. To do this,
  6435. it'll return true if the value is "1", "true", "y", etc, or false for other
  6436. values.
  6437. @param attributeName the name of the attribute to look up
  6438. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6439. with this name
  6440. */
  6441. bool getBoolAttribute (const tchar* const attributeName,
  6442. const bool defaultReturnValue = false) const throw();
  6443. /** Adds a named attribute to the element.
  6444. If the element already contains an attribute with this name, it's value will
  6445. be updated to the new value. If there's no such attribute yet, a new one will
  6446. be added.
  6447. Note that there are other setAttribute() methods that take integers,
  6448. doubles, etc. to make it easy to store numbers.
  6449. @param attributeName the name of the attribute to set
  6450. @param newValue the value to set it to
  6451. @see removeAttribute
  6452. */
  6453. void setAttribute (const tchar* const attributeName,
  6454. const String& newValue) throw();
  6455. /** Adds a named attribute to the element.
  6456. If the element already contains an attribute with this name, it's value will
  6457. be updated to the new value. If there's no such attribute yet, a new one will
  6458. be added.
  6459. Note that there are other setAttribute() methods that take integers,
  6460. doubles, etc. to make it easy to store numbers.
  6461. @param attributeName the name of the attribute to set
  6462. @param newValue the value to set it to
  6463. */
  6464. void setAttribute (const tchar* const attributeName,
  6465. const tchar* const newValue) throw();
  6466. /** Adds a named attribute to the element, setting it to an integer value.
  6467. If the element already contains an attribute with this name, it's value will
  6468. be updated to the new value. If there's no such attribute yet, a new one will
  6469. be added.
  6470. Note that there are other setAttribute() methods that take integers,
  6471. doubles, etc. to make it easy to store numbers.
  6472. @param attributeName the name of the attribute to set
  6473. @param newValue the value to set it to
  6474. */
  6475. void setAttribute (const tchar* const attributeName,
  6476. const int newValue) throw();
  6477. /** Adds a named attribute to the element, setting it to a floating-point value.
  6478. If the element already contains an attribute with this name, it's value will
  6479. be updated to the new value. If there's no such attribute yet, a new one will
  6480. be added.
  6481. Note that there are other setAttribute() methods that take integers,
  6482. doubles, etc. to make it easy to store numbers.
  6483. @param attributeName the name of the attribute to set
  6484. @param newValue the value to set it to
  6485. */
  6486. void setAttribute (const tchar* const attributeName,
  6487. const double newValue) throw();
  6488. /** Removes a named attribute from the element.
  6489. @param attributeName the name of the attribute to remove
  6490. @see removeAllAttributes
  6491. */
  6492. void removeAttribute (const tchar* const attributeName) throw();
  6493. /** Removes all attributes from this element.
  6494. */
  6495. void removeAllAttributes() throw();
  6496. // Child element methods..
  6497. /** Returns the first of this element's sub-elements.
  6498. see getNextElement() for an example of how to iterate the sub-elements.
  6499. @see forEachXmlChildElement
  6500. */
  6501. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6502. /** Returns the next of this element's siblings.
  6503. This can be used for iterating an element's sub-elements, e.g.
  6504. @code
  6505. XmlElement* child = myXmlDocument->getFirstChildElement();
  6506. while (child != 0)
  6507. {
  6508. ...do stuff with this child..
  6509. child = child->getNextElement();
  6510. }
  6511. @endcode
  6512. Note that when iterating the child elements, some of them might be
  6513. text elements as well as XML tags - use isTextElement() to work this
  6514. out.
  6515. Also, it's much easier and neater to use this method indirectly via the
  6516. forEachXmlChildElement macro.
  6517. @returns the sibling element that follows this one, or zero if this is the last
  6518. element in its parent
  6519. @see getNextElement, isTextElement, forEachXmlChildElement
  6520. */
  6521. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6522. /** Returns the next of this element's siblings which has the specified tag
  6523. name.
  6524. This is like getNextElement(), but will scan through the list until it
  6525. finds an element with the given tag name.
  6526. @see getNextElement, forEachXmlChildElementWithTagName
  6527. */
  6528. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6529. /** Returns the number of sub-elements in this element.
  6530. @see getChildElement
  6531. */
  6532. int getNumChildElements() const throw();
  6533. /** Returns the sub-element at a certain index.
  6534. It's not very efficient to iterate the sub-elements by index - see
  6535. getNextElement() for an example of how best to iterate.
  6536. @returns the n'th child of this element, or 0 if the index is out-of-range
  6537. @see getNextElement, isTextElement, getChildByName
  6538. */
  6539. XmlElement* getChildElement (const int index) const throw();
  6540. /** Returns the first sub-element with a given tag-name.
  6541. @param tagNameToLookFor the tag name of the element you want to find
  6542. @returns the first element with this tag name, or 0 if none is found
  6543. @see getNextElement, isTextElement, getChildElement
  6544. */
  6545. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6546. /** Appends an element to this element's list of children.
  6547. Child elements are deleted automatically when their parent is deleted, so
  6548. make sure the object that you pass in will not be deleted by anything else,
  6549. and make sure it's not already the child of another element.
  6550. @see getFirstChildElement, getNextElement, getNumChildElements,
  6551. getChildElement, removeChildElement
  6552. */
  6553. void addChildElement (XmlElement* const newChildElement) throw();
  6554. /** Inserts an element into this element's list of children.
  6555. Child elements are deleted automatically when their parent is deleted, so
  6556. make sure the object that you pass in will not be deleted by anything else,
  6557. and make sure it's not already the child of another element.
  6558. @param newChildNode the element to add
  6559. @param indexToInsertAt the index at which to insert the new element - if this is
  6560. below zero, it will be added to the end of the list
  6561. @see addChildElement, insertChildElement
  6562. */
  6563. void insertChildElement (XmlElement* const newChildNode,
  6564. int indexToInsertAt) throw();
  6565. /** Replaces one of this element's children with another node.
  6566. If the current element passed-in isn't actually a child of this element,
  6567. this will return false and the new one won't be added. Otherwise, the
  6568. existing element will be deleted, replaced with the new one, and it
  6569. will return true.
  6570. */
  6571. bool replaceChildElement (XmlElement* const currentChildElement,
  6572. XmlElement* const newChildNode) throw();
  6573. /** Removes a child element.
  6574. @param childToRemove the child to look for and remove
  6575. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6576. just remove it
  6577. */
  6578. void removeChildElement (XmlElement* const childToRemove,
  6579. const bool shouldDeleteTheChild) throw();
  6580. /** Deletes all the child elements in the element.
  6581. @see removeChildElement, deleteAllChildElementsWithTagName
  6582. */
  6583. void deleteAllChildElements() throw();
  6584. /** Deletes all the child elements with a given tag name.
  6585. @see removeChildElement
  6586. */
  6587. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6588. /** Returns true if the given element is a child of this one. */
  6589. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6590. /** Recursively searches all sub-elements to find one that contains the specified
  6591. child element.
  6592. */
  6593. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6594. /** Sorts the child elements using a comparator.
  6595. This will use a comparator object to sort the elements into order. The object
  6596. passed must have a method of the form:
  6597. @code
  6598. int compareElements (const XmlElement* first, const XmlElement* second);
  6599. @endcode
  6600. ..and this method must return:
  6601. - a value of < 0 if the first comes before the second
  6602. - a value of 0 if the two objects are equivalent
  6603. - a value of > 0 if the second comes before the first
  6604. To improve performance, the compareElements() method can be declared as static or const.
  6605. @param comparator the comparator to use for comparing elements.
  6606. @param retainOrderOfEquivalentItems if this is true, then items
  6607. which the comparator says are equivalent will be
  6608. kept in the order in which they currently appear
  6609. in the array. This is slower to perform, but may
  6610. be important in some cases. If it's false, a faster
  6611. algorithm is used, but equivalent elements may be
  6612. rearranged.
  6613. */
  6614. template <class ElementComparator>
  6615. void sortChildElements (ElementComparator& comparator,
  6616. const bool retainOrderOfEquivalentItems = false) throw()
  6617. {
  6618. const int num = getNumChildElements();
  6619. if (num > 1)
  6620. {
  6621. HeapBlock <XmlElement*> elems (num);
  6622. getChildElementsAsArray (elems);
  6623. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  6624. reorderChildElements (elems, num);
  6625. }
  6626. }
  6627. /** Returns true if this element is a section of text.
  6628. Elements can either be an XML tag element or a secton of text, so this
  6629. is used to find out what kind of element this one is.
  6630. @see getAllText, addTextElement, deleteAllTextElements
  6631. */
  6632. bool isTextElement() const throw();
  6633. /** Returns the text for a text element.
  6634. Note that if you have an element like this:
  6635. @code<xyz>hello</xyz>@endcode
  6636. then calling getText on the "xyz" element won't return "hello", because that is
  6637. actually stored in a special text sub-element inside the xyz element. To get the
  6638. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6639. use getAllSubText() to do this automatically.
  6640. @see isTextElement, getAllSubText, getChildElementAllSubText
  6641. */
  6642. const String getText() const throw();
  6643. /** Sets the text in a text element.
  6644. Note that this is only a valid call if this element is a text element. If it's
  6645. not, then no action will be performed.
  6646. */
  6647. void setText (const String& newText) throw();
  6648. /** Returns all the text from this element's child nodes.
  6649. This iterates all the child elements and when it finds text elements,
  6650. it concatenates their text into a big string which it returns.
  6651. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6652. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6653. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6654. */
  6655. const String getAllSubText() const throw();
  6656. /** Returns all the sub-text of a named child element.
  6657. If there is a child element with the given tag name, this will return
  6658. all of its sub-text (by calling getAllSubText() on it). If there is
  6659. no such child element, this will return the default string passed-in.
  6660. @see getAllSubText
  6661. */
  6662. const String getChildElementAllSubText (const tchar* const childTagName,
  6663. const String& defaultReturnValue) const throw();
  6664. /** Appends a section of text to this element.
  6665. @see isTextElement, getText, getAllSubText
  6666. */
  6667. void addTextElement (const String& text) throw();
  6668. /** Removes all the text elements from this element.
  6669. @see isTextElement, getText, getAllSubText, addTextElement
  6670. */
  6671. void deleteAllTextElements() throw();
  6672. /** Creates a text element that can be added to a parent element.
  6673. */
  6674. static XmlElement* createTextElement (const String& text) throw();
  6675. juce_UseDebuggingNewOperator
  6676. private:
  6677. friend class XmlDocument;
  6678. String tagName;
  6679. XmlElement* firstChildElement;
  6680. XmlElement* nextElement;
  6681. struct XmlAttributeNode
  6682. {
  6683. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6684. XmlAttributeNode (const String& name, const String& value) throw();
  6685. String name, value;
  6686. XmlAttributeNode* next;
  6687. private:
  6688. const XmlAttributeNode& operator= (const XmlAttributeNode&);
  6689. };
  6690. XmlAttributeNode* attributes;
  6691. XmlElement (int) throw(); // for internal use
  6692. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6693. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6694. void writeElementAsText (OutputStream& out,
  6695. const int indentationLevel,
  6696. const int lineWrapLength) const throw();
  6697. void getChildElementsAsArray (XmlElement**) const throw();
  6698. void reorderChildElements (XmlElement** const, const int) throw();
  6699. };
  6700. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6701. /********* End of inlined file: juce_XmlElement.h *********/
  6702. /**
  6703. A set of named property values, which can be strings, integers, floating point, etc.
  6704. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6705. to load and save types other than strings.
  6706. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6707. messages and saves/loads the list from a file.
  6708. */
  6709. class JUCE_API PropertySet
  6710. {
  6711. public:
  6712. /** Creates an empty PropertySet.
  6713. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6714. case-insensitive way
  6715. */
  6716. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6717. /** Creates a copy of another PropertySet.
  6718. */
  6719. PropertySet (const PropertySet& other) throw();
  6720. /** Copies another PropertySet over this one.
  6721. */
  6722. const PropertySet& operator= (const PropertySet& other) throw();
  6723. /** Destructor. */
  6724. virtual ~PropertySet();
  6725. /** Returns one of the properties as a string.
  6726. If the value isn't found in this set, then this will look for it in a fallback
  6727. property set (if you've specified one with the setFallbackPropertySet() method),
  6728. and if it can't find one there, it'll return the default value passed-in.
  6729. @param keyName the name of the property to retrieve
  6730. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6731. */
  6732. const String getValue (const String& keyName,
  6733. const String& defaultReturnValue = String::empty) const throw();
  6734. /** Returns one of the properties as an integer.
  6735. If the value isn't found in this set, then this will look for it in a fallback
  6736. property set (if you've specified one with the setFallbackPropertySet() method),
  6737. and if it can't find one there, it'll return the default value passed-in.
  6738. @param keyName the name of the property to retrieve
  6739. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6740. */
  6741. int getIntValue (const String& keyName,
  6742. const int defaultReturnValue = 0) const throw();
  6743. /** Returns one of the properties as an double.
  6744. If the value isn't found in this set, then this will look for it in a fallback
  6745. property set (if you've specified one with the setFallbackPropertySet() method),
  6746. and if it can't find one there, it'll return the default value passed-in.
  6747. @param keyName the name of the property to retrieve
  6748. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6749. */
  6750. double getDoubleValue (const String& keyName,
  6751. const double defaultReturnValue = 0.0) const throw();
  6752. /** Returns one of the properties as an boolean.
  6753. The result will be true if the string found for this key name can be parsed as a non-zero
  6754. integer.
  6755. If the value isn't found in this set, then this will look for it in a fallback
  6756. property set (if you've specified one with the setFallbackPropertySet() method),
  6757. and if it can't find one there, it'll return the default value passed-in.
  6758. @param keyName the name of the property to retrieve
  6759. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6760. */
  6761. bool getBoolValue (const String& keyName,
  6762. const bool defaultReturnValue = false) const throw();
  6763. /** Returns one of the properties as an XML element.
  6764. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  6765. key isn't found, or if the entry contains an string that isn't valid XML.
  6766. If the value isn't found in this set, then this will look for it in a fallback
  6767. property set (if you've specified one with the setFallbackPropertySet() method),
  6768. and if it can't find one there, it'll return the default value passed-in.
  6769. @param keyName the name of the property to retrieve
  6770. */
  6771. XmlElement* getXmlValue (const String& keyName) const;
  6772. /** Sets a named property as a string.
  6773. @param keyName the name of the property to set. (This mustn't be an empty string)
  6774. @param value the new value to set it to
  6775. */
  6776. void setValue (const String& keyName, const String& value) throw();
  6777. /** Sets a named property as a string.
  6778. @param keyName the name of the property to set. (This mustn't be an empty string)
  6779. @param value the new value to set it to
  6780. */
  6781. void setValue (const String& keyName, const tchar* const value) throw();
  6782. /** Sets a named property to an integer.
  6783. @param keyName the name of the property to set. (This mustn't be an empty string)
  6784. @param value the new value to set it to
  6785. */
  6786. void setValue (const String& keyName, const int value) throw();
  6787. /** Sets a named property to a double.
  6788. @param keyName the name of the property to set. (This mustn't be an empty string)
  6789. @param value the new value to set it to
  6790. */
  6791. void setValue (const String& keyName, const double value) throw();
  6792. /** Sets a named property to a boolean.
  6793. @param keyName the name of the property to set. (This mustn't be an empty string)
  6794. @param value the new value to set it to
  6795. */
  6796. void setValue (const String& keyName, const bool value) throw();
  6797. /** Sets a named property to an XML element.
  6798. @param keyName the name of the property to set. (This mustn't be an empty string)
  6799. @param xml the new element to set it to. If this is zero, the value will be set to
  6800. an empty string
  6801. @see getXmlValue
  6802. */
  6803. void setValue (const String& keyName, const XmlElement* const xml);
  6804. /** Deletes a property.
  6805. @param keyName the name of the property to delete. (This mustn't be an empty string)
  6806. */
  6807. void removeValue (const String& keyName) throw();
  6808. /** Returns true if the properies include the given key. */
  6809. bool containsKey (const String& keyName) const throw();
  6810. /** Removes all values. */
  6811. void clear();
  6812. /** Returns the keys/value pair array containing all the properties. */
  6813. StringPairArray& getAllProperties() throw() { return properties; }
  6814. /** Returns the lock used when reading or writing to this set */
  6815. const CriticalSection& getLock() const throw() { return lock; }
  6816. /** Returns an XML element which encapsulates all the items in this property set.
  6817. The string parameter is the tag name that should be used for the node.
  6818. @see restoreFromXml
  6819. */
  6820. XmlElement* createXml (const String& nodeName) const throw();
  6821. /** Reloads a set of properties that were previously stored as XML.
  6822. The node passed in must have been created by the createXml() method.
  6823. @see createXml
  6824. */
  6825. void restoreFromXml (const XmlElement& xml) throw();
  6826. /** Sets up a second PopertySet that will be used to look up any values that aren't
  6827. set in this one.
  6828. If you set this up to be a pointer to a second property set, then whenever one
  6829. of the getValue() methods fails to find an entry in this set, it will look up that
  6830. value in the fallback set, and if it finds it, it will return that.
  6831. Make sure that you don't delete the fallback set while it's still being used by
  6832. another set! To remove the fallback set, just call this method with a null pointer.
  6833. @see getFallbackPropertySet
  6834. */
  6835. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  6836. /** Returns the fallback property set.
  6837. @see setFallbackPropertySet
  6838. */
  6839. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  6840. juce_UseDebuggingNewOperator
  6841. protected:
  6842. /** Subclasses can override this to be told when one of the properies has been changed.
  6843. */
  6844. virtual void propertyChanged();
  6845. private:
  6846. StringPairArray properties;
  6847. PropertySet* fallbackProperties;
  6848. CriticalSection lock;
  6849. bool ignoreCaseOfKeys;
  6850. };
  6851. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  6852. /********* End of inlined file: juce_PropertySet.h *********/
  6853. #endif
  6854. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6855. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  6856. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6857. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6858. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  6859. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6860. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6861. /********* Start of inlined file: juce_Atomic.h *********/
  6862. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  6863. #define __JUCE_ATOMIC_JUCEHEADER__
  6864. /** Contains static functions for thread-safe atomic operations.
  6865. */
  6866. class JUCE_API Atomic
  6867. {
  6868. public:
  6869. /** Increments an integer in a thread-safe way. */
  6870. static void increment (int& variable);
  6871. /** Increments an integer in a thread-safe way and returns its new value. */
  6872. static int incrementAndReturn (int& variable);
  6873. /** Decrements an integer in a thread-safe way. */
  6874. static void decrement (int& variable);
  6875. /** Decrements an integer in a thread-safe way and returns its new value. */
  6876. static int decrementAndReturn (int& variable);
  6877. };
  6878. #if (JUCE_MAC || JUCE_IPHONE) // Mac and iPhone...
  6879. #include <libkern/OSAtomic.h>
  6880. inline void Atomic::increment (int& variable) { OSAtomicIncrement32 ((int32_t*) &variable); }
  6881. inline int Atomic::incrementAndReturn (int& variable) { return OSAtomicIncrement32 ((int32_t*) &variable); }
  6882. inline void Atomic::decrement (int& variable) { OSAtomicDecrement32 ((int32_t*) &variable); }
  6883. inline int Atomic::decrementAndReturn (int& variable) { return OSAtomicDecrement32 ((int32_t*) &variable); }
  6884. #elif JUCE_GCC
  6885. #if JUCE_USE_GCC_ATOMIC_INTRINSICS // Linux with intrinsics...
  6886. inline void Atomic::increment (int& variable) { __sync_add_and_fetch (&variable, 1); }
  6887. inline int Atomic::incrementAndReturn (int& variable) { return __sync_add_and_fetch (&variable, 1); }
  6888. inline void Atomic::decrement (int& variable) { __sync_add_and_fetch (&variable, -1); }
  6889. inline int Atomic::decrementAndReturn (int& variable) { return __sync_add_and_fetch (&variable, -1); }
  6890. #else // Linux without intrinsics...
  6891. inline void Atomic::increment (int& variable)
  6892. {
  6893. __asm__ __volatile__ (
  6894. #if JUCE_64BIT
  6895. "lock incl (%%rax)"
  6896. :
  6897. : "a" (&variable)
  6898. : "cc", "memory");
  6899. #else
  6900. "lock incl %0"
  6901. : "=m" (variable)
  6902. : "m" (variable));
  6903. #endif
  6904. }
  6905. inline int Atomic::incrementAndReturn (int& variable)
  6906. {
  6907. int result;
  6908. __asm__ __volatile__ (
  6909. #if JUCE_64BIT
  6910. "lock xaddl %%ebx, (%%rax) \n\
  6911. incl %%ebx"
  6912. : "=b" (result)
  6913. : "a" (&variable), "b" (1)
  6914. : "cc", "memory");
  6915. #else
  6916. "lock xaddl %%eax, (%%ecx) \n\
  6917. incl %%eax"
  6918. : "=a" (result)
  6919. : "c" (&variable), "a" (1)
  6920. : "memory");
  6921. #endif
  6922. return result;
  6923. }
  6924. inline void Atomic::decrement (int& variable)
  6925. {
  6926. __asm__ __volatile__ (
  6927. #if JUCE_64BIT
  6928. "lock decl (%%rax)"
  6929. :
  6930. : "a" (&variable)
  6931. : "cc", "memory");
  6932. #else
  6933. "lock decl %0"
  6934. : "=m" (variable)
  6935. : "m" (variable));
  6936. #endif
  6937. }
  6938. inline int Atomic::decrementAndReturn (int& variable)
  6939. {
  6940. int result;
  6941. __asm__ __volatile__ (
  6942. #if JUCE_64BIT
  6943. "lock xaddl %%ebx, (%%rax) \n\
  6944. decl %%ebx"
  6945. : "=b" (result)
  6946. : "a" (&variable), "b" (-1)
  6947. : "cc", "memory");
  6948. #else
  6949. "lock xaddl %%eax, (%%ecx) \n\
  6950. decl %%eax"
  6951. : "=a" (result)
  6952. : "c" (&variable), "a" (-1)
  6953. : "memory");
  6954. #endif
  6955. return result;
  6956. }
  6957. #endif
  6958. #elif JUCE_USE_INTRINSICS // Windows with intrinsics...
  6959. #pragma intrinsic (_InterlockedIncrement)
  6960. #pragma intrinsic (_InterlockedDecrement)
  6961. inline void Atomic::increment (int& variable) { _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable)); }
  6962. inline int Atomic::incrementAndReturn (int& variable) { return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable)); }
  6963. inline void Atomic::decrement (int& variable) { _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable)); }
  6964. inline int Atomic::decrementAndReturn (int& variable) { return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable)); }
  6965. #else // Windows without intrinsics...
  6966. inline void Atomic::increment (int& variable)
  6967. {
  6968. __asm {
  6969. mov ecx, dword ptr [variable]
  6970. lock inc dword ptr [ecx]
  6971. }
  6972. }
  6973. inline int Atomic::incrementAndReturn (int& variable)
  6974. {
  6975. int result;
  6976. __asm {
  6977. mov ecx, dword ptr [variable]
  6978. mov eax, 1
  6979. lock xadd dword ptr [ecx], eax
  6980. inc eax
  6981. mov result, eax
  6982. }
  6983. return result;
  6984. }
  6985. inline void Atomic::decrement (int& variable)
  6986. {
  6987. __asm {
  6988. mov ecx, dword ptr [variable]
  6989. lock dec dword ptr [ecx]
  6990. }
  6991. }
  6992. inline int Atomic::decrementAndReturn (int& variable)
  6993. {
  6994. int result;
  6995. __asm {
  6996. mov ecx, dword ptr [variable]
  6997. mov eax, -1
  6998. lock xadd dword ptr [ecx], eax
  6999. dec eax
  7000. mov result, eax
  7001. }
  7002. return result;
  7003. }
  7004. #endif
  7005. #endif // __JUCE_ATOMIC_JUCEHEADER__
  7006. /********* End of inlined file: juce_Atomic.h *********/
  7007. /**
  7008. Adds reference-counting to an object.
  7009. To add reference-counting to a class, derive it from this class, and
  7010. use the ReferenceCountedObjectPtr class to point to it.
  7011. e.g. @code
  7012. class MyClass : public ReferenceCountedObject
  7013. {
  7014. void foo();
  7015. // This is a neat way of declaring a typedef for a pointer class,
  7016. // rather than typing out the full templated name each time..
  7017. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7018. };
  7019. MyClass::Ptr p = new MyClass();
  7020. MyClass::Ptr p2 = p;
  7021. p = 0;
  7022. p2->foo();
  7023. @endcode
  7024. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7025. careful not to delete the object manually.
  7026. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7027. */
  7028. class JUCE_API ReferenceCountedObject
  7029. {
  7030. public:
  7031. /** Increments the object's reference count.
  7032. This is done automatically by the smart pointer, but is public just
  7033. in case it's needed for nefarious purposes.
  7034. */
  7035. inline void incReferenceCount() throw()
  7036. {
  7037. Atomic::increment (refCounts);
  7038. jassert (refCounts > 0);
  7039. }
  7040. /** Decreases the object's reference count.
  7041. If the count gets to zero, the object will be deleted.
  7042. */
  7043. inline void decReferenceCount() throw()
  7044. {
  7045. jassert (refCounts > 0);
  7046. if (Atomic::decrementAndReturn (refCounts) == 0)
  7047. delete this;
  7048. }
  7049. /** Returns the object's current reference count. */
  7050. inline int getReferenceCount() const throw()
  7051. {
  7052. return refCounts;
  7053. }
  7054. protected:
  7055. /** Creates the reference-counted object (with an initial ref count of zero). */
  7056. ReferenceCountedObject()
  7057. : refCounts (0)
  7058. {
  7059. }
  7060. /** Destructor. */
  7061. virtual ~ReferenceCountedObject()
  7062. {
  7063. // it's dangerous to delete an object that's still referenced by something else!
  7064. jassert (refCounts == 0);
  7065. }
  7066. private:
  7067. int refCounts;
  7068. };
  7069. /**
  7070. Used to point to an object of type ReferenceCountedObject.
  7071. It's wise to use a typedef instead of typing out the templated name
  7072. each time - e.g.
  7073. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7074. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7075. */
  7076. template <class ReferenceCountedObjectClass>
  7077. class ReferenceCountedObjectPtr
  7078. {
  7079. public:
  7080. /** Creates a pointer to a null object. */
  7081. inline ReferenceCountedObjectPtr() throw()
  7082. : referencedObject (0)
  7083. {
  7084. }
  7085. /** Creates a pointer to an object.
  7086. This will increment the object's reference-count if it is non-null.
  7087. */
  7088. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7089. : referencedObject (refCountedObject)
  7090. {
  7091. if (refCountedObject != 0)
  7092. refCountedObject->incReferenceCount();
  7093. }
  7094. /** Copies another pointer.
  7095. This will increment the object's reference-count (if it is non-null).
  7096. */
  7097. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7098. : referencedObject (other.referencedObject)
  7099. {
  7100. if (referencedObject != 0)
  7101. referencedObject->incReferenceCount();
  7102. }
  7103. /** Changes this pointer to point at a different object.
  7104. The reference count of the old object is decremented, and it might be
  7105. deleted if it hits zero. The new object's count is incremented.
  7106. */
  7107. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7108. {
  7109. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7110. if (newObject != referencedObject)
  7111. {
  7112. if (newObject != 0)
  7113. newObject->incReferenceCount();
  7114. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7115. referencedObject = newObject;
  7116. if (oldObject != 0)
  7117. oldObject->decReferenceCount();
  7118. }
  7119. return *this;
  7120. }
  7121. /** Changes this pointer to point at a different object.
  7122. The reference count of the old object is decremented, and it might be
  7123. deleted if it hits zero. The new object's count is incremented.
  7124. */
  7125. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7126. {
  7127. if (referencedObject != newObject)
  7128. {
  7129. if (newObject != 0)
  7130. newObject->incReferenceCount();
  7131. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7132. referencedObject = newObject;
  7133. if (oldObject != 0)
  7134. oldObject->decReferenceCount();
  7135. }
  7136. return *this;
  7137. }
  7138. /** Destructor.
  7139. This will decrement the object's reference-count, and may delete it if it
  7140. gets to zero.
  7141. */
  7142. inline ~ReferenceCountedObjectPtr()
  7143. {
  7144. if (referencedObject != 0)
  7145. referencedObject->decReferenceCount();
  7146. }
  7147. /** Returns the object that this pointer references.
  7148. The pointer returned may be zero, of course.
  7149. */
  7150. inline operator ReferenceCountedObjectClass*() const throw()
  7151. {
  7152. return referencedObject;
  7153. }
  7154. /** Returns true if this pointer refers to the given object. */
  7155. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7156. {
  7157. return referencedObject == object;
  7158. }
  7159. /** Returns true if this pointer doesn't refer to the given object. */
  7160. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7161. {
  7162. return referencedObject != object;
  7163. }
  7164. // the -> operator is called on the referenced object
  7165. inline ReferenceCountedObjectClass* operator->() const throw()
  7166. {
  7167. return referencedObject;
  7168. }
  7169. private:
  7170. ReferenceCountedObjectClass* referencedObject;
  7171. };
  7172. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7173. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7174. /**
  7175. Holds a list of objects derived from ReferenceCountedObject.
  7176. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7177. and takes care of incrementing and decrementing their ref counts when they
  7178. are added and removed from the array.
  7179. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7180. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7181. @see Array, OwnedArray, StringArray
  7182. */
  7183. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7184. class ReferenceCountedArray
  7185. {
  7186. public:
  7187. /** Creates an empty array.
  7188. @param granularity this is the size of increment by which the internal storage
  7189. used by the array will grow. Only change it from the default if you know the
  7190. array is going to be very big and needs to be able to grow efficiently.
  7191. @see ReferenceCountedObject, Array, OwnedArray
  7192. */
  7193. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7194. : data (granularity),
  7195. numUsed (0)
  7196. {
  7197. }
  7198. /** Creates a copy of another array */
  7199. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7200. : data (other.data.granularity)
  7201. {
  7202. other.lockArray();
  7203. numUsed = other.numUsed;
  7204. data.setAllocatedSize (numUsed);
  7205. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7206. for (int i = numUsed; --i >= 0;)
  7207. if (data.elements[i] != 0)
  7208. data.elements[i]->incReferenceCount();
  7209. other.unlockArray();
  7210. }
  7211. /** Copies another array into this one.
  7212. Any existing objects in this array will first be released.
  7213. */
  7214. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7215. {
  7216. if (this != &other)
  7217. {
  7218. other.lockArray();
  7219. lock.enter();
  7220. clear();
  7221. data.granularity = other.granularity;
  7222. data.ensureAllocatedSize (other.numUsed);
  7223. numUsed = other.numUsed;
  7224. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7225. minimiseStorageOverheads();
  7226. for (int i = numUsed; --i >= 0;)
  7227. if (data.elements[i] != 0)
  7228. data.elements[i]->incReferenceCount();
  7229. lock.exit();
  7230. other.unlockArray();
  7231. }
  7232. return *this;
  7233. }
  7234. /** Destructor.
  7235. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7236. */
  7237. ~ReferenceCountedArray()
  7238. {
  7239. clear();
  7240. }
  7241. /** Removes all objects from the array.
  7242. Any objects in the array that are not referenced from elsewhere will be deleted.
  7243. */
  7244. void clear()
  7245. {
  7246. lock.enter();
  7247. while (numUsed > 0)
  7248. if (data.elements [--numUsed] != 0)
  7249. data.elements [numUsed]->decReferenceCount();
  7250. jassert (numUsed == 0);
  7251. data.setAllocatedSize (0);
  7252. lock.exit();
  7253. }
  7254. /** Returns the current number of objects in the array. */
  7255. inline int size() const throw()
  7256. {
  7257. return numUsed;
  7258. }
  7259. /** Returns a pointer to the object at this index in the array.
  7260. If the index is out-of-range, this will return a null pointer, (and
  7261. it could be null anyway, because it's ok for the array to hold null
  7262. pointers as well as objects).
  7263. @see getUnchecked
  7264. */
  7265. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7266. {
  7267. lock.enter();
  7268. const ReferenceCountedObjectPtr<ObjectClass> result ((((unsigned int) index) < (unsigned int) numUsed)
  7269. ? data.elements [index]
  7270. : (ObjectClass*) 0);
  7271. lock.exit();
  7272. return result;
  7273. }
  7274. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7275. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7276. it can be used when you're sure the index if always going to be legal.
  7277. */
  7278. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7279. {
  7280. lock.enter();
  7281. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7282. const ReferenceCountedObjectPtr<ObjectClass> result (data.elements [index]);
  7283. lock.exit();
  7284. return result;
  7285. }
  7286. /** Returns a pointer to the first object in the array.
  7287. This will return a null pointer if the array's empty.
  7288. @see getLast
  7289. */
  7290. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7291. {
  7292. lock.enter();
  7293. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? data.elements [0]
  7294. : (ObjectClass*) 0);
  7295. lock.exit();
  7296. return result;
  7297. }
  7298. /** Returns a pointer to the last object in the array.
  7299. This will return a null pointer if the array's empty.
  7300. @see getFirst
  7301. */
  7302. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7303. {
  7304. lock.enter();
  7305. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? data.elements [numUsed - 1]
  7306. : (ObjectClass*) 0);
  7307. lock.exit();
  7308. return result;
  7309. }
  7310. /** Finds the index of the first occurrence of an object in the array.
  7311. @param objectToLookFor the object to look for
  7312. @returns the index at which the object was found, or -1 if it's not found
  7313. */
  7314. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7315. {
  7316. int result = -1;
  7317. lock.enter();
  7318. ObjectClass** e = data.elements;
  7319. for (int i = numUsed; --i >= 0;)
  7320. {
  7321. if (objectToLookFor == *e)
  7322. {
  7323. result = (int) (e - data.elements);
  7324. break;
  7325. }
  7326. ++e;
  7327. }
  7328. lock.exit();
  7329. return result;
  7330. }
  7331. /** Returns true if the array contains a specified object.
  7332. @param objectToLookFor the object to look for
  7333. @returns true if the object is in the array
  7334. */
  7335. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7336. {
  7337. lock.enter();
  7338. ObjectClass** e = data.elements;
  7339. for (int i = numUsed; --i >= 0;)
  7340. {
  7341. if (objectToLookFor == *e)
  7342. {
  7343. lock.exit();
  7344. return true;
  7345. }
  7346. ++e;
  7347. }
  7348. lock.exit();
  7349. return false;
  7350. }
  7351. /** Appends a new object to the end of the array.
  7352. This will increase the new object's reference count.
  7353. @param newObject the new object to add to the array
  7354. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7355. */
  7356. void add (ObjectClass* const newObject) throw()
  7357. {
  7358. lock.enter();
  7359. data.ensureAllocatedSize (numUsed + 1);
  7360. data.elements [numUsed++] = newObject;
  7361. if (newObject != 0)
  7362. newObject->incReferenceCount();
  7363. lock.exit();
  7364. }
  7365. /** Inserts a new object into the array at the given index.
  7366. If the index is less than 0 or greater than the size of the array, the
  7367. element will be added to the end of the array.
  7368. Otherwise, it will be inserted into the array, moving all the later elements
  7369. along to make room.
  7370. This will increase the new object's reference count.
  7371. @param indexToInsertAt the index at which the new element should be inserted
  7372. @param newObject the new object to add to the array
  7373. @see add, addSorted, addIfNotAlreadyThere, set
  7374. */
  7375. void insert (int indexToInsertAt,
  7376. ObjectClass* const newObject) throw()
  7377. {
  7378. if (indexToInsertAt >= 0)
  7379. {
  7380. lock.enter();
  7381. if (indexToInsertAt > numUsed)
  7382. indexToInsertAt = numUsed;
  7383. data.ensureAllocatedSize (numUsed + 1);
  7384. ObjectClass** const e = data.elements + indexToInsertAt;
  7385. const int numToMove = numUsed - indexToInsertAt;
  7386. if (numToMove > 0)
  7387. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7388. *e = newObject;
  7389. if (newObject != 0)
  7390. newObject->incReferenceCount();
  7391. ++numUsed;
  7392. lock.exit();
  7393. }
  7394. else
  7395. {
  7396. add (newObject);
  7397. }
  7398. }
  7399. /** Appends a new object at the end of the array as long as the array doesn't
  7400. already contain it.
  7401. If the array already contains a matching object, nothing will be done.
  7402. @param newObject the new object to add to the array
  7403. */
  7404. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7405. {
  7406. lock.enter();
  7407. if (! contains (newObject))
  7408. add (newObject);
  7409. lock.exit();
  7410. }
  7411. /** Replaces an object in the array with a different one.
  7412. If the index is less than zero, this method does nothing.
  7413. If the index is beyond the end of the array, the new object is added to the end of the array.
  7414. The object being added has its reference count increased, and if it's replacing
  7415. another object, then that one has its reference count decreased, and may be deleted.
  7416. @param indexToChange the index whose value you want to change
  7417. @param newObject the new value to set for this index.
  7418. @see add, insert, remove
  7419. */
  7420. void set (const int indexToChange,
  7421. ObjectClass* const newObject)
  7422. {
  7423. if (indexToChange >= 0)
  7424. {
  7425. lock.enter();
  7426. if (newObject != 0)
  7427. newObject->incReferenceCount();
  7428. if (indexToChange < numUsed)
  7429. {
  7430. if (data.elements [indexToChange] != 0)
  7431. data.elements [indexToChange]->decReferenceCount();
  7432. data.elements [indexToChange] = newObject;
  7433. }
  7434. else
  7435. {
  7436. data.ensureAllocatedSize (numUsed + 1);
  7437. data.elements [numUsed++] = newObject;
  7438. }
  7439. lock.exit();
  7440. }
  7441. }
  7442. /** Adds elements from another array to the end of this array.
  7443. @param arrayToAddFrom the array from which to copy the elements
  7444. @param startIndex the first element of the other array to start copying from
  7445. @param numElementsToAdd how many elements to add from the other array. If this
  7446. value is negative or greater than the number of available elements,
  7447. all available elements will be copied.
  7448. @see add
  7449. */
  7450. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7451. int startIndex = 0,
  7452. int numElementsToAdd = -1) throw()
  7453. {
  7454. arrayToAddFrom.lockArray();
  7455. lock.enter();
  7456. if (startIndex < 0)
  7457. {
  7458. jassertfalse
  7459. startIndex = 0;
  7460. }
  7461. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7462. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7463. if (numElementsToAdd > 0)
  7464. {
  7465. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7466. while (--numElementsToAdd >= 0)
  7467. add (arrayToAddFrom.getUnchecked (startIndex++));
  7468. }
  7469. lock.exit();
  7470. arrayToAddFrom.unlockArray();
  7471. }
  7472. /** Inserts a new object into the array assuming that the array is sorted.
  7473. This will use a comparator to find the position at which the new object
  7474. should go. If the array isn't sorted, the behaviour of this
  7475. method will be unpredictable.
  7476. @param comparator the comparator object to use to compare the elements - see the
  7477. sort() method for details about this object's form
  7478. @param newObject the new object to insert to the array
  7479. @see add, sort
  7480. */
  7481. template <class ElementComparator>
  7482. void addSorted (ElementComparator& comparator,
  7483. ObjectClass* newObject) throw()
  7484. {
  7485. lock.enter();
  7486. insert (findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed), newObject);
  7487. lock.exit();
  7488. }
  7489. /** Inserts or replaces an object in the array, assuming it is sorted.
  7490. This is similar to addSorted, but if a matching element already exists, then it will be
  7491. replaced by the new one, rather than the new one being added as well.
  7492. */
  7493. template <class ElementComparator>
  7494. void addOrReplaceSorted (ElementComparator& comparator,
  7495. ObjectClass* newObject) throw()
  7496. {
  7497. lock.enter();
  7498. const int index = findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed);
  7499. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  7500. set (index - 1, newObject); // replace an existing object that matches
  7501. else
  7502. insert (index, newObject); // no match, so insert the new one
  7503. lock.exit();
  7504. }
  7505. /** Removes an object from the array.
  7506. This will remove the object at a given index and move back all the
  7507. subsequent objects to close the gap.
  7508. If the index passed in is out-of-range, nothing will happen.
  7509. The object that is removed will have its reference count decreased,
  7510. and may be deleted if not referenced from elsewhere.
  7511. @param indexToRemove the index of the element to remove
  7512. @see removeObject, removeRange
  7513. */
  7514. void remove (const int indexToRemove)
  7515. {
  7516. lock.enter();
  7517. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7518. {
  7519. ObjectClass** const e = data.elements + indexToRemove;
  7520. if (*e != 0)
  7521. (*e)->decReferenceCount();
  7522. --numUsed;
  7523. const int numberToShift = numUsed - indexToRemove;
  7524. if (numberToShift > 0)
  7525. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7526. if ((numUsed << 1) < data.numAllocated)
  7527. minimiseStorageOverheads();
  7528. }
  7529. lock.exit();
  7530. }
  7531. /** Removes the first occurrence of a specified object from the array.
  7532. If the item isn't found, no action is taken. If it is found, it is
  7533. removed and has its reference count decreased.
  7534. @param objectToRemove the object to try to remove
  7535. @see remove, removeRange
  7536. */
  7537. void removeObject (ObjectClass* const objectToRemove)
  7538. {
  7539. lock.enter();
  7540. remove (indexOf (objectToRemove));
  7541. lock.exit();
  7542. }
  7543. /** Removes a range of objects from the array.
  7544. This will remove a set of objects, starting from the given index,
  7545. and move any subsequent elements down to close the gap.
  7546. If the range extends beyond the bounds of the array, it will
  7547. be safely clipped to the size of the array.
  7548. The objects that are removed will have their reference counts decreased,
  7549. and may be deleted if not referenced from elsewhere.
  7550. @param startIndex the index of the first object to remove
  7551. @param numberToRemove how many objects should be removed
  7552. @see remove, removeObject
  7553. */
  7554. void removeRange (const int startIndex,
  7555. const int numberToRemove)
  7556. {
  7557. lock.enter();
  7558. const int start = jlimit (0, numUsed, startIndex);
  7559. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7560. if (end > start)
  7561. {
  7562. int i;
  7563. for (i = start; i < end; ++i)
  7564. {
  7565. if (data.elements[i] != 0)
  7566. {
  7567. data.elements[i]->decReferenceCount();
  7568. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7569. }
  7570. }
  7571. const int rangeSize = end - start;
  7572. ObjectClass** e = data.elements + start;
  7573. i = numUsed - end;
  7574. numUsed -= rangeSize;
  7575. while (--i >= 0)
  7576. {
  7577. *e = e [rangeSize];
  7578. ++e;
  7579. }
  7580. if ((numUsed << 1) < data.numAllocated)
  7581. minimiseStorageOverheads();
  7582. }
  7583. lock.exit();
  7584. }
  7585. /** Removes the last n objects from the array.
  7586. The objects that are removed will have their reference counts decreased,
  7587. and may be deleted if not referenced from elsewhere.
  7588. @param howManyToRemove how many objects to remove from the end of the array
  7589. @see remove, removeObject, removeRange
  7590. */
  7591. void removeLast (int howManyToRemove = 1)
  7592. {
  7593. lock.enter();
  7594. if (howManyToRemove > numUsed)
  7595. howManyToRemove = numUsed;
  7596. while (--howManyToRemove >= 0)
  7597. remove (numUsed - 1);
  7598. lock.exit();
  7599. }
  7600. /** Swaps a pair of objects in the array.
  7601. If either of the indexes passed in is out-of-range, nothing will happen,
  7602. otherwise the two objects at these positions will be exchanged.
  7603. */
  7604. void swap (const int index1,
  7605. const int index2) throw()
  7606. {
  7607. lock.enter();
  7608. if (((unsigned int) index1) < (unsigned int) numUsed
  7609. && ((unsigned int) index2) < (unsigned int) numUsed)
  7610. {
  7611. swapVariables (data.elements [index1],
  7612. data.elements [index2]);
  7613. }
  7614. lock.exit();
  7615. }
  7616. /** Moves one of the objects to a different position.
  7617. This will move the object to a specified index, shuffling along
  7618. any intervening elements as required.
  7619. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7620. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7621. @param currentIndex the index of the object to be moved. If this isn't a
  7622. valid index, then nothing will be done
  7623. @param newIndex the index at which you'd like this object to end up. If this
  7624. is less than zero, it will be moved to the end of the array
  7625. */
  7626. void move (const int currentIndex,
  7627. int newIndex) throw()
  7628. {
  7629. if (currentIndex != newIndex)
  7630. {
  7631. lock.enter();
  7632. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7633. {
  7634. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7635. newIndex = numUsed - 1;
  7636. ObjectClass* const value = data.elements [currentIndex];
  7637. if (newIndex > currentIndex)
  7638. {
  7639. memmove (data.elements + currentIndex,
  7640. data.elements + currentIndex + 1,
  7641. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7642. }
  7643. else
  7644. {
  7645. memmove (data.elements + newIndex + 1,
  7646. data.elements + newIndex,
  7647. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7648. }
  7649. data.elements [newIndex] = value;
  7650. }
  7651. lock.exit();
  7652. }
  7653. }
  7654. /** Compares this array to another one.
  7655. @returns true only if the other array contains the same objects in the same order
  7656. */
  7657. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7658. {
  7659. other.lockArray();
  7660. lock.enter();
  7661. bool result = numUsed == other.numUsed;
  7662. if (result)
  7663. {
  7664. for (int i = numUsed; --i >= 0;)
  7665. {
  7666. if (data.elements [i] != other.data.elements [i])
  7667. {
  7668. result = false;
  7669. break;
  7670. }
  7671. }
  7672. }
  7673. lock.exit();
  7674. other.unlockArray();
  7675. return result;
  7676. }
  7677. /** Compares this array to another one.
  7678. @see operator==
  7679. */
  7680. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7681. {
  7682. return ! operator== (other);
  7683. }
  7684. /** Sorts the elements in the array.
  7685. This will use a comparator object to sort the elements into order. The object
  7686. passed must have a method of the form:
  7687. @code
  7688. int compareElements (ElementType first, ElementType second);
  7689. @endcode
  7690. ..and this method must return:
  7691. - a value of < 0 if the first comes before the second
  7692. - a value of 0 if the two objects are equivalent
  7693. - a value of > 0 if the second comes before the first
  7694. To improve performance, the compareElements() method can be declared as static or const.
  7695. @param comparator the comparator to use for comparing elements.
  7696. @param retainOrderOfEquivalentItems if this is true, then items
  7697. which the comparator says are equivalent will be
  7698. kept in the order in which they currently appear
  7699. in the array. This is slower to perform, but may
  7700. be important in some cases. If it's false, a faster
  7701. algorithm is used, but equivalent elements may be
  7702. rearranged.
  7703. @see sortArray
  7704. */
  7705. template <class ElementComparator>
  7706. void sort (ElementComparator& comparator,
  7707. const bool retainOrderOfEquivalentItems = false) const throw()
  7708. {
  7709. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7710. // avoids getting warning messages about the parameter being unused
  7711. lock.enter();
  7712. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7713. lock.exit();
  7714. }
  7715. /** Reduces the amount of storage being used by the array.
  7716. Arrays typically allocate slightly more storage than they need, and after
  7717. removing elements, they may have quite a lot of unused space allocated.
  7718. This method will reduce the amount of allocated storage to a minimum.
  7719. */
  7720. void minimiseStorageOverheads() throw()
  7721. {
  7722. lock.enter();
  7723. if (numUsed == 0)
  7724. {
  7725. data.setAllocatedSize (0);
  7726. }
  7727. else
  7728. {
  7729. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  7730. if (newAllocation < data.numAllocated)
  7731. data.setAllocatedSize (newAllocation);
  7732. }
  7733. lock.exit();
  7734. }
  7735. /** Locks the array's CriticalSection.
  7736. Of course if the type of section used is a DummyCriticalSection, this won't
  7737. have any effect.
  7738. @see unlockArray
  7739. */
  7740. void lockArray() const throw()
  7741. {
  7742. lock.enter();
  7743. }
  7744. /** Unlocks the array's CriticalSection.
  7745. Of course if the type of section used is a DummyCriticalSection, this won't
  7746. have any effect.
  7747. @see lockArray
  7748. */
  7749. void unlockArray() const throw()
  7750. {
  7751. lock.exit();
  7752. }
  7753. juce_UseDebuggingNewOperator
  7754. private:
  7755. ArrayAllocationBase <ObjectClass*> data;
  7756. int numUsed;
  7757. TypeOfCriticalSectionToUse lock;
  7758. };
  7759. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7760. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7761. #endif
  7762. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7763. #endif
  7764. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  7765. #endif
  7766. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7767. /********* Start of inlined file: juce_SortedSet.h *********/
  7768. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7769. #define __JUCE_SORTEDSET_JUCEHEADER__
  7770. #if JUCE_MSVC
  7771. #pragma warning (push)
  7772. #pragma warning (disable: 4512)
  7773. #endif
  7774. /**
  7775. Holds a set of unique primitive objects, such as ints or doubles.
  7776. A set can only hold one item with a given value, so if for example it's a
  7777. set of integers, attempting to add the same integer twice will do nothing
  7778. the second time.
  7779. Internally, the list of items is kept sorted (which means that whatever
  7780. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7781. to determine the order), and searching the set for known values is very fast
  7782. because it uses a binary-chop method.
  7783. Note that if you're using a class or struct as the element type, it must be
  7784. capable of being copied or moved with a straightforward memcpy, rather than
  7785. needing construction and destruction code.
  7786. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7787. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7788. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7789. */
  7790. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7791. class SortedSet
  7792. {
  7793. public:
  7794. /** Creates an empty set.
  7795. @param granularity this is the size of increment by which the internal storage
  7796. used by the array will grow. Only change it from the default if you know the
  7797. array is going to be very big and needs to be able to grow efficiently.
  7798. */
  7799. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7800. : data (granularity),
  7801. numUsed (0)
  7802. {
  7803. }
  7804. /** Creates a copy of another set.
  7805. @param other the set to copy
  7806. */
  7807. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7808. : data (other.data.granularity)
  7809. {
  7810. other.lockSet();
  7811. numUsed = other.numUsed;
  7812. data.setAllocatedSize (other.numUsed);
  7813. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  7814. other.unlockSet();
  7815. }
  7816. /** Destructor. */
  7817. ~SortedSet() throw()
  7818. {
  7819. }
  7820. /** Copies another set over this one.
  7821. @param other the set to copy
  7822. */
  7823. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7824. {
  7825. if (this != &other)
  7826. {
  7827. other.lockSet();
  7828. lock.enter();
  7829. data.granularity = other.data.granularity;
  7830. data.ensureAllocatedSize (other.size());
  7831. numUsed = other.numUsed;
  7832. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  7833. minimiseStorageOverheads();
  7834. lock.exit();
  7835. other.unlockSet();
  7836. }
  7837. return *this;
  7838. }
  7839. /** Compares this set to another one.
  7840. Two sets are considered equal if they both contain the same set of
  7841. elements.
  7842. @param other the other set to compare with
  7843. */
  7844. bool operator== (const SortedSet<ElementType>& other) const throw()
  7845. {
  7846. lock.enter();
  7847. if (numUsed != other.numUsed)
  7848. {
  7849. lock.exit();
  7850. return false;
  7851. }
  7852. for (int i = numUsed; --i >= 0;)
  7853. {
  7854. if (data.elements [i] != other.data.elements [i])
  7855. {
  7856. lock.exit();
  7857. return false;
  7858. }
  7859. }
  7860. lock.exit();
  7861. return true;
  7862. }
  7863. /** Compares this set to another one.
  7864. Two sets are considered equal if they both contain the same set of
  7865. elements.
  7866. @param other the other set to compare with
  7867. */
  7868. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7869. {
  7870. return ! operator== (other);
  7871. }
  7872. /** Removes all elements from the set.
  7873. This will remove all the elements, and free any storage that the set is
  7874. using. To clear it without freeing the storage, use the clearQuick()
  7875. method instead.
  7876. @see clearQuick
  7877. */
  7878. void clear() throw()
  7879. {
  7880. lock.enter();
  7881. data.setAllocatedSize (0);
  7882. numUsed = 0;
  7883. lock.exit();
  7884. }
  7885. /** Removes all elements from the set without freeing the array's allocated storage.
  7886. @see clear
  7887. */
  7888. void clearQuick() throw()
  7889. {
  7890. lock.enter();
  7891. numUsed = 0;
  7892. lock.exit();
  7893. }
  7894. /** Returns the current number of elements in the set.
  7895. */
  7896. inline int size() const throw()
  7897. {
  7898. return numUsed;
  7899. }
  7900. /** Returns one of the elements in the set.
  7901. If the index passed in is beyond the range of valid elements, this
  7902. will return zero.
  7903. If you're certain that the index will always be a valid element, you
  7904. can call getUnchecked() instead, which is faster.
  7905. @param index the index of the element being requested (0 is the first element in the set)
  7906. @see getUnchecked, getFirst, getLast
  7907. */
  7908. inline ElementType operator[] (const int index) const throw()
  7909. {
  7910. lock.enter();
  7911. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  7912. ? data.elements [index]
  7913. : (ElementType) 0;
  7914. lock.exit();
  7915. return result;
  7916. }
  7917. /** Returns one of the elements in the set, without checking the index passed in.
  7918. Unlike the operator[] method, this will try to return an element without
  7919. checking that the index is within the bounds of the set, so should only
  7920. be used when you're confident that it will always be a valid index.
  7921. @param index the index of the element being requested (0 is the first element in the set)
  7922. @see operator[], getFirst, getLast
  7923. */
  7924. inline ElementType getUnchecked (const int index) const throw()
  7925. {
  7926. lock.enter();
  7927. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7928. const ElementType result = data.elements [index];
  7929. lock.exit();
  7930. return result;
  7931. }
  7932. /** Returns the first element in the set, or 0 if the set is empty.
  7933. @see operator[], getUnchecked, getLast
  7934. */
  7935. inline ElementType getFirst() const throw()
  7936. {
  7937. lock.enter();
  7938. const ElementType result = (numUsed > 0) ? data.elements [0]
  7939. : (ElementType) 0;
  7940. lock.exit();
  7941. return result;
  7942. }
  7943. /** Returns the last element in the set, or 0 if the set is empty.
  7944. @see operator[], getUnchecked, getFirst
  7945. */
  7946. inline ElementType getLast() const throw()
  7947. {
  7948. lock.enter();
  7949. const ElementType result = (numUsed > 0) ? data.elements [numUsed - 1]
  7950. : (ElementType) 0;
  7951. lock.exit();
  7952. return result;
  7953. }
  7954. /** Finds the index of the first element which matches the value passed in.
  7955. This will search the set for the given object, and return the index
  7956. of its first occurrence. If the object isn't found, the method will return -1.
  7957. @param elementToLookFor the value or object to look for
  7958. @returns the index of the object, or -1 if it's not found
  7959. */
  7960. int indexOf (const ElementType elementToLookFor) const throw()
  7961. {
  7962. lock.enter();
  7963. int start = 0;
  7964. int end = numUsed;
  7965. for (;;)
  7966. {
  7967. if (start >= end)
  7968. {
  7969. lock.exit();
  7970. return -1;
  7971. }
  7972. else if (elementToLookFor == data.elements [start])
  7973. {
  7974. lock.exit();
  7975. return start;
  7976. }
  7977. else
  7978. {
  7979. const int halfway = (start + end) >> 1;
  7980. if (halfway == start)
  7981. {
  7982. lock.exit();
  7983. return -1;
  7984. }
  7985. else if (elementToLookFor >= data.elements [halfway])
  7986. start = halfway;
  7987. else
  7988. end = halfway;
  7989. }
  7990. }
  7991. }
  7992. /** Returns true if the set contains at least one occurrence of an object.
  7993. @param elementToLookFor the value or object to look for
  7994. @returns true if the item is found
  7995. */
  7996. bool contains (const ElementType elementToLookFor) const throw()
  7997. {
  7998. lock.enter();
  7999. int start = 0;
  8000. int end = numUsed;
  8001. for (;;)
  8002. {
  8003. if (start >= end)
  8004. {
  8005. lock.exit();
  8006. return false;
  8007. }
  8008. else if (elementToLookFor == data.elements [start])
  8009. {
  8010. lock.exit();
  8011. return true;
  8012. }
  8013. else
  8014. {
  8015. const int halfway = (start + end) >> 1;
  8016. if (halfway == start)
  8017. {
  8018. lock.exit();
  8019. return false;
  8020. }
  8021. else if (elementToLookFor >= data.elements [halfway])
  8022. start = halfway;
  8023. else
  8024. end = halfway;
  8025. }
  8026. }
  8027. }
  8028. /** Adds a new element to the set, (as long as it's not already in there).
  8029. @param newElement the new object to add to the set
  8030. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8031. */
  8032. void add (const ElementType newElement) throw()
  8033. {
  8034. lock.enter();
  8035. int start = 0;
  8036. int end = numUsed;
  8037. for (;;)
  8038. {
  8039. if (start >= end)
  8040. {
  8041. jassert (start <= end);
  8042. insertInternal (start, newElement);
  8043. break;
  8044. }
  8045. else if (newElement == data.elements [start])
  8046. {
  8047. break;
  8048. }
  8049. else
  8050. {
  8051. const int halfway = (start + end) >> 1;
  8052. if (halfway == start)
  8053. {
  8054. if (newElement >= data.elements [halfway])
  8055. insertInternal (start + 1, newElement);
  8056. else
  8057. insertInternal (start, newElement);
  8058. break;
  8059. }
  8060. else if (newElement >= data.elements [halfway])
  8061. start = halfway;
  8062. else
  8063. end = halfway;
  8064. }
  8065. }
  8066. lock.exit();
  8067. }
  8068. /** Adds elements from an array to this set.
  8069. @param elementsToAdd the array of elements to add
  8070. @param numElementsToAdd how many elements are in this other array
  8071. @see add
  8072. */
  8073. void addArray (const ElementType* elementsToAdd,
  8074. int numElementsToAdd) throw()
  8075. {
  8076. lock.enter();
  8077. while (--numElementsToAdd >= 0)
  8078. add (*elementsToAdd++);
  8079. lock.exit();
  8080. }
  8081. /** Adds elements from another set to this one.
  8082. @param setToAddFrom the set from which to copy the elements
  8083. @param startIndex the first element of the other set to start copying from
  8084. @param numElementsToAdd how many elements to add from the other set. If this
  8085. value is negative or greater than the number of available elements,
  8086. all available elements will be copied.
  8087. @see add
  8088. */
  8089. template <class OtherSetType>
  8090. void addSet (const OtherSetType& setToAddFrom,
  8091. int startIndex = 0,
  8092. int numElementsToAdd = -1) throw()
  8093. {
  8094. setToAddFrom.lockSet();
  8095. lock.enter();
  8096. jassert (this != &setToAddFrom);
  8097. if (this != &setToAddFrom)
  8098. {
  8099. if (startIndex < 0)
  8100. {
  8101. jassertfalse
  8102. startIndex = 0;
  8103. }
  8104. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8105. numElementsToAdd = setToAddFrom.size() - startIndex;
  8106. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8107. }
  8108. lock.exit();
  8109. setToAddFrom.unlockSet();
  8110. }
  8111. /** Removes an element from the set.
  8112. This will remove the element at a given index.
  8113. If the index passed in is out-of-range, nothing will happen.
  8114. @param indexToRemove the index of the element to remove
  8115. @returns the element that has been removed
  8116. @see removeValue, removeRange
  8117. */
  8118. ElementType remove (const int indexToRemove) throw()
  8119. {
  8120. lock.enter();
  8121. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8122. {
  8123. --numUsed;
  8124. ElementType* const e = data.elements + indexToRemove;
  8125. ElementType const removed = *e;
  8126. const int numberToShift = numUsed - indexToRemove;
  8127. if (numberToShift > 0)
  8128. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8129. if ((numUsed << 1) < data.numAllocated)
  8130. minimiseStorageOverheads();
  8131. lock.exit();
  8132. return removed;
  8133. }
  8134. else
  8135. {
  8136. lock.exit();
  8137. return 0;
  8138. }
  8139. }
  8140. /** Removes an item from the set.
  8141. This will remove the given element from the set, if it's there.
  8142. @param valueToRemove the object to try to remove
  8143. @see remove, removeRange
  8144. */
  8145. void removeValue (const ElementType valueToRemove) throw()
  8146. {
  8147. lock.enter();
  8148. remove (indexOf (valueToRemove));
  8149. lock.exit();
  8150. }
  8151. /** Removes any elements which are also in another set.
  8152. @param otherSet the other set in which to look for elements to remove
  8153. @see removeValuesNotIn, remove, removeValue, removeRange
  8154. */
  8155. template <class OtherSetType>
  8156. void removeValuesIn (const OtherSetType& otherSet) throw()
  8157. {
  8158. otherSet.lockSet();
  8159. lock.enter();
  8160. if (this == &otherSet)
  8161. {
  8162. clear();
  8163. }
  8164. else
  8165. {
  8166. if (otherSet.size() > 0)
  8167. {
  8168. for (int i = numUsed; --i >= 0;)
  8169. if (otherSet.contains (data.elements [i]))
  8170. remove (i);
  8171. }
  8172. }
  8173. lock.exit();
  8174. otherSet.unlockSet();
  8175. }
  8176. /** Removes any elements which are not found in another set.
  8177. Only elements which occur in this other set will be retained.
  8178. @param otherSet the set in which to look for elements NOT to remove
  8179. @see removeValuesIn, remove, removeValue, removeRange
  8180. */
  8181. template <class OtherSetType>
  8182. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8183. {
  8184. otherSet.lockSet();
  8185. lock.enter();
  8186. if (this != &otherSet)
  8187. {
  8188. if (otherSet.size() <= 0)
  8189. {
  8190. clear();
  8191. }
  8192. else
  8193. {
  8194. for (int i = numUsed; --i >= 0;)
  8195. if (! otherSet.contains (data.elements [i]))
  8196. remove (i);
  8197. }
  8198. }
  8199. lock.exit();
  8200. otherSet.lockSet();
  8201. }
  8202. /** Reduces the amount of storage being used by the set.
  8203. Sets typically allocate slightly more storage than they need, and after
  8204. removing elements, they may have quite a lot of unused space allocated.
  8205. This method will reduce the amount of allocated storage to a minimum.
  8206. */
  8207. void minimiseStorageOverheads() throw()
  8208. {
  8209. lock.enter();
  8210. if (numUsed == 0)
  8211. {
  8212. data.setAllocatedSize (0);
  8213. }
  8214. else
  8215. {
  8216. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  8217. if (newAllocation < data.numAllocated)
  8218. data.setAllocatedSize (newAllocation);
  8219. }
  8220. lock.exit();
  8221. }
  8222. /** Locks the set's CriticalSection.
  8223. Of course if the type of section used is a DummyCriticalSection, this won't
  8224. have any effect.
  8225. @see unlockSet
  8226. */
  8227. void lockSet() const throw()
  8228. {
  8229. lock.enter();
  8230. }
  8231. /** Unlocks the set's CriticalSection.
  8232. Of course if the type of section used is a DummyCriticalSection, this won't
  8233. have any effect.
  8234. @see lockSet
  8235. */
  8236. void unlockSet() const throw()
  8237. {
  8238. lock.exit();
  8239. }
  8240. juce_UseDebuggingNewOperator
  8241. private:
  8242. ArrayAllocationBase <ElementType> data;
  8243. int numUsed;
  8244. TypeOfCriticalSectionToUse lock;
  8245. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8246. {
  8247. data.ensureAllocatedSize (numUsed + 1);
  8248. ElementType* const insertPos = data.elements + indexToInsertAt;
  8249. const int numberToMove = numUsed - indexToInsertAt;
  8250. if (numberToMove > 0)
  8251. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8252. *insertPos = newElement;
  8253. ++numUsed;
  8254. }
  8255. };
  8256. #if JUCE_MSVC
  8257. #pragma warning (pop)
  8258. #endif
  8259. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8260. /********* End of inlined file: juce_SortedSet.h *********/
  8261. #endif
  8262. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8263. /********* Start of inlined file: juce_SparseSet.h *********/
  8264. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8265. #define __JUCE_SPARSESET_JUCEHEADER__
  8266. /**
  8267. Holds a set of primitive values, storing them as a set of ranges.
  8268. This container acts like a simple BitArray, but can efficiently hold large
  8269. continguous ranges of values. It's quite a specialised class, mostly useful
  8270. for things like keeping the set of selected rows in a listbox.
  8271. The type used as a template paramter must be an integer type, such as int, short,
  8272. int64, etc.
  8273. */
  8274. template <class Type>
  8275. class SparseSet
  8276. {
  8277. public:
  8278. /** Creates a new empty set. */
  8279. SparseSet() throw()
  8280. {
  8281. }
  8282. /** Creates a copy of another SparseSet. */
  8283. SparseSet (const SparseSet<Type>& other) throw()
  8284. : values (other.values)
  8285. {
  8286. }
  8287. /** Destructor. */
  8288. ~SparseSet() throw()
  8289. {
  8290. }
  8291. /** Clears the set. */
  8292. void clear() throw()
  8293. {
  8294. values.clear();
  8295. }
  8296. /** Checks whether the set is empty.
  8297. This is much quicker than using (size() == 0).
  8298. */
  8299. bool isEmpty() const throw()
  8300. {
  8301. return values.size() == 0;
  8302. }
  8303. /** Returns the number of values in the set.
  8304. Because of the way the data is stored, this method can take longer if there
  8305. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8306. are any items.
  8307. */
  8308. Type size() const throw()
  8309. {
  8310. Type num = 0;
  8311. for (int i = 0; i < values.size(); i += 2)
  8312. num += values[i + 1] - values[i];
  8313. return num;
  8314. }
  8315. /** Returns one of the values in the set.
  8316. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8317. @returns the value at this index, or 0 if it's out-of-range
  8318. */
  8319. Type operator[] (int index) const throw()
  8320. {
  8321. for (int i = 0; i < values.size(); i += 2)
  8322. {
  8323. const Type s = values.getUnchecked(i);
  8324. const Type e = values.getUnchecked(i + 1);
  8325. if (index < e - s)
  8326. return s + index;
  8327. index -= e - s;
  8328. }
  8329. return (Type) 0;
  8330. }
  8331. /** Checks whether a particular value is in the set. */
  8332. bool contains (const Type valueToLookFor) const throw()
  8333. {
  8334. bool on = false;
  8335. for (int i = 0; i < values.size(); ++i)
  8336. {
  8337. if (values.getUnchecked(i) > valueToLookFor)
  8338. return on;
  8339. on = ! on;
  8340. }
  8341. return false;
  8342. }
  8343. /** Returns the number of contiguous blocks of values.
  8344. @see getRange
  8345. */
  8346. int getNumRanges() const throw()
  8347. {
  8348. return values.size() >> 1;
  8349. }
  8350. /** Returns one of the contiguous ranges of values stored.
  8351. @param rangeIndex the index of the range to look up, between 0
  8352. and (getNumRanges() - 1)
  8353. @param startValue on return, the value at the start of the range
  8354. @param numValues on return, the number of values in the range
  8355. @see getTotalRange
  8356. */
  8357. bool getRange (const int rangeIndex,
  8358. Type& startValue,
  8359. Type& numValues) const throw()
  8360. {
  8361. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8362. {
  8363. startValue = values [rangeIndex << 1];
  8364. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8365. return true;
  8366. }
  8367. return false;
  8368. }
  8369. /** Returns the lowest and highest values in the set.
  8370. @see getRange
  8371. */
  8372. bool getTotalRange (Type& lowestValue,
  8373. Type& highestValue) const throw()
  8374. {
  8375. if (values.size() > 0)
  8376. {
  8377. lowestValue = values.getUnchecked (0);
  8378. highestValue = values.getUnchecked (values.size() - 1);
  8379. return true;
  8380. }
  8381. return false;
  8382. }
  8383. /** Adds a range of contiguous values to the set.
  8384. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8385. @param firstValue the start of the range of values to add
  8386. @param numValuesToAdd how many values to add
  8387. */
  8388. void addRange (const Type firstValue,
  8389. const Type numValuesToAdd) throw()
  8390. {
  8391. jassert (numValuesToAdd >= 0);
  8392. if (numValuesToAdd > 0)
  8393. {
  8394. removeRange (firstValue, numValuesToAdd);
  8395. IntegerElementComparator<Type> sorter;
  8396. values.addSorted (sorter, firstValue);
  8397. values.addSorted (sorter, firstValue + numValuesToAdd);
  8398. simplify();
  8399. }
  8400. }
  8401. /** Removes a range of values from the set.
  8402. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8403. @param firstValue the start of the range of values to remove
  8404. @param numValuesToRemove how many values to remove
  8405. */
  8406. void removeRange (const Type firstValue,
  8407. const Type numValuesToRemove) throw()
  8408. {
  8409. jassert (numValuesToRemove >= 0);
  8410. if (numValuesToRemove >= 0
  8411. && firstValue < values.getLast())
  8412. {
  8413. const bool onAtStart = contains (firstValue - 1);
  8414. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  8415. const bool onAtEnd = contains (lastValue);
  8416. for (int i = values.size(); --i >= 0;)
  8417. {
  8418. if (values.getUnchecked(i) <= lastValue)
  8419. {
  8420. while (values.getUnchecked(i) >= firstValue)
  8421. {
  8422. values.remove (i);
  8423. if (--i < 0)
  8424. break;
  8425. }
  8426. break;
  8427. }
  8428. }
  8429. IntegerElementComparator<Type> sorter;
  8430. if (onAtStart)
  8431. values.addSorted (sorter, firstValue);
  8432. if (onAtEnd)
  8433. values.addSorted (sorter, lastValue);
  8434. simplify();
  8435. }
  8436. }
  8437. /** Does an XOR of the values in a given range. */
  8438. void invertRange (const Type firstValue,
  8439. const Type numValues)
  8440. {
  8441. SparseSet newItems;
  8442. newItems.addRange (firstValue, numValues);
  8443. int i;
  8444. for (i = getNumRanges(); --i >= 0;)
  8445. {
  8446. const int start = values [i << 1];
  8447. const int end = values [(i << 1) + 1];
  8448. newItems.removeRange (start, end);
  8449. }
  8450. removeRange (firstValue, numValues);
  8451. for (i = newItems.getNumRanges(); --i >= 0;)
  8452. {
  8453. const int start = newItems.values [i << 1];
  8454. const int end = newItems.values [(i << 1) + 1];
  8455. addRange (start, end);
  8456. }
  8457. }
  8458. /** Checks whether any part of a given range overlaps any part of this one. */
  8459. bool overlapsRange (const Type firstValue,
  8460. const Type numValues) throw()
  8461. {
  8462. jassert (numValues >= 0);
  8463. if (numValues > 0)
  8464. {
  8465. for (int i = getNumRanges(); --i >= 0;)
  8466. {
  8467. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8468. return false;
  8469. if (firstValue + numValues > values.getUnchecked (i << 1))
  8470. return true;
  8471. }
  8472. }
  8473. return false;
  8474. }
  8475. /** Checks whether the whole of a given range is contained within this one. */
  8476. bool containsRange (const Type firstValue,
  8477. const Type numValues) throw()
  8478. {
  8479. jassert (numValues >= 0);
  8480. if (numValues > 0)
  8481. {
  8482. for (int i = getNumRanges(); --i >= 0;)
  8483. {
  8484. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8485. return false;
  8486. if (firstValue >= values.getUnchecked (i << 1)
  8487. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8488. return true;
  8489. }
  8490. }
  8491. return false;
  8492. }
  8493. bool operator== (const SparseSet<Type>& other) throw()
  8494. {
  8495. return values == other.values;
  8496. }
  8497. bool operator!= (const SparseSet<Type>& other) throw()
  8498. {
  8499. return values != other.values;
  8500. }
  8501. juce_UseDebuggingNewOperator
  8502. private:
  8503. // alternating start/end values of ranges of values that are present.
  8504. Array<Type> values;
  8505. void simplify() throw()
  8506. {
  8507. jassert ((values.size() & 1) == 0);
  8508. for (int i = values.size(); --i > 0;)
  8509. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8510. values.removeRange (i - 1, 2);
  8511. }
  8512. };
  8513. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8514. /********* End of inlined file: juce_SparseSet.h *********/
  8515. #endif
  8516. #ifndef __JUCE_VALUE_JUCEHEADER__
  8517. /********* Start of inlined file: juce_Value.h *********/
  8518. #ifndef __JUCE_VALUE_JUCEHEADER__
  8519. #define __JUCE_VALUE_JUCEHEADER__
  8520. /********* Start of inlined file: juce_Variant.h *********/
  8521. #ifndef __JUCE_VARIANT_JUCEHEADER__
  8522. #define __JUCE_VARIANT_JUCEHEADER__
  8523. class JUCE_API DynamicObject;
  8524. /**
  8525. A variant class, that can be used to hold a range of primitive values.
  8526. A var object can hold a range of simple primitive values, strings, or
  8527. a reference-counted pointer to a DynamicObject. The var class is intended
  8528. to act like the values used in dynamic scripting languages.
  8529. @see DynamicObject
  8530. */
  8531. class JUCE_API var
  8532. {
  8533. public:
  8534. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  8535. /** Creates a void variant. */
  8536. var() throw();
  8537. /** Destructor. */
  8538. ~var();
  8539. var (const var& valueToCopy) throw();
  8540. var (const int value) throw();
  8541. var (const bool value) throw();
  8542. var (const double value) throw();
  8543. var (const char* const value) throw();
  8544. var (const juce_wchar* const value) throw();
  8545. var (const String& value) throw();
  8546. var (DynamicObject* const object) throw();
  8547. var (MethodFunction method) throw();
  8548. const var& operator= (const var& valueToCopy) throw();
  8549. const var& operator= (const int value) throw();
  8550. const var& operator= (const bool value) throw();
  8551. const var& operator= (const double value) throw();
  8552. const var& operator= (const char* const value) throw();
  8553. const var& operator= (const juce_wchar* const value) throw();
  8554. const var& operator= (const String& value) throw();
  8555. const var& operator= (DynamicObject* const object) throw();
  8556. const var& operator= (MethodFunction method) throw();
  8557. operator int() const throw();
  8558. operator bool() const throw();
  8559. operator float() const throw();
  8560. operator double() const throw();
  8561. operator const String() const throw();
  8562. const String toString() const throw();
  8563. DynamicObject* getObject() const throw();
  8564. bool isVoid() const throw() { return type == voidType; }
  8565. bool isInt() const throw() { return type == intType; }
  8566. bool isBool() const throw() { return type == boolType; }
  8567. bool isDouble() const throw() { return type == doubleType; }
  8568. bool isString() const throw() { return type == stringType; }
  8569. bool isObject() const throw() { return type == objectType; }
  8570. bool isMethod() const throw() { return type == methodType; }
  8571. bool operator== (const var& other) const throw();
  8572. bool operator!= (const var& other) const throw();
  8573. /** Writes a binary representation of this value to a stream.
  8574. The data can be read back later using readFromStream().
  8575. */
  8576. void writeToStream (OutputStream& output) const throw();
  8577. /** Reads back a stored binary representation of a value.
  8578. The data in the stream must have been written using writeToStream(), or this
  8579. will have unpredictable results.
  8580. */
  8581. static const var readFromStream (InputStream& input) throw();
  8582. class JUCE_API identifier
  8583. {
  8584. public:
  8585. identifier (const char* const name) throw();
  8586. identifier (const String& name) throw();
  8587. ~identifier() throw();
  8588. bool operator== (const identifier& other) const throw()
  8589. {
  8590. jassert (hashCode != other.hashCode || name == other.name); // check for name hash collisions
  8591. return hashCode == other.hashCode;
  8592. }
  8593. String name;
  8594. int hashCode;
  8595. };
  8596. /** If this variant is an object, this returns one of its properties. */
  8597. const var operator[] (const identifier& propertyName) const throw();
  8598. /** If this variant is an object, this invokes one of its methods with no arguments. */
  8599. const var call (const identifier& method) const;
  8600. /** If this variant is an object, this invokes one of its methods with one argument. */
  8601. const var call (const identifier& method, const var& arg1) const;
  8602. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  8603. const var call (const identifier& method, const var& arg1, const var& arg2) const;
  8604. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  8605. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3);
  8606. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  8607. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  8608. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  8609. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  8610. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  8611. const var invoke (const identifier& method, const var* arguments, int numArguments) const;
  8612. /** If this variant is a method pointer, this invokes it on a target object. */
  8613. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  8614. juce_UseDebuggingNewOperator
  8615. private:
  8616. enum Type
  8617. {
  8618. voidType = 0,
  8619. intType,
  8620. boolType,
  8621. doubleType,
  8622. stringType,
  8623. objectType,
  8624. methodType
  8625. };
  8626. Type type;
  8627. union
  8628. {
  8629. int intValue;
  8630. bool boolValue;
  8631. double doubleValue;
  8632. String* stringValue;
  8633. DynamicObject* objectValue;
  8634. MethodFunction methodValue;
  8635. } value;
  8636. void releaseValue() throw();
  8637. };
  8638. /**
  8639. Represents a dynamically implemented object.
  8640. An instance of this class can be used to store named properties, and
  8641. by subclassing hasMethod() and invokeMethod(), you can give your object
  8642. methods.
  8643. This is intended for use as a wrapper for scripting language objects.
  8644. */
  8645. class JUCE_API DynamicObject : public ReferenceCountedObject
  8646. {
  8647. public:
  8648. DynamicObject();
  8649. /** Destructor. */
  8650. virtual ~DynamicObject();
  8651. /** Returns true if the object has a property with this name.
  8652. Note that if the property is actually a method, this will return false.
  8653. */
  8654. virtual bool hasProperty (const var::identifier& propertyName) const;
  8655. /** Returns a named property.
  8656. This returns a void if no such property exists.
  8657. */
  8658. virtual const var getProperty (const var::identifier& propertyName) const;
  8659. /** Sets a named property. */
  8660. virtual void setProperty (const var::identifier& propertyName, const var& newValue);
  8661. /** Removes a named property. */
  8662. virtual void removeProperty (const var::identifier& propertyName);
  8663. /** Checks whether this object has the specified method.
  8664. The default implementation of this just checks whether there's a property
  8665. with this name that's actually a method, but this can be overridden for
  8666. building objects with dynamic invocation.
  8667. */
  8668. virtual bool hasMethod (const var::identifier& methodName) const;
  8669. /** Invokes a named method on this object.
  8670. The default implementation looks up the named property, and if it's a method
  8671. call, then it invokes it.
  8672. This method is virtual to allow more dynamic invocation to used for objects
  8673. where the methods may not already be set as properies.
  8674. */
  8675. virtual const var invokeMethod (const var::identifier& methodName,
  8676. const var* parameters,
  8677. int numParameters);
  8678. /** Sets up a method.
  8679. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  8680. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  8681. the code easier to read,
  8682. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  8683. @code
  8684. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  8685. @endcode
  8686. */
  8687. void setMethod (const var::identifier& methodName,
  8688. var::MethodFunction methodFunction);
  8689. /** Removes all properties and methods from the object. */
  8690. void clear();
  8691. juce_UseDebuggingNewOperator
  8692. private:
  8693. Array <int> propertyIds;
  8694. OwnedArray <var> propertyValues;
  8695. };
  8696. #endif // __JUCE_VARIANT_JUCEHEADER__
  8697. /********* End of inlined file: juce_Variant.h *********/
  8698. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  8699. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  8700. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  8701. /********* Start of inlined file: juce_MessageListener.h *********/
  8702. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  8703. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  8704. /********* Start of inlined file: juce_Message.h *********/
  8705. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  8706. #define __JUCE_MESSAGE_JUCEHEADER__
  8707. class MessageListener;
  8708. class MessageManager;
  8709. /** The base class for objects that can be delivered to a MessageListener.
  8710. The simplest Message object contains a few integer and pointer parameters
  8711. that the user can set, and this is enough for a lot of purposes. For passing more
  8712. complex data, subclasses of Message can also be used.
  8713. @see MessageListener, MessageManager, ActionListener, ChangeListener
  8714. */
  8715. class JUCE_API Message
  8716. {
  8717. public:
  8718. /** Creates an uninitialised message.
  8719. The class's variables will also be left uninitialised.
  8720. */
  8721. Message() throw();
  8722. /** Creates a message object, filling in the member variables.
  8723. The corresponding public member variables will be set from the parameters
  8724. passed in.
  8725. */
  8726. Message (const int intParameter1,
  8727. const int intParameter2,
  8728. const int intParameter3,
  8729. void* const pointerParameter) throw();
  8730. /** Destructor. */
  8731. virtual ~Message() throw();
  8732. // These values can be used for carrying simple data that the application needs to
  8733. // pass around. For more complex messages, just create a subclass.
  8734. int intParameter1; /**< user-defined integer value. */
  8735. int intParameter2; /**< user-defined integer value. */
  8736. int intParameter3; /**< user-defined integer value. */
  8737. void* pointerParameter; /**< user-defined pointer value. */
  8738. juce_UseDebuggingNewOperator
  8739. private:
  8740. friend class MessageListener;
  8741. friend class MessageManager;
  8742. MessageListener* messageRecipient;
  8743. Message (const Message&);
  8744. const Message& operator= (const Message&);
  8745. };
  8746. #endif // __JUCE_MESSAGE_JUCEHEADER__
  8747. /********* End of inlined file: juce_Message.h *********/
  8748. /**
  8749. MessageListener subclasses can post and receive Message objects.
  8750. @see Message, MessageManager, ActionListener, ChangeListener
  8751. */
  8752. class JUCE_API MessageListener
  8753. {
  8754. protected:
  8755. /** Creates a MessageListener. */
  8756. MessageListener() throw();
  8757. public:
  8758. /** Destructor.
  8759. When a MessageListener is deleted, it removes itself from a global list
  8760. of registered listeners, so that the isValidMessageListener() method
  8761. will no longer return true.
  8762. */
  8763. virtual ~MessageListener();
  8764. /** This is the callback method that receives incoming messages.
  8765. This is called by the MessageManager from its dispatch loop.
  8766. @see postMessage
  8767. */
  8768. virtual void handleMessage (const Message& message) = 0;
  8769. /** Sends a message to the message queue, for asynchronous delivery to this listener
  8770. later on.
  8771. This method can be called safely by any thread.
  8772. @param message the message object to send - this will be deleted
  8773. automatically by the message queue, so don't keep any
  8774. references to it after calling this method.
  8775. @see handleMessage
  8776. */
  8777. void postMessage (Message* const message) const throw();
  8778. /** Checks whether this MessageListener has been deleted.
  8779. Although not foolproof, this method is safe to call on dangling or null
  8780. pointers. A list of active MessageListeners is kept internally, so this
  8781. checks whether the object is on this list or not.
  8782. Note that it's possible to get a false-positive here, if an object is
  8783. deleted and another is subsequently created that happens to be at the
  8784. exact same memory location, but I can't think of a good way of avoiding
  8785. this.
  8786. */
  8787. bool isValidMessageListener() const throw();
  8788. };
  8789. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  8790. /********* End of inlined file: juce_MessageListener.h *********/
  8791. /**
  8792. Has a callback method that is triggered asynchronously.
  8793. This object allows an asynchronous callback function to be triggered, for
  8794. tasks such as coalescing multiple updates into a single callback later on.
  8795. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  8796. message thread calling handleAsyncUpdate() as soon as it can.
  8797. */
  8798. class JUCE_API AsyncUpdater
  8799. {
  8800. public:
  8801. /** Creates an AsyncUpdater object. */
  8802. AsyncUpdater() throw();
  8803. /** Destructor.
  8804. If there are any pending callbacks when the object is deleted, these are lost.
  8805. */
  8806. virtual ~AsyncUpdater();
  8807. /** Causes the callback to be triggered at a later time.
  8808. This method returns immediately, having made sure that a callback
  8809. to the handleAsyncUpdate() method will occur as soon as possible.
  8810. If an update callback is already pending but hasn't happened yet, calls
  8811. to this method will be ignored.
  8812. It's thread-safe to call this method from any number of threads without
  8813. needing to worry about locking.
  8814. */
  8815. void triggerAsyncUpdate() throw();
  8816. /** This will stop any pending updates from happening.
  8817. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  8818. callback happens, this will cancel the handleAsyncUpdate() callback.
  8819. */
  8820. void cancelPendingUpdate() throw();
  8821. /** If an update has been triggered and is pending, this will invoke it
  8822. synchronously.
  8823. Use this as a kind of "flush" operation - if an update is pending, the
  8824. handleAsyncUpdate() method will be called immediately; if no update is
  8825. pending, then nothing will be done.
  8826. */
  8827. void handleUpdateNowIfNeeded();
  8828. /** Called back to do whatever your class needs to do.
  8829. This method is called by the message thread at the next convenient time
  8830. after the triggerAsyncUpdate() method has been called.
  8831. */
  8832. virtual void handleAsyncUpdate() = 0;
  8833. private:
  8834. class AsyncUpdaterInternal : public MessageListener
  8835. {
  8836. public:
  8837. AsyncUpdaterInternal() throw() {}
  8838. ~AsyncUpdaterInternal() {}
  8839. void handleMessage (const Message&);
  8840. AsyncUpdater* owner;
  8841. private:
  8842. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  8843. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  8844. };
  8845. AsyncUpdaterInternal internalAsyncHandler;
  8846. bool asyncMessagePending;
  8847. };
  8848. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  8849. /********* End of inlined file: juce_AsyncUpdater.h *********/
  8850. /**
  8851. Represents a shared variant value.
  8852. A Value object contains a reference to a var object, and can get and set its value.
  8853. Listeners can be attached to be told when the value is changed.
  8854. The Value class is a wrapper around a shared, reference-counted underlying data
  8855. object - this means that multiple Value objects can all refer to the same piece of
  8856. data, allowing all of them to be notified when any of them changes it.
  8857. The base class of Value contains a simple var object, but subclasses can be
  8858. created that map a Value onto any kind of underlying data, e.g.
  8859. ValueTree::getPropertyAsValue() returns a Value object that is a wrapper
  8860. for one of its properties.
  8861. */
  8862. class JUCE_API Value
  8863. {
  8864. public:
  8865. /** Creates an empty Value, containing a void var. */
  8866. Value();
  8867. /** Creates a Value that refers to the same value as another one.
  8868. Note that this doesn't make a copy of the other value - both this and the other
  8869. Value will share the same underlying value, so that when either one alters it, both
  8870. will see it change.
  8871. */
  8872. Value (const Value& other);
  8873. /** Creates a Value that is set to the specified value. */
  8874. Value (const var& initialValue);
  8875. /** Destructor. */
  8876. ~Value();
  8877. /** Returns the current value. */
  8878. const var getValue() const;
  8879. /** Returns the current value. */
  8880. operator const var() const;
  8881. /** Sets the current value.
  8882. You can also use operator= to set the value.
  8883. If there are any listeners registered, they will be notified of the
  8884. change asynchronously.
  8885. */
  8886. void setValue (const var& newValue);
  8887. /** Sets the current value.
  8888. This is the same as calling setValue().
  8889. If there are any listeners registered, they will be notified of the
  8890. change asynchronously.
  8891. */
  8892. const Value& operator= (const var& newValue);
  8893. /** Makes this object refer to the same underlying ValueSource as another one.
  8894. Once this object has been connected to another one, changing either one
  8895. will update the other.
  8896. Existing listeners will still be registered after you call this method, and
  8897. they'll continue to receive messages when the new value changes.
  8898. */
  8899. void referTo (const Value& valueToReferTo);
  8900. /** Returns true if this value and the other one are references to the same value.
  8901. */
  8902. bool refersToSameSourceAs (const Value& other) const;
  8903. /** Compares two values.
  8904. This is a compare-by-value comparison, so is effectively the same as
  8905. saying (this->getValue() == other.getValue()).
  8906. */
  8907. bool operator== (const Value& other) const;
  8908. /** Compares two values.
  8909. This is a compare-by-value comparison, so is effectively the same as
  8910. saying (this->getValue() != other.getValue()).
  8911. */
  8912. bool operator!= (const Value& other) const;
  8913. /** Receives callbacks when a Value object changes.
  8914. @see Value::addListener
  8915. */
  8916. class JUCE_API Listener
  8917. {
  8918. public:
  8919. Listener() {}
  8920. virtual ~Listener() {}
  8921. /** Called when a Value object is changed.
  8922. Note that the Value object passed as a parameter may not be exactly the same
  8923. object that you registered the listener with - it might be a copy that refers
  8924. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  8925. */
  8926. virtual void valueChanged (Value& value) = 0;
  8927. };
  8928. /** Adds a listener to receive callbacks when the value changes.
  8929. The listener is added to this specific Value object, and not to the shared
  8930. object that it refers to. When this object is deleted, all the listeners will
  8931. be lost, even if other references to the same Value still exist. So when you're
  8932. adding a listener, make sure that you add it to a ValueTree instance that will last
  8933. for as long as you need the listener. In general, you'd never want to add a listener
  8934. to a local stack-based ValueTree, but more likely to one that's a member variable.
  8935. @see removeListener
  8936. */
  8937. void addListener (Listener* const listener);
  8938. /** Removes a listener that was previously added with addListener(). */
  8939. void removeListener (Listener* const listener);
  8940. /**
  8941. Used internally by the Value class as the base class for its shared value objects.
  8942. The Value class is essentially a reference-counted pointer to a shared instance
  8943. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  8944. ValueSource classes to allow Value objects to represent your own custom data items.
  8945. */
  8946. class JUCE_API ValueSource : public ReferenceCountedObject,
  8947. public AsyncUpdater
  8948. {
  8949. public:
  8950. ValueSource();
  8951. virtual ~ValueSource();
  8952. /** Returns the current value of this object. */
  8953. virtual const var getValue() const = 0;
  8954. /** Changes the current value.
  8955. This must also trigger a change message if the value actually changes.
  8956. */
  8957. virtual void setValue (const var& newValue) = 0;
  8958. /** Delivers a change message to all the listeners that are registered with
  8959. this value.
  8960. If dispatchSynchronously is true, the method will call all the listeners
  8961. before returning; otherwise it'll dispatch a message and make the call later.
  8962. */
  8963. void sendChangeMessage (const bool dispatchSynchronously);
  8964. juce_UseDebuggingNewOperator
  8965. protected:
  8966. friend class Value;
  8967. SortedSet <Value*> valuesWithListeners;
  8968. void handleAsyncUpdate();
  8969. ValueSource (const ValueSource&);
  8970. const ValueSource& operator= (const ValueSource&);
  8971. };
  8972. /** @internal */
  8973. explicit Value (ValueSource* const valueSource);
  8974. /** @internal */
  8975. ValueSource& getValueSource() { return *value; }
  8976. juce_UseDebuggingNewOperator
  8977. private:
  8978. friend class ValueSource;
  8979. ReferenceCountedObjectPtr <ValueSource> value;
  8980. SortedSet <Listener*> listeners;
  8981. void callListeners();
  8982. // This is disallowed to avoid confusion about whether it should
  8983. // do a by-value or by-reference copy.
  8984. const Value& operator= (const Value& other);
  8985. };
  8986. #endif // __JUCE_VALUE_JUCEHEADER__
  8987. /********* End of inlined file: juce_Value.h *********/
  8988. #endif
  8989. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  8990. /********* Start of inlined file: juce_ValueTree.h *********/
  8991. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  8992. #define __JUCE_VALUETREE_JUCEHEADER__
  8993. /********* Start of inlined file: juce_UndoManager.h *********/
  8994. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  8995. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  8996. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  8997. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  8998. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  8999. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  9000. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9001. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9002. /********* Start of inlined file: juce_ChangeListener.h *********/
  9003. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9004. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9005. /**
  9006. Receives callbacks about changes to some kind of object.
  9007. Many objects use a ChangeListenerList to keep a set of listeners which they
  9008. will inform when something changes. A subclass of ChangeListener
  9009. is used to receive these callbacks.
  9010. Note that the major difference between an ActionListener and a ChangeListener
  9011. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9012. callbacks, but ActionListeners perform one callback for every event posted.
  9013. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9014. */
  9015. class JUCE_API ChangeListener
  9016. {
  9017. public:
  9018. /** Destructor. */
  9019. virtual ~ChangeListener() {}
  9020. /** Overridden by your subclass to receive the callback.
  9021. @param objectThatHasChanged the value that was passed to the
  9022. ChangeListenerList::sendChangeMessage() method
  9023. */
  9024. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9025. };
  9026. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9027. /********* End of inlined file: juce_ChangeListener.h *********/
  9028. /********* Start of inlined file: juce_ScopedLock.h *********/
  9029. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9030. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9031. /**
  9032. Automatically locks and unlocks a CriticalSection object.
  9033. Use one of these as a local variable to control access to a CriticalSection.
  9034. e.g. @code
  9035. CriticalSection myCriticalSection;
  9036. for (;;)
  9037. {
  9038. const ScopedLock myScopedLock (myCriticalSection);
  9039. // myCriticalSection is now locked
  9040. ...do some stuff...
  9041. // myCriticalSection gets unlocked here.
  9042. }
  9043. @endcode
  9044. @see CriticalSection, ScopedUnlock
  9045. */
  9046. class JUCE_API ScopedLock
  9047. {
  9048. public:
  9049. /** Creates a ScopedLock.
  9050. As soon as it is created, this will lock the CriticalSection, and
  9051. when the ScopedLock object is deleted, the CriticalSection will
  9052. be unlocked.
  9053. Make sure this object is created and deleted by the same thread,
  9054. otherwise there are no guarantees what will happen! Best just to use it
  9055. as a local stack object, rather than creating one with the new() operator.
  9056. */
  9057. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9058. /** Destructor.
  9059. The CriticalSection will be unlocked when the destructor is called.
  9060. Make sure this object is created and deleted by the same thread,
  9061. otherwise there are no guarantees what will happen!
  9062. */
  9063. inline ~ScopedLock() throw() { lock_.exit(); }
  9064. private:
  9065. const CriticalSection& lock_;
  9066. ScopedLock (const ScopedLock&);
  9067. const ScopedLock& operator= (const ScopedLock&);
  9068. };
  9069. /**
  9070. Automatically unlocks and re-locks a CriticalSection object.
  9071. This is the reverse of a ScopedLock object - instead of locking the critical
  9072. section for the lifetime of this object, it unlocks it.
  9073. Make sure you don't try to unlock critical sections that aren't actually locked!
  9074. e.g. @code
  9075. CriticalSection myCriticalSection;
  9076. for (;;)
  9077. {
  9078. const ScopedLock myScopedLock (myCriticalSection);
  9079. // myCriticalSection is now locked
  9080. ... do some stuff with it locked ..
  9081. while (xyz)
  9082. {
  9083. ... do some stuff with it locked ..
  9084. const ScopedUnlock unlocker (myCriticalSection);
  9085. // myCriticalSection is now unlocked for the remainder of this block,
  9086. // and re-locked at the end.
  9087. ...do some stuff with it unlocked ...
  9088. }
  9089. // myCriticalSection gets unlocked here.
  9090. }
  9091. @endcode
  9092. @see CriticalSection, ScopedLock
  9093. */
  9094. class ScopedUnlock
  9095. {
  9096. public:
  9097. /** Creates a ScopedUnlock.
  9098. As soon as it is created, this will unlock the CriticalSection, and
  9099. when the ScopedLock object is deleted, the CriticalSection will
  9100. be re-locked.
  9101. Make sure this object is created and deleted by the same thread,
  9102. otherwise there are no guarantees what will happen! Best just to use it
  9103. as a local stack object, rather than creating one with the new() operator.
  9104. */
  9105. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9106. /** Destructor.
  9107. The CriticalSection will be unlocked when the destructor is called.
  9108. Make sure this object is created and deleted by the same thread,
  9109. otherwise there are no guarantees what will happen!
  9110. */
  9111. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9112. private:
  9113. const CriticalSection& lock_;
  9114. ScopedUnlock (const ScopedLock&);
  9115. const ScopedUnlock& operator= (const ScopedUnlock&);
  9116. };
  9117. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9118. /********* End of inlined file: juce_ScopedLock.h *********/
  9119. /**
  9120. A set of ChangeListeners.
  9121. Listeners can be added and removed from the list, and change messages can be
  9122. broadcast to all the listeners.
  9123. @see ChangeListener, ChangeBroadcaster
  9124. */
  9125. class JUCE_API ChangeListenerList : public MessageListener
  9126. {
  9127. public:
  9128. /** Creates an empty list. */
  9129. ChangeListenerList() throw();
  9130. /** Destructor. */
  9131. ~ChangeListenerList() throw();
  9132. /** Adds a listener to the list.
  9133. (Trying to add a listener that's already on the list will have no effect).
  9134. */
  9135. void addChangeListener (ChangeListener* const listener) throw();
  9136. /** Removes a listener from the list.
  9137. If the listener isn't on the list, this won't have any effect.
  9138. */
  9139. void removeChangeListener (ChangeListener* const listener) throw();
  9140. /** Removes all listeners from the list. */
  9141. void removeAllChangeListeners() throw();
  9142. /** Posts an asynchronous change message to all the listeners.
  9143. If a message has already been sent and hasn't yet been delivered, this
  9144. method won't send another - in this way it coalesces multiple frequent
  9145. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9146. with the ActionListener, which posts a new event for every call to its
  9147. sendActionMessage() method.
  9148. Only listeners which are on the list when the change event is delivered
  9149. will receive the event - and this may include listeners that weren't on
  9150. the list when the change message was sent.
  9151. @param objectThatHasChanged this pointer is passed to the
  9152. ChangeListener::changeListenerCallback() method,
  9153. and can be any value the application needs
  9154. @see sendSynchronousChangeMessage
  9155. */
  9156. void sendChangeMessage (void* objectThatHasChanged) throw();
  9157. /** This will synchronously callback all the ChangeListeners.
  9158. Use this if you need to synchronously force a call to all the
  9159. listeners' ChangeListener::changeListenerCallback() methods.
  9160. */
  9161. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9162. /** If a change message has been sent but not yet dispatched, this will
  9163. use sendSynchronousChangeMessage() to make the callback immediately.
  9164. */
  9165. void dispatchPendingMessages();
  9166. /** @internal */
  9167. void handleMessage (const Message&);
  9168. juce_UseDebuggingNewOperator
  9169. private:
  9170. SortedSet <void*> listeners;
  9171. CriticalSection lock;
  9172. void* lastChangedObject;
  9173. bool messagePending;
  9174. ChangeListenerList (const ChangeListenerList&);
  9175. const ChangeListenerList& operator= (const ChangeListenerList&);
  9176. };
  9177. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9178. /********* End of inlined file: juce_ChangeListenerList.h *********/
  9179. /** Manages a list of ChangeListeners, and can send them messages.
  9180. To quickly add methods to your class that can add/remove change
  9181. listeners and broadcast to them, you can derive from this.
  9182. @see ChangeListenerList, ChangeListener
  9183. */
  9184. class JUCE_API ChangeBroadcaster
  9185. {
  9186. public:
  9187. /** Creates an ChangeBroadcaster. */
  9188. ChangeBroadcaster() throw();
  9189. /** Destructor. */
  9190. virtual ~ChangeBroadcaster();
  9191. /** Adds a listener to the list.
  9192. (Trying to add a listener that's already on the list will have no effect).
  9193. */
  9194. void addChangeListener (ChangeListener* const listener) throw();
  9195. /** Removes a listener from the list.
  9196. If the listener isn't on the list, this won't have any effect.
  9197. */
  9198. void removeChangeListener (ChangeListener* const listener) throw();
  9199. /** Removes all listeners from the list. */
  9200. void removeAllChangeListeners() throw();
  9201. /** Broadcasts a change message to all the registered listeners.
  9202. The message will be delivered asynchronously by the event thread, so this
  9203. method will not directly call any of the listeners. For a synchronous
  9204. message, use sendSynchronousChangeMessage().
  9205. @see ChangeListenerList::sendActionMessage
  9206. */
  9207. void sendChangeMessage (void* objectThatHasChanged) throw();
  9208. /** Sends a synchronous change message to all the registered listeners.
  9209. @see ChangeListenerList::sendSynchronousChangeMessage
  9210. */
  9211. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9212. /** If a change message has been sent but not yet dispatched, this will
  9213. use sendSynchronousChangeMessage() to make the callback immediately.
  9214. */
  9215. void dispatchPendingMessages();
  9216. private:
  9217. ChangeListenerList changeListenerList;
  9218. ChangeBroadcaster (const ChangeBroadcaster&);
  9219. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9220. };
  9221. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9222. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  9223. /********* Start of inlined file: juce_UndoableAction.h *********/
  9224. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9225. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9226. /**
  9227. Used by the UndoManager class to store an action which can be done
  9228. and undone.
  9229. @see UndoManager
  9230. */
  9231. class JUCE_API UndoableAction
  9232. {
  9233. protected:
  9234. /** Creates an action. */
  9235. UndoableAction() throw() {}
  9236. public:
  9237. /** Destructor. */
  9238. virtual ~UndoableAction() {}
  9239. /** Overridden by a subclass to perform the action.
  9240. This method is called by the UndoManager, and shouldn't be used directly by
  9241. applications.
  9242. Be careful not to make any calls in a perform() method that could call
  9243. recursively back into the UndoManager::perform() method
  9244. @returns true if the action could be performed.
  9245. @see UndoManager::perform
  9246. */
  9247. virtual bool perform() = 0;
  9248. /** Overridden by a subclass to undo the action.
  9249. This method is called by the UndoManager, and shouldn't be used directly by
  9250. applications.
  9251. Be careful not to make any calls in an undo() method that could call
  9252. recursively back into the UndoManager::perform() method
  9253. @returns true if the action could be undone without any errors.
  9254. @see UndoManager::perform
  9255. */
  9256. virtual bool undo() = 0;
  9257. /** Returns a value to indicate how much memory this object takes up.
  9258. Because the UndoManager keeps a list of UndoableActions, this is used
  9259. to work out how much space each one will take up, so that the UndoManager
  9260. can work out how many to keep.
  9261. The default value returned here is 10 - units are arbitrary and
  9262. don't have to be accurate.
  9263. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9264. UndoManager::setMaxNumberOfStoredUnits
  9265. */
  9266. virtual int getSizeInUnits() { return 10; }
  9267. };
  9268. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9269. /********* End of inlined file: juce_UndoableAction.h *********/
  9270. /**
  9271. Manages a list of undo/redo commands.
  9272. An UndoManager object keeps a list of past actions and can use these actions
  9273. to move backwards and forwards through an undo history.
  9274. To use it, create subclasses of UndoableAction which perform all the
  9275. actions you need, then when you need to actually perform an action, create one
  9276. and pass it to the UndoManager's perform() method.
  9277. The manager also uses the concept of 'transactions' to group the actions
  9278. together - all actions performed between calls to beginNewTransaction() are
  9279. grouped together and are all undone/redone as a group.
  9280. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9281. when actions are performed or undone.
  9282. @see UndoableAction
  9283. */
  9284. class JUCE_API UndoManager : public ChangeBroadcaster
  9285. {
  9286. public:
  9287. /** Creates an UndoManager.
  9288. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9289. to indicate how much storage it takes up
  9290. (UndoableAction::getSizeInUnits()), so this
  9291. lets you specify the maximum total number of
  9292. units that the undomanager is allowed to
  9293. keep in memory before letting the older actions
  9294. drop off the end of the list.
  9295. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9296. that will be kept, even if this involves exceeding
  9297. the amount of space specified in maxNumberOfUnitsToKeep
  9298. */
  9299. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  9300. const int minimumTransactionsToKeep = 30);
  9301. /** Destructor. */
  9302. ~UndoManager();
  9303. /** Deletes all stored actions in the list. */
  9304. void clearUndoHistory();
  9305. /** Returns the current amount of space to use for storing UndoableAction objects.
  9306. @see setMaxNumberOfStoredUnits
  9307. */
  9308. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9309. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9310. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9311. to indicate how much storage it takes up
  9312. (UndoableAction::getSizeInUnits()), so this
  9313. lets you specify the maximum total number of
  9314. units that the undomanager is allowed to
  9315. keep in memory before letting the older actions
  9316. drop off the end of the list.
  9317. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9318. that will be kept, even if this involves exceeding
  9319. the amount of space specified in maxNumberOfUnitsToKeep
  9320. @see getNumberOfUnitsTakenUpByStoredCommands
  9321. */
  9322. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  9323. const int minimumTransactionsToKeep);
  9324. /** Performs an action and adds it to the undo history list.
  9325. @param action the action to perform - this will be deleted by the UndoManager
  9326. when no longer needed
  9327. @param actionName if this string is non-empty, the current transaction will be
  9328. given this name; if it's empty, the current transaction name will
  9329. be left unchanged. See setCurrentTransactionName()
  9330. @returns true if the command succeeds - see UndoableAction::perform
  9331. @see beginNewTransaction
  9332. */
  9333. bool perform (UndoableAction* const action,
  9334. const String& actionName = String::empty);
  9335. /** Starts a new group of actions that together will be treated as a single transaction.
  9336. All actions that are passed to the perform() method between calls to this
  9337. method are grouped together and undone/redone together by a single call to
  9338. undo() or redo().
  9339. @param actionName a description of the transaction that is about to be
  9340. performed
  9341. */
  9342. void beginNewTransaction (const String& actionName = String::empty);
  9343. /** Changes the name stored for the current transaction.
  9344. Each transaction is given a name when the beginNewTransaction() method is
  9345. called, but this can be used to change that name without starting a new
  9346. transaction.
  9347. */
  9348. void setCurrentTransactionName (const String& newName);
  9349. /** Returns true if there's at least one action in the list to undo.
  9350. @see getUndoDescription, undo, canRedo
  9351. */
  9352. bool canUndo() const;
  9353. /** Returns the description of the transaction that would be next to get undone.
  9354. The description returned is the one that was passed into beginNewTransaction
  9355. before the set of actions was performed.
  9356. @see undo
  9357. */
  9358. const String getUndoDescription() const;
  9359. /** Tries to roll-back the last transaction.
  9360. @returns true if the transaction can be undone, and false if it fails, or
  9361. if there aren't any transactions to undo
  9362. */
  9363. bool undo();
  9364. /** Tries to roll-back any actions that were added to the current transaction.
  9365. This will perform an undo() only if there are some actions in the undo list
  9366. that were added after the last call to beginNewTransaction().
  9367. This is useful because it lets you call beginNewTransaction(), then
  9368. perform an operation which may or may not actually perform some actions, and
  9369. then call this method to get rid of any actions that might have been done
  9370. without it rolling back the previous transaction if nothing was actually
  9371. done.
  9372. @returns true if any actions were undone.
  9373. */
  9374. bool undoCurrentTransactionOnly();
  9375. /** Returns a list of the UndoableAction objects that have been performed during the
  9376. transaction that is currently open.
  9377. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9378. were to be called now.
  9379. The first item in the list is the earliest action performed.
  9380. */
  9381. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9382. /** Returns true if there's at least one action in the list to redo.
  9383. @see getRedoDescription, redo, canUndo
  9384. */
  9385. bool canRedo() const;
  9386. /** Returns the description of the transaction that would be next to get redone.
  9387. The description returned is the one that was passed into beginNewTransaction
  9388. before the set of actions was performed.
  9389. @see redo
  9390. */
  9391. const String getRedoDescription() const;
  9392. /** Tries to redo the last transaction that was undone.
  9393. @returns true if the transaction can be redone, and false if it fails, or
  9394. if there aren't any transactions to redo
  9395. */
  9396. bool redo();
  9397. juce_UseDebuggingNewOperator
  9398. private:
  9399. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9400. StringArray transactionNames;
  9401. String currentTransactionName;
  9402. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9403. bool newTransaction, reentrancyCheck;
  9404. // disallow copy constructor
  9405. UndoManager (const UndoManager&);
  9406. const UndoManager& operator= (const UndoManager&);
  9407. };
  9408. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  9409. /********* End of inlined file: juce_UndoManager.h *********/
  9410. /**
  9411. A powerful tree structure that can be used to hold free-form data, and which can
  9412. handle its own undo and redo behaviour.
  9413. A ValueTree contains a list of named properties as var objects, and also holds
  9414. any number of sub-trees.
  9415. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  9416. they're simply a lightweight reference to a shared data container. Creating a copy
  9417. of another ValueTree simply creates a new reference to the same underlying object - to
  9418. make a separate, deep copy of a tree you should explicitly call createCopy().
  9419. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  9420. and much of the structure of a ValueTree is similar to an XmlElement tree.
  9421. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  9422. contain text elements, the conversion works well and makes a good serialisation
  9423. format. They can also be serialised to a binary format, which is very fast and compact.
  9424. All the methods that change data take an optional UndoManager, which will be used
  9425. to track any changes to the object. For this to work, you have to be careful to
  9426. consistently always use the same UndoManager for all operations to any node inside
  9427. the tree.
  9428. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  9429. one tree to another, be careful to always remove it first, before adding it. This
  9430. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  9431. assertions if you try to do anything dangerous, but there are still plenty of ways it
  9432. could go wrong.
  9433. Listeners can be added to a ValueTree to be told when properies change and when
  9434. nodes are added or removed.
  9435. @see var, XmlElement
  9436. */
  9437. class JUCE_API ValueTree
  9438. {
  9439. public:
  9440. /** Creates an empty ValueTree with the given type name.
  9441. Like an XmlElement, each ValueTree node has a type, which you can access with
  9442. getType() and hasType().
  9443. */
  9444. ValueTree (const String& type);
  9445. /** Creates a reference to another ValueTree. */
  9446. ValueTree (const ValueTree& other);
  9447. /** Makes this object reference another node. */
  9448. const ValueTree& operator= (const ValueTree& other);
  9449. /** Destructor. */
  9450. ~ValueTree();
  9451. /** Returns true if both this and the other tree node refer to the same underlying structure.
  9452. Note that this isn't a value comparison - two independently-created trees which
  9453. contain identical data are not considered equal.
  9454. */
  9455. bool operator== (const ValueTree& other) const;
  9456. /** Returns true if this and the other node refer to different underlying structures.
  9457. Note that this isn't a value comparison - two independently-created trees which
  9458. contain identical data are not considered equal.
  9459. */
  9460. bool operator!= (const ValueTree& other) const;
  9461. /** Returns true if this node refers to some valid data.
  9462. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  9463. call to getChild().
  9464. */
  9465. bool isValid() const { return object != 0; }
  9466. /** Returns a deep copy of this tree and all its sub-nodes. */
  9467. ValueTree createCopy() const;
  9468. /** Returns the type of this node.
  9469. The type is specified when the ValueTree is created.
  9470. @see hasType
  9471. */
  9472. const String getType() const;
  9473. /** Returns true if the node has this type.
  9474. The comparison is case-sensitive.
  9475. */
  9476. bool hasType (const String& typeName) const;
  9477. /** Returns the value of a named property.
  9478. If no such property has been set, this will return a void variant.
  9479. You can also use operator[] to get a property.
  9480. @see var, setProperty, hasProperty
  9481. */
  9482. const var getProperty (const var::identifier& name) const;
  9483. /** Returns the value of a named property.
  9484. If no such property has been set, this will return a void variant. This is the same as
  9485. calling getProperty().
  9486. @see getProperty
  9487. */
  9488. const var operator[] (const var::identifier& name) const;
  9489. /** Changes a named property of the node.
  9490. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9491. so that this change can be undone.
  9492. @see var, getProperty, removeProperty
  9493. */
  9494. void setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager);
  9495. /** Returns true if the node contains a named property. */
  9496. bool hasProperty (const var::identifier& name) const;
  9497. /** Removes a property from the node.
  9498. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9499. so that this change can be undone.
  9500. */
  9501. void removeProperty (const var::identifier& name, UndoManager* const undoManager);
  9502. /** Removes all properties from the node.
  9503. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9504. so that this change can be undone.
  9505. */
  9506. void removeAllProperties (UndoManager* const undoManager);
  9507. /** Returns the total number of properties that the node contains.
  9508. @see getProperty.
  9509. */
  9510. int getNumProperties() const;
  9511. /** Returns the identifier of the property with a given index.
  9512. @see getNumProperties
  9513. */
  9514. const var::identifier getPropertyName (int index) const;
  9515. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  9516. The Value object will maintain a reference to this tree, and will use the undo manager when
  9517. it needs to change the value. Attaching a Value::Listener to the value object will provide
  9518. callbacks whenever the property changes.
  9519. */
  9520. Value getPropertyAsValue (const var::identifier& name, UndoManager* const undoManager) const;
  9521. /** Returns the number of child nodes belonging to this one.
  9522. @see getChild
  9523. */
  9524. int getNumChildren() const;
  9525. /** Returns one of this node's child nodes.
  9526. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  9527. whether a node is valid).
  9528. */
  9529. ValueTree getChild (int index) const;
  9530. /** Looks for a child node with the speficied type name.
  9531. If no such node is found, it'll return an invalid node. (See isValid() to find out
  9532. whether a node is valid).
  9533. */
  9534. ValueTree getChildWithName (const String& type) const;
  9535. /** Looks for the first child node that has the speficied property value.
  9536. This will scan the child nodes in order, until it finds one that has property that matches
  9537. the specified value.
  9538. If no such node is found, it'll return an invalid node. (See isValid() to find out
  9539. whether a node is valid).
  9540. */
  9541. ValueTree getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const;
  9542. /** Adds a child to this node.
  9543. Make sure that the child is removed from any former parent node before calling this, or
  9544. you'll hit an assertion.
  9545. If the index is < 0 or greater than the current number of child nodes, the new node will
  9546. be added at the end of the list.
  9547. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9548. so that this change can be undone.
  9549. */
  9550. void addChild (ValueTree child, int index, UndoManager* const undoManager);
  9551. /** Removes the specified child from this node's child-list.
  9552. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9553. so that this change can be undone.
  9554. */
  9555. void removeChild (ValueTree& child, UndoManager* const undoManager);
  9556. /** Removes a child from this node's child-list.
  9557. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9558. so that this change can be undone.
  9559. */
  9560. void removeChild (const int childIndex, UndoManager* const undoManager);
  9561. /** Removes all child-nodes from this node.
  9562. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9563. so that this change can be undone.
  9564. */
  9565. void removeAllChildren (UndoManager* const undoManager);
  9566. /** Returns true if this node is anywhere below the specified parent node.
  9567. This returns true if the node is a child-of-a-child, as well as a direct child.
  9568. */
  9569. bool isAChildOf (const ValueTree& possibleParent) const;
  9570. /** Returns the parent node that contains this one.
  9571. If the node has no parent, this will return an invalid node. (See isValid() to find out
  9572. whether a node is valid).
  9573. */
  9574. ValueTree getParent() const;
  9575. /** Creates an XmlElement that holds a complete image of this node and all its children.
  9576. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  9577. be used to recreate a similar node by calling fromXml()
  9578. @see fromXml
  9579. */
  9580. XmlElement* createXml() const;
  9581. /** Tries to recreate a node from its XML representation.
  9582. This isn't designed to cope with random XML data - for a sensible result, it should only
  9583. be fed XML that was created by the createXml() method.
  9584. */
  9585. static ValueTree fromXml (const XmlElement& xml);
  9586. /** Stores this tree (and all its children) in a binary format.
  9587. Once written, the data can be read back with readFromStream().
  9588. It's much faster to load/save your tree in binary form than as XML, but
  9589. obviously isn't human-readable.
  9590. */
  9591. void writeToStream (OutputStream& output);
  9592. /** Reloads a tree from a stream that was written with writeToStream().
  9593. */
  9594. static ValueTree readFromStream (InputStream& input);
  9595. /** Listener class for events that happen to a ValueTree.
  9596. To get events from a ValueTree, make your class implement this interface, and use
  9597. ValueTree::addListener() and ValueTree::removeListener() to register it.
  9598. */
  9599. class JUCE_API Listener
  9600. {
  9601. public:
  9602. /** Destructor. */
  9603. virtual ~Listener() {}
  9604. /** This method is called when one of the properties of this node has been changed. */
  9605. virtual void valueTreePropertyChanged (ValueTree& tree, const var::identifier& property) = 0;
  9606. /** This method is called when one or more of the children of this node have been added or removed. */
  9607. virtual void valueTreeChildrenChanged (ValueTree& tree) = 0;
  9608. /** This method is called when this node has been added or removed from a parent node. */
  9609. virtual void valueTreeParentChanged (ValueTree& tree) = 0;
  9610. };
  9611. /** Adds a listener to receive callbacks when this node is changed.
  9612. The listener is added to this specific ValueTree object, and not to the shared
  9613. object that it refers to. When this object is deleted, all the listeners will
  9614. be lost, even if other references to the same ValueTree still exist. And if you
  9615. use the operator= to make this refer to a different ValueTree, any listeners will
  9616. begin listening to changes to the new tree instead of the old one.
  9617. When you're adding a listener, make sure that you add it to a ValueTree instance that
  9618. will last for as long as you need the listener. In general, you'd never want to add a
  9619. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  9620. @see removeListener
  9621. */
  9622. void addListener (Listener* listener);
  9623. /** Removes a listener that was previously added with addListener(). */
  9624. void removeListener (Listener* listener);
  9625. juce_UseDebuggingNewOperator
  9626. private:
  9627. friend class ValueTreeSetPropertyAction;
  9628. friend class ValueTreeChildChangeAction;
  9629. class JUCE_API SharedObject : public ReferenceCountedObject
  9630. {
  9631. public:
  9632. SharedObject (const String& type);
  9633. SharedObject (const SharedObject& other);
  9634. ~SharedObject();
  9635. struct Property
  9636. {
  9637. Property (const var::identifier& name, const var& value);
  9638. var::identifier name;
  9639. var value;
  9640. };
  9641. const String type;
  9642. OwnedArray <Property> properties;
  9643. ReferenceCountedArray <SharedObject> children;
  9644. SortedSet <ValueTree*> valueTreesWithListeners;
  9645. SharedObject* parent;
  9646. void sendPropertyChangeMessage (const var::identifier& property);
  9647. void sendChildChangeMessage();
  9648. void sendParentChangeMessage();
  9649. const var getProperty (const var::identifier& name) const;
  9650. void setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager);
  9651. bool hasProperty (const var::identifier& name) const;
  9652. void removeProperty (const var::identifier& name, UndoManager* const undoManager);
  9653. void removeAllProperties (UndoManager* const undoManager);
  9654. bool isAChildOf (const SharedObject* const possibleParent) const;
  9655. ValueTree getChildWithName (const String& type) const;
  9656. ValueTree getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const;
  9657. void addChild (SharedObject* child, int index, UndoManager* const undoManager);
  9658. void removeChild (const int childIndex, UndoManager* const undoManager);
  9659. void removeAllChildren (UndoManager* const undoManager);
  9660. XmlElement* createXml() const;
  9661. juce_UseDebuggingNewOperator
  9662. private:
  9663. const SharedObject& operator= (const SharedObject&);
  9664. };
  9665. friend class SharedObject;
  9666. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  9667. ReferenceCountedObjectPtr <SharedObject> object;
  9668. SortedSet <Listener*> listeners;
  9669. void deliverPropertyChangeMessage (const var::identifier& property);
  9670. void deliverChildChangeMessage();
  9671. void deliverParentChangeMessage();
  9672. ValueTree (SharedObject* const object_);
  9673. };
  9674. #endif // __JUCE_VALUETREE_JUCEHEADER__
  9675. /********* End of inlined file: juce_ValueTree.h *********/
  9676. #endif
  9677. #ifndef __JUCE_VARIANT_JUCEHEADER__
  9678. #endif
  9679. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9680. /********* Start of inlined file: juce_VoidArray.h *********/
  9681. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9682. #define __JUCE_VOIDARRAY_JUCEHEADER__
  9683. /**
  9684. A typedef for an Array of void*'s.
  9685. VoidArrays are used in various places throughout the library instead of
  9686. more strongly-typed arrays, to keep code-size low.
  9687. */
  9688. typedef Array <void*> VoidArray;
  9689. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  9690. /********* End of inlined file: juce_VoidArray.h *********/
  9691. #endif
  9692. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  9693. #endif
  9694. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  9695. #endif
  9696. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  9697. /********* Start of inlined file: juce_FileLogger.h *********/
  9698. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  9699. #define __JUCE_FILELOGGER_JUCEHEADER__
  9700. /**
  9701. A simple implemenation of a Logger that writes to a file.
  9702. @see Logger
  9703. */
  9704. class JUCE_API FileLogger : public Logger
  9705. {
  9706. public:
  9707. /** Creates a FileLogger for a given file.
  9708. @param fileToWriteTo the file that to use - new messages will be appended
  9709. to the file. If the file doesn't exist, it will be created,
  9710. along with any parent directories that are needed.
  9711. @param welcomeMessage when opened, the logger will write a header to the log, along
  9712. with the current date and time, and this welcome message
  9713. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  9714. but is larger than this number of bytes, then the start of the
  9715. file will be truncated to keep the size down. This prevents a log
  9716. file getting ridiculously large over time. The file will be truncated
  9717. at a new-line boundary. If this value is less than zero, no size limit
  9718. will be imposed; if it's zero, the file will always be deleted. Note that
  9719. the size is only checked once when this object is created - any logging
  9720. that is done later will be appended without any checking
  9721. */
  9722. FileLogger (const File& fileToWriteTo,
  9723. const String& welcomeMessage,
  9724. const int maxInitialFileSizeBytes = 128 * 1024);
  9725. /** Destructor. */
  9726. ~FileLogger();
  9727. void logMessage (const String& message);
  9728. /** Helper function to create a log file in the correct place for this platform.
  9729. On Windows this will return a logger with a path such as:
  9730. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  9731. On the Mac it'll create something like:
  9732. ~/Library/Logs/[logFileName]
  9733. The method might return 0 if the file can't be created for some reason.
  9734. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  9735. it's best to use the something like the name of your application here.
  9736. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  9737. call it "log.txt" because if it goes in a directory with logs
  9738. from other applications (as it will do on the Mac) then no-one
  9739. will know which one is yours!
  9740. @param welcomeMessage a message that will be written to the log when it's opened.
  9741. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  9742. */
  9743. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  9744. const String& logFileName,
  9745. const String& welcomeMessage,
  9746. const int maxInitialFileSizeBytes = 128 * 1024);
  9747. juce_UseDebuggingNewOperator
  9748. private:
  9749. File logFile;
  9750. CriticalSection logLock;
  9751. ScopedPointer <FileOutputStream> logStream;
  9752. void trimFileSize (int maxFileSizeBytes) const;
  9753. FileLogger (const FileLogger&);
  9754. const FileLogger& operator= (const FileLogger&);
  9755. };
  9756. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  9757. /********* End of inlined file: juce_FileLogger.h *********/
  9758. #endif
  9759. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  9760. /********* Start of inlined file: juce_Initialisation.h *********/
  9761. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  9762. #define __JUCE_INITIALISATION_JUCEHEADER__
  9763. /** Initialises Juce's GUI classes.
  9764. If you're embedding Juce into an application that uses its own event-loop rather
  9765. than using the START_JUCE_APPLICATION macro, call this function before making any
  9766. Juce calls, to make sure things are initialised correctly.
  9767. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  9768. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  9769. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  9770. */
  9771. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  9772. /** Clears up any static data being used by Juce's GUI classes.
  9773. If you're embedding Juce into an application that uses its own event-loop rather
  9774. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  9775. code to clean up any juce objects that might be lying around.
  9776. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  9777. */
  9778. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  9779. /** Initialises the core parts of Juce.
  9780. If you're embedding Juce into either a command-line program, call this function
  9781. at the start of your main() function to make sure that Juce is initialised correctly.
  9782. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  9783. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  9784. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  9785. */
  9786. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  9787. /** Clears up any static data being used by Juce's non-gui core classes.
  9788. If you're embedding Juce into either a command-line program, call this function
  9789. at the end of your main() function if you want to make sure any Juce objects are
  9790. cleaned up correctly.
  9791. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  9792. */
  9793. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  9794. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  9795. /********* End of inlined file: juce_Initialisation.h *********/
  9796. #endif
  9797. #ifndef __JUCE_LOGGER_JUCEHEADER__
  9798. #endif
  9799. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  9800. #endif
  9801. #ifndef __JUCE_MEMORY_JUCEHEADER__
  9802. #endif
  9803. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9804. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9805. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9806. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9807. /** A timer for measuring performance of code and dumping the results to a file.
  9808. e.g. @code
  9809. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9810. for (;;)
  9811. {
  9812. pc.start();
  9813. doSomethingFishy();
  9814. pc.stop();
  9815. }
  9816. @endcode
  9817. In this example, the time of each period between calling start/stop will be
  9818. measured and averaged over 50 runs, and the results printed to a file
  9819. every 50 times round the loop.
  9820. */
  9821. class JUCE_API PerformanceCounter
  9822. {
  9823. public:
  9824. /** Creates a PerformanceCounter object.
  9825. @param counterName the name used when printing out the statistics
  9826. @param runsPerPrintout the number of start/stop iterations before calling
  9827. printStatistics()
  9828. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9829. the results are just written to the debugger output
  9830. */
  9831. PerformanceCounter (const String& counterName,
  9832. int runsPerPrintout = 100,
  9833. const File& loggingFile = File::nonexistent);
  9834. /** Destructor. */
  9835. ~PerformanceCounter();
  9836. /** Starts timing.
  9837. @see stop
  9838. */
  9839. void start();
  9840. /** Stops timing and prints out the results.
  9841. The number of iterations before doing a printout of the
  9842. results is set in the constructor.
  9843. @see start
  9844. */
  9845. void stop();
  9846. /** Dumps the current metrics to the debugger output and to a file.
  9847. As well as using Logger::outputDebugString to print the results,
  9848. this will write then to the file specified in the constructor (if
  9849. this was valid).
  9850. */
  9851. void printStatistics();
  9852. juce_UseDebuggingNewOperator
  9853. private:
  9854. String name;
  9855. int numRuns, runsPerPrint;
  9856. double totalTime;
  9857. int64 started;
  9858. File outputFile;
  9859. };
  9860. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9861. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9862. #endif
  9863. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  9864. #endif
  9865. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9866. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9867. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9868. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9869. /**
  9870. A collection of miscellaneous platform-specific utilities.
  9871. */
  9872. class JUCE_API PlatformUtilities
  9873. {
  9874. public:
  9875. /** Plays the operating system's default alert 'beep' sound. */
  9876. static void beep();
  9877. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9878. const String& emailSubject,
  9879. const String& bodyText,
  9880. const StringArray& filesToAttach);
  9881. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  9882. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9883. static const String cfStringToJuceString (CFStringRef cfString);
  9884. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9885. static CFStringRef juceStringToCFString (const String& s);
  9886. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9887. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9888. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9889. static const String makePathFromFSRef (FSRef* file);
  9890. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9891. their precomposed equivalents.
  9892. */
  9893. static const String convertToPrecomposedUnicode (const String& s);
  9894. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9895. static OSType getTypeOfFile (const String& filename);
  9896. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9897. static bool isBundle (const String& filename);
  9898. /** MAC ONLY - Adds an item to the dock */
  9899. static void addItemToDock (const File& file);
  9900. /** MAC ONLY - Returns the current OS version number.
  9901. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  9902. */
  9903. static int getOSXMinorVersionNumber();
  9904. #endif
  9905. #if JUCE_WINDOWS || DOXYGEN
  9906. // Some registry helper functions:
  9907. /** WIN32 ONLY - Returns a string from the registry.
  9908. The path is a string for the entire path of a value in the registry,
  9909. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9910. */
  9911. static const String getRegistryValue (const String& regValuePath,
  9912. const String& defaultValue = String::empty);
  9913. /** WIN32 ONLY - Sets a registry value as a string.
  9914. This will take care of creating any groups needed to get to the given
  9915. registry value.
  9916. */
  9917. static void setRegistryValue (const String& regValuePath,
  9918. const String& value);
  9919. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9920. static bool registryValueExists (const String& regValuePath);
  9921. /** WIN32 ONLY - Deletes a registry value. */
  9922. static void deleteRegistryValue (const String& regValuePath);
  9923. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9924. static void deleteRegistryKey (const String& regKeyPath);
  9925. /** WIN32 ONLY - Creates a file association in the registry.
  9926. This lets you set the exe that should be launched by a given file extension.
  9927. @param fileExtension the file extension to associate, including the
  9928. initial dot, e.g. ".txt"
  9929. @param symbolicDescription a space-free short token to identify the file type
  9930. @param fullDescription a human-readable description of the file type
  9931. @param targetExecutable the executable that should be launched
  9932. @param iconResourceNumber the icon that gets displayed for the file type will be
  9933. found by looking up this resource number in the
  9934. executable. Pass 0 here to not use an icon
  9935. */
  9936. static void registerFileAssociation (const String& fileExtension,
  9937. const String& symbolicDescription,
  9938. const String& fullDescription,
  9939. const File& targetExecutable,
  9940. int iconResourceNumber);
  9941. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9942. In a normal Juce application this will be set to the module handle
  9943. of the application executable.
  9944. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9945. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9946. to set the correct module handle in your DllMain() function, because
  9947. the win32 system relies on the correct instance handle when opening windows.
  9948. */
  9949. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9950. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9951. @see getCurrentModuleInstanceHandle()
  9952. */
  9953. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  9954. /** WIN32 ONLY - Gets the command-line params as a string.
  9955. This is needed to avoid unicode problems with the argc type params.
  9956. */
  9957. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  9958. #endif
  9959. /** Clears the floating point unit's flags.
  9960. Only has an effect under win32, currently.
  9961. */
  9962. static void fpuReset();
  9963. #if JUCE_LINUX || JUCE_WINDOWS
  9964. /** Loads a dynamically-linked library into the process's address space.
  9965. @param pathOrFilename the platform-dependent name and search path
  9966. @returns a handle which can be used by getProcedureEntryPoint(), or
  9967. zero if it fails.
  9968. @see freeDynamicLibrary, getProcedureEntryPoint
  9969. */
  9970. static void* loadDynamicLibrary (const String& pathOrFilename);
  9971. /** Frees a dynamically-linked library.
  9972. @param libraryHandle a handle created by loadDynamicLibrary
  9973. @see loadDynamicLibrary, getProcedureEntryPoint
  9974. */
  9975. static void freeDynamicLibrary (void* libraryHandle);
  9976. /** Finds a procedure call in a dynamically-linked library.
  9977. @param libraryHandle a library handle returned by loadDynamicLibrary
  9978. @param procedureName the name of the procedure call to try to load
  9979. @returns a pointer to the function if found, or 0 if it fails
  9980. @see loadDynamicLibrary
  9981. */
  9982. static void* getProcedureEntryPoint (void* libraryHandle,
  9983. const String& procedureName);
  9984. #endif
  9985. #if JUCE_LINUX || DOXYGEN
  9986. #endif
  9987. };
  9988. #if JUCE_MAC || JUCE_IPHONE
  9989. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  9990. using RAII.
  9991. */
  9992. class ScopedAutoReleasePool
  9993. {
  9994. public:
  9995. ScopedAutoReleasePool();
  9996. ~ScopedAutoReleasePool();
  9997. private:
  9998. void* pool;
  9999. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10000. const ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10001. };
  10002. #endif
  10003. #if JUCE_MAC
  10004. /**
  10005. A wrapper class for picking up events from an Apple IR remote control device.
  10006. To use it, just create a subclass of this class, implementing the buttonPressed()
  10007. callback, then call start() and stop() to start or stop receiving events.
  10008. */
  10009. class JUCE_API AppleRemoteDevice
  10010. {
  10011. public:
  10012. AppleRemoteDevice();
  10013. virtual ~AppleRemoteDevice();
  10014. /** The set of buttons that may be pressed.
  10015. @see buttonPressed
  10016. */
  10017. enum ButtonType
  10018. {
  10019. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10020. playButton, /**< The play button. */
  10021. plusButton, /**< The plus or volume-up button. */
  10022. minusButton, /**< The minus or volume-down button. */
  10023. rightButton, /**< The right button (if it's held for a short time). */
  10024. leftButton, /**< The left button (if it's held for a short time). */
  10025. rightButton_Long, /**< The right button (if it's held for a long time). */
  10026. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10027. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10028. playButtonSleepMode,
  10029. switched
  10030. };
  10031. /** Override this method to receive the callback about a button press.
  10032. The callback will happen on the application's message thread.
  10033. Some buttons trigger matching up and down events, in which the isDown parameter
  10034. will be true and then false. Others only send a single event when the
  10035. button is pressed.
  10036. */
  10037. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10038. /** Starts the device running and responding to events.
  10039. Returns true if it managed to open the device.
  10040. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10041. and will not be available to any other part of the system. If
  10042. false, it will be shared with other apps.
  10043. @see stop
  10044. */
  10045. bool start (const bool inExclusiveMode);
  10046. /** Stops the device running.
  10047. @see start
  10048. */
  10049. void stop();
  10050. /** Returns true if the device has been started successfully.
  10051. */
  10052. bool isActive() const;
  10053. /** Returns the ID number of the remote, if it has sent one.
  10054. */
  10055. int getRemoteId() const { return remoteId; }
  10056. juce_UseDebuggingNewOperator
  10057. /** @internal */
  10058. void handleCallbackInternal();
  10059. private:
  10060. void* device;
  10061. void* queue;
  10062. int remoteId;
  10063. bool open (const bool openInExclusiveMode);
  10064. AppleRemoteDevice (const AppleRemoteDevice&);
  10065. const AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10066. };
  10067. #endif
  10068. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10069. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10070. #endif
  10071. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10072. /********* Start of inlined file: juce_Random.h *********/
  10073. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10074. #define __JUCE_RANDOM_JUCEHEADER__
  10075. /**
  10076. A simple pseudo-random number generator.
  10077. */
  10078. class JUCE_API Random
  10079. {
  10080. public:
  10081. /** Creates a Random object based on a seed value.
  10082. For a given seed value, the subsequent numbers generated by this object
  10083. will be predictable, so a good idea is to set this value based
  10084. on the time, e.g.
  10085. new Random (Time::currentTimeMillis())
  10086. */
  10087. Random (const int64 seedValue) throw();
  10088. /** Destructor. */
  10089. ~Random() throw();
  10090. /** Returns the next random 32 bit integer.
  10091. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10092. */
  10093. int nextInt() throw();
  10094. /** Returns the next random number, limited to a given range.
  10095. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10096. */
  10097. int nextInt (const int maxValue) throw();
  10098. /** Returns the next 64-bit random number.
  10099. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10100. */
  10101. int64 nextInt64() throw();
  10102. /** Returns the next random floating-point number.
  10103. @returns a random value in the range 0 to 1.0
  10104. */
  10105. float nextFloat() throw();
  10106. /** Returns the next random floating-point number.
  10107. @returns a random value in the range 0 to 1.0
  10108. */
  10109. double nextDouble() throw();
  10110. /** Returns the next random boolean value.
  10111. */
  10112. bool nextBool() throw();
  10113. /** Returns a BitArray containing a random number.
  10114. @returns a random value in the range 0 to (maximumValue - 1).
  10115. */
  10116. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  10117. /** Sets a range of bits in a BitArray to random values. */
  10118. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  10119. /** To avoid the overhead of having to create a new Random object whenever
  10120. you need a number, this is a shared application-wide object that
  10121. can be used.
  10122. It's not thread-safe though, so threads should use their own Random object.
  10123. */
  10124. static Random& getSystemRandom() throw();
  10125. /** Resets this Random object to a given seed value. */
  10126. void setSeed (const int64 newSeed) throw();
  10127. /** Reseeds this generator using a value generated from various semi-random system
  10128. properties like the current time, etc.
  10129. Because this function convolves the time with the last seed value, calling
  10130. it repeatedly will increase the randomness of the final result.
  10131. */
  10132. void setSeedRandomly();
  10133. juce_UseDebuggingNewOperator
  10134. private:
  10135. int64 seed;
  10136. };
  10137. #endif // __JUCE_RANDOM_JUCEHEADER__
  10138. /********* End of inlined file: juce_Random.h *********/
  10139. #endif
  10140. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10141. #endif
  10142. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10143. /********* Start of inlined file: juce_Singleton.h *********/
  10144. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10145. #define __JUCE_SINGLETON_JUCEHEADER__
  10146. /**
  10147. Macro to declare member variables and methods for a singleton class.
  10148. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10149. to the class's definition.
  10150. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10151. implementation code.
  10152. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10153. destructor, in case it is deleted by other means than deleteInstance()
  10154. Clients can then call the static method MyClass::getInstance() to get a pointer
  10155. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10156. no instance currently exists.
  10157. e.g. @code
  10158. class MySingleton
  10159. {
  10160. public:
  10161. MySingleton()
  10162. {
  10163. }
  10164. ~MySingleton()
  10165. {
  10166. // this ensures that no dangling pointers are left when the
  10167. // singleton is deleted.
  10168. clearSingletonInstance();
  10169. }
  10170. juce_DeclareSingleton (MySingleton, false)
  10171. };
  10172. juce_ImplementSingleton (MySingleton)
  10173. // example of usage:
  10174. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10175. ...
  10176. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10177. @endcode
  10178. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10179. than once during the process's lifetime - i.e. after you've created and deleted the
  10180. object, getInstance() will refuse to create another one. This can be useful to stop
  10181. objects being accidentally re-created during your app's shutdown code.
  10182. If you know that your object will only be created and deleted by a single thread, you
  10183. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  10184. of this one.
  10185. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  10186. */
  10187. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  10188. \
  10189. static classname* _singletonInstance; \
  10190. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  10191. \
  10192. static classname* getInstance() \
  10193. { \
  10194. if (_singletonInstance == 0) \
  10195. {\
  10196. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10197. \
  10198. if (_singletonInstance == 0) \
  10199. { \
  10200. static bool alreadyInside = false; \
  10201. static bool createdOnceAlready = false; \
  10202. \
  10203. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10204. jassert (! problem); \
  10205. if (! problem) \
  10206. { \
  10207. createdOnceAlready = true; \
  10208. alreadyInside = true; \
  10209. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10210. alreadyInside = false; \
  10211. \
  10212. _singletonInstance = newObject; \
  10213. } \
  10214. } \
  10215. } \
  10216. \
  10217. return _singletonInstance; \
  10218. } \
  10219. \
  10220. static inline classname* getInstanceWithoutCreating() throw() \
  10221. { \
  10222. return _singletonInstance; \
  10223. } \
  10224. \
  10225. static void deleteInstance() \
  10226. { \
  10227. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10228. if (_singletonInstance != 0) \
  10229. { \
  10230. classname* const old = _singletonInstance; \
  10231. _singletonInstance = 0; \
  10232. delete old; \
  10233. } \
  10234. } \
  10235. \
  10236. void clearSingletonInstance() throw() \
  10237. { \
  10238. if (_singletonInstance == this) \
  10239. _singletonInstance = 0; \
  10240. }
  10241. /** This is a counterpart to the juce_DeclareSingleton macro.
  10242. After adding the juce_DeclareSingleton to the class definition, this macro has
  10243. to be used in the cpp file.
  10244. */
  10245. #define juce_ImplementSingleton(classname) \
  10246. \
  10247. classname* classname::_singletonInstance = 0; \
  10248. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  10249. /**
  10250. Macro to declare member variables and methods for a singleton class.
  10251. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  10252. section to make access to it thread-safe. If you know that your object will
  10253. only ever be created or deleted by a single thread, then this is a
  10254. more efficient version to use.
  10255. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10256. than once during the process's lifetime - i.e. after you've created and deleted the
  10257. object, getInstance() will refuse to create another one. This can be useful to stop
  10258. objects being accidentally re-created during your app's shutdown code.
  10259. See the documentation for juce_DeclareSingleton for more information about
  10260. how to use it, the only difference being that you have to use
  10261. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10262. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  10263. */
  10264. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  10265. \
  10266. static classname* _singletonInstance; \
  10267. \
  10268. static classname* getInstance() \
  10269. { \
  10270. if (_singletonInstance == 0) \
  10271. { \
  10272. static bool alreadyInside = false; \
  10273. static bool createdOnceAlready = false; \
  10274. \
  10275. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10276. jassert (! problem); \
  10277. if (! problem) \
  10278. { \
  10279. createdOnceAlready = true; \
  10280. alreadyInside = true; \
  10281. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10282. alreadyInside = false; \
  10283. \
  10284. _singletonInstance = newObject; \
  10285. } \
  10286. } \
  10287. \
  10288. return _singletonInstance; \
  10289. } \
  10290. \
  10291. static inline classname* getInstanceWithoutCreating() throw() \
  10292. { \
  10293. return _singletonInstance; \
  10294. } \
  10295. \
  10296. static void deleteInstance() \
  10297. { \
  10298. if (_singletonInstance != 0) \
  10299. { \
  10300. classname* const old = _singletonInstance; \
  10301. _singletonInstance = 0; \
  10302. delete old; \
  10303. } \
  10304. } \
  10305. \
  10306. void clearSingletonInstance() throw() \
  10307. { \
  10308. if (_singletonInstance == this) \
  10309. _singletonInstance = 0; \
  10310. }
  10311. /**
  10312. Macro to declare member variables and methods for a singleton class.
  10313. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  10314. for recursion or repeated instantiation. It's intended for use as a lightweight
  10315. version of a singleton, where you're using it in very straightforward
  10316. circumstances and don't need the extra checking.
  10317. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  10318. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  10319. See the documentation for juce_DeclareSingleton for more information about
  10320. how to use it, the only difference being that you have to use
  10321. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10322. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  10323. */
  10324. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  10325. \
  10326. static classname* _singletonInstance; \
  10327. \
  10328. static classname* getInstance() \
  10329. { \
  10330. if (_singletonInstance == 0) \
  10331. _singletonInstance = new classname(); \
  10332. \
  10333. return _singletonInstance; \
  10334. } \
  10335. \
  10336. static inline classname* getInstanceWithoutCreating() throw() \
  10337. { \
  10338. return _singletonInstance; \
  10339. } \
  10340. \
  10341. static void deleteInstance() \
  10342. { \
  10343. if (_singletonInstance != 0) \
  10344. { \
  10345. classname* const old = _singletonInstance; \
  10346. _singletonInstance = 0; \
  10347. delete old; \
  10348. } \
  10349. } \
  10350. \
  10351. void clearSingletonInstance() throw() \
  10352. { \
  10353. if (_singletonInstance == this) \
  10354. _singletonInstance = 0; \
  10355. }
  10356. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  10357. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  10358. to the class definition, this macro has to be used somewhere in the cpp file.
  10359. */
  10360. #define juce_ImplementSingleton_SingleThreaded(classname) \
  10361. \
  10362. classname* classname::_singletonInstance = 0;
  10363. #endif // __JUCE_SINGLETON_JUCEHEADER__
  10364. /********* End of inlined file: juce_Singleton.h *********/
  10365. #endif
  10366. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  10367. #endif
  10368. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  10369. /********* Start of inlined file: juce_SystemStats.h *********/
  10370. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  10371. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  10372. /**
  10373. Contains methods for finding out about the current hardware and OS configuration.
  10374. */
  10375. class JUCE_API SystemStats
  10376. {
  10377. public:
  10378. /** Returns the current version of JUCE,
  10379. (just in case you didn't already know at compile-time.)
  10380. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  10381. */
  10382. static const String getJUCEVersion() throw();
  10383. /** The set of possible results of the getOperatingSystemType() method.
  10384. */
  10385. enum OperatingSystemType
  10386. {
  10387. UnknownOS = 0,
  10388. MacOSX = 0x1000,
  10389. Linux = 0x2000,
  10390. Win95 = 0x4001,
  10391. Win98 = 0x4002,
  10392. WinNT351 = 0x4103,
  10393. WinNT40 = 0x4104,
  10394. Win2000 = 0x4105,
  10395. WinXP = 0x4106,
  10396. WinVista = 0x4107,
  10397. Windows7 = 0x4108,
  10398. Windows = 0x4000, /**< To test whether any version of Windows is running,
  10399. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  10400. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  10401. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  10402. };
  10403. /** Returns the type of operating system we're running on.
  10404. @returns one of the values from the OperatingSystemType enum.
  10405. @see getOperatingSystemName
  10406. */
  10407. static OperatingSystemType getOperatingSystemType() throw();
  10408. /** Returns the name of the type of operating system we're running on.
  10409. @returns a string describing the OS type.
  10410. @see getOperatingSystemType
  10411. */
  10412. static const String getOperatingSystemName() throw();
  10413. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  10414. */
  10415. static bool isOperatingSystem64Bit() throw();
  10416. // CPU and memory information..
  10417. /** Returns the approximate CPU speed.
  10418. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  10419. what year you're reading this...)
  10420. */
  10421. static int getCpuSpeedInMegaherz() throw();
  10422. /** Returns a string to indicate the CPU vendor.
  10423. Might not be known on some systems.
  10424. */
  10425. static const String getCpuVendor() throw();
  10426. /** Checks whether Intel MMX instructions are available. */
  10427. static bool hasMMX() throw();
  10428. /** Checks whether Intel SSE instructions are available. */
  10429. static bool hasSSE() throw();
  10430. /** Checks whether Intel SSE2 instructions are available. */
  10431. static bool hasSSE2() throw();
  10432. /** Checks whether AMD 3DNOW instructions are available. */
  10433. static bool has3DNow() throw();
  10434. /** Returns the number of CPUs.
  10435. */
  10436. static int getNumCpus() throw();
  10437. /** Returns a clock-cycle tick counter, if available.
  10438. If the machine can do it, this will return a tick-count
  10439. where each tick is one cpu clock cycle - used for profiling
  10440. code.
  10441. @returns the tick count, or zero if not available.
  10442. */
  10443. static int64 getClockCycleCounter() throw();
  10444. /** Finds out how much RAM is in the machine.
  10445. @returns the approximate number of megabytes of memory, or zero if
  10446. something goes wrong when finding out.
  10447. */
  10448. static int getMemorySizeInMegabytes() throw();
  10449. /** Returns the system page-size.
  10450. This is only used by programmers with beards.
  10451. */
  10452. static int getPageSize() throw();
  10453. /** Returns a list of MAC addresses found on this machine.
  10454. @param addresses an array into which the MAC addresses should be copied
  10455. @param maxNum the number of elements in this array
  10456. @param littleEndian the endianness of the numbers to return. If this is true,
  10457. the least-significant byte of each number is the first byte
  10458. of the mac address. If false, the least significant byte is
  10459. the last number. Note that the default values of this parameter
  10460. are different on Mac/PC to avoid breaking old software that was
  10461. written before this parameter was added (when the two systems
  10462. defaulted to using different endiannesses). In newer
  10463. software you probably want to specify an explicit value
  10464. for this.
  10465. @returns the number of MAC addresses that were found
  10466. */
  10467. static int getMACAddresses (int64* addresses, int maxNum,
  10468. #if JUCE_MAC
  10469. const bool littleEndian = true) throw();
  10470. #else
  10471. const bool littleEndian = false) throw();
  10472. #endif
  10473. // not-for-public-use platform-specific method gets called at startup to initialise things.
  10474. static void initialiseStats() throw();
  10475. };
  10476. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  10477. /********* End of inlined file: juce_SystemStats.h *********/
  10478. #endif
  10479. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  10480. #endif
  10481. #ifndef __JUCE_TIME_JUCEHEADER__
  10482. #endif
  10483. #ifndef __JUCE_UUID_JUCEHEADER__
  10484. /********* Start of inlined file: juce_Uuid.h *********/
  10485. #ifndef __JUCE_UUID_JUCEHEADER__
  10486. #define __JUCE_UUID_JUCEHEADER__
  10487. /**
  10488. A universally unique 128-bit identifier.
  10489. This class generates very random unique numbers based on the system time
  10490. and MAC addresses if any are available. It's extremely unlikely that two identical
  10491. UUIDs would ever be created by chance.
  10492. The class includes methods for saving the ID as a string or as raw binary data.
  10493. */
  10494. class JUCE_API Uuid
  10495. {
  10496. public:
  10497. /** Creates a new unique ID. */
  10498. Uuid();
  10499. /** Destructor. */
  10500. ~Uuid() throw();
  10501. /** Creates a copy of another UUID. */
  10502. Uuid (const Uuid& other);
  10503. /** Copies another UUID. */
  10504. Uuid& operator= (const Uuid& other);
  10505. /** Returns true if the ID is zero. */
  10506. bool isNull() const throw();
  10507. /** Compares two UUIDs. */
  10508. bool operator== (const Uuid& other) const;
  10509. /** Compares two UUIDs. */
  10510. bool operator!= (const Uuid& other) const;
  10511. /** Returns a stringified version of this UUID.
  10512. A Uuid object can later be reconstructed from this string using operator= or
  10513. the constructor that takes a string parameter.
  10514. @returns a 32 character hex string.
  10515. */
  10516. const String toString() const;
  10517. /** Creates an ID from an encoded string version.
  10518. @see toString
  10519. */
  10520. Uuid (const String& uuidString);
  10521. /** Copies from a stringified UUID.
  10522. The string passed in should be one that was created with the toString() method.
  10523. */
  10524. Uuid& operator= (const String& uuidString);
  10525. /** Returns a pointer to the internal binary representation of the ID.
  10526. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10527. the constructor or operator= method that takes an array of uint8s.
  10528. */
  10529. const uint8* getRawData() const throw() { return value.asBytes; }
  10530. /** Creates a UUID from a 16-byte array.
  10531. @see getRawData
  10532. */
  10533. Uuid (const uint8* const rawData);
  10534. /** Sets this UUID from 16-bytes of raw data. */
  10535. Uuid& operator= (const uint8* const rawData);
  10536. juce_UseDebuggingNewOperator
  10537. private:
  10538. union
  10539. {
  10540. uint8 asBytes [16];
  10541. int asInt[4];
  10542. int64 asInt64[2];
  10543. } value;
  10544. };
  10545. #endif // __JUCE_UUID_JUCEHEADER__
  10546. /********* End of inlined file: juce_Uuid.h *********/
  10547. #endif
  10548. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  10549. /********* Start of inlined file: juce_BlowFish.h *********/
  10550. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  10551. #define __JUCE_BLOWFISH_JUCEHEADER__
  10552. /**
  10553. BlowFish encryption class.
  10554. */
  10555. class JUCE_API BlowFish
  10556. {
  10557. public:
  10558. /** Creates an object that can encode/decode based on the specified key.
  10559. The key data can be up to 72 bytes long.
  10560. */
  10561. BlowFish (const uint8* keyData, int keyBytes);
  10562. /** Creates a copy of another blowfish object. */
  10563. BlowFish (const BlowFish& other);
  10564. /** Copies another blowfish object. */
  10565. const BlowFish& operator= (const BlowFish& other);
  10566. /** Destructor. */
  10567. ~BlowFish();
  10568. /** Encrypts a pair of 32-bit integers. */
  10569. void encrypt (uint32& data1, uint32& data2) const;
  10570. /** Decrypts a pair of 32-bit integers. */
  10571. void decrypt (uint32& data1, uint32& data2) const;
  10572. juce_UseDebuggingNewOperator
  10573. private:
  10574. uint32 p[18];
  10575. HeapBlock <uint32> s[4];
  10576. uint32 F (uint32 x) const;
  10577. };
  10578. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  10579. /********* End of inlined file: juce_BlowFish.h *********/
  10580. #endif
  10581. #ifndef __JUCE_MD5_JUCEHEADER__
  10582. /********* Start of inlined file: juce_MD5.h *********/
  10583. #ifndef __JUCE_MD5_JUCEHEADER__
  10584. #define __JUCE_MD5_JUCEHEADER__
  10585. /**
  10586. MD5 checksum class.
  10587. Create one of these with a block of source data or a string, and it calculates the
  10588. MD5 checksum of that data.
  10589. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  10590. */
  10591. class JUCE_API MD5
  10592. {
  10593. public:
  10594. /** Creates a null MD5 object. */
  10595. MD5();
  10596. /** Creates a copy of another MD5. */
  10597. MD5 (const MD5& other);
  10598. /** Copies another MD5. */
  10599. const MD5& operator= (const MD5& other);
  10600. /** Creates a checksum for a block of binary data. */
  10601. MD5 (const MemoryBlock& data);
  10602. /** Creates a checksum for a block of binary data. */
  10603. MD5 (const char* data, const int numBytes);
  10604. /** Creates a checksum for a string.
  10605. Note that this operates on the string as a block of unicode characters, so the
  10606. result you get will differ from the value you'd get if the string was treated
  10607. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  10608. of this method with a checksum created by a different framework, which may have
  10609. used a different encoding.
  10610. */
  10611. MD5 (const String& text);
  10612. /** Creates a checksum for the input from a stream.
  10613. This will read up to the given number of bytes from the stream, and produce the
  10614. checksum of that. If the number of bytes to read is negative, it'll read
  10615. until the stream is exhausted.
  10616. */
  10617. MD5 (InputStream& input, int numBytesToRead = -1);
  10618. /** Creates a checksum for a file. */
  10619. MD5 (const File& file);
  10620. /** Destructor. */
  10621. ~MD5();
  10622. /** Returns the checksum as a 16-byte block of data. */
  10623. const MemoryBlock getRawChecksumData() const;
  10624. /** Returns the checksum as a 32-digit hex string. */
  10625. const String toHexString() const;
  10626. /** Compares this to another MD5. */
  10627. bool operator== (const MD5& other) const;
  10628. /** Compares this to another MD5. */
  10629. bool operator!= (const MD5& other) const;
  10630. juce_UseDebuggingNewOperator
  10631. private:
  10632. uint8 result [16];
  10633. struct ProcessContext
  10634. {
  10635. uint8 buffer [64];
  10636. uint32 state [4];
  10637. uint32 count [2];
  10638. ProcessContext();
  10639. void processBlock (const uint8* const data, int dataSize);
  10640. void transform (const uint8* const buffer);
  10641. void finish (uint8* const result);
  10642. };
  10643. void processStream (InputStream& input, int numBytesToRead);
  10644. };
  10645. #endif // __JUCE_MD5_JUCEHEADER__
  10646. /********* End of inlined file: juce_MD5.h *********/
  10647. #endif
  10648. #ifndef __JUCE_PRIMES_JUCEHEADER__
  10649. /********* Start of inlined file: juce_Primes.h *********/
  10650. #ifndef __JUCE_PRIMES_JUCEHEADER__
  10651. #define __JUCE_PRIMES_JUCEHEADER__
  10652. /**
  10653. Prime number creation class.
  10654. This class contains static methods for generating and testing prime numbers.
  10655. @see BitArray
  10656. */
  10657. class JUCE_API Primes
  10658. {
  10659. public:
  10660. /** Creates a random prime number with a given bit-length.
  10661. The certainty parameter specifies how many iterations to use when testing
  10662. for primality. A safe value might be anything over about 20-30.
  10663. The randomSeeds parameter lets you optionally pass it a set of values with
  10664. which to seed the random number generation, improving the security of the
  10665. keys generated.
  10666. */
  10667. static const BitArray createProbablePrime (int bitLength,
  10668. int certainty,
  10669. const int* randomSeeds = 0,
  10670. int numRandomSeeds = 0) throw();
  10671. /** Tests a number to see if it's prime.
  10672. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  10673. whether the number is prime.
  10674. The certainty parameter specifies how many iterations to use when testing - a
  10675. safe value might be anything over about 20-30.
  10676. */
  10677. static bool isProbablyPrime (const BitArray& number,
  10678. int certainty) throw();
  10679. };
  10680. #endif // __JUCE_PRIMES_JUCEHEADER__
  10681. /********* End of inlined file: juce_Primes.h *********/
  10682. #endif
  10683. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  10684. /********* Start of inlined file: juce_RSAKey.h *********/
  10685. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  10686. #define __JUCE_RSAKEY_JUCEHEADER__
  10687. /**
  10688. RSA public/private key-pair encryption class.
  10689. An object of this type makes up one half of a public/private RSA key pair. Use the
  10690. createKeyPair() method to create a matching pair for encoding/decoding.
  10691. */
  10692. class JUCE_API RSAKey
  10693. {
  10694. public:
  10695. /** Creates a null key object.
  10696. Initialise a pair of objects for use with the createKeyPair() method.
  10697. */
  10698. RSAKey() throw();
  10699. /** Loads a key from an encoded string representation.
  10700. This reloads a key from a string created by the toString() method.
  10701. */
  10702. RSAKey (const String& stringRepresentation) throw();
  10703. /** Destructor. */
  10704. ~RSAKey() throw();
  10705. /** Turns the key into a string representation.
  10706. This can be reloaded using the constructor that takes a string.
  10707. */
  10708. const String toString() const throw();
  10709. /** Encodes or decodes a value.
  10710. Call this on the public key object to encode some data, then use the matching
  10711. private key object to decode it.
  10712. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  10713. initialised correctly.
  10714. NOTE: This method dumbly applies this key to this data. If you encode some data
  10715. and then try to decode it with a key that doesn't match, this method will still
  10716. happily do its job and return true, but the result won't be what you were expecting.
  10717. It's your responsibility to check that the result is what you wanted.
  10718. */
  10719. bool applyToValue (BitArray& value) const throw();
  10720. /** Creates a public/private key-pair.
  10721. Each key will perform one-way encryption that can only be reversed by
  10722. using the other key.
  10723. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  10724. sizes are more secure, but this method will take longer to execute.
  10725. The randomSeeds parameter lets you optionally pass it a set of values with
  10726. which to seed the random number generation, improving the security of the
  10727. keys generated.
  10728. */
  10729. static void createKeyPair (RSAKey& publicKey,
  10730. RSAKey& privateKey,
  10731. const int numBits,
  10732. const int* randomSeeds = 0,
  10733. const int numRandomSeeds = 0) throw();
  10734. juce_UseDebuggingNewOperator
  10735. protected:
  10736. BitArray part1, part2;
  10737. };
  10738. #endif // __JUCE_RSAKEY_JUCEHEADER__
  10739. /********* End of inlined file: juce_RSAKey.h *********/
  10740. #endif
  10741. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10742. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  10743. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10744. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10745. /**
  10746. Searches through a the files in a directory, returning each file that is found.
  10747. A DirectoryIterator will search through a directory and its subdirectories using
  10748. a wildcard filepattern match.
  10749. If you may be finding a large number of files, this is better than
  10750. using File::findChildFiles() because it doesn't block while it finds them
  10751. all, and this is more memory-efficient.
  10752. It can also guess how far it's got using a wildly inaccurate algorithm.
  10753. */
  10754. class JUCE_API DirectoryIterator
  10755. {
  10756. public:
  10757. /** Creates a DirectoryIterator for a given directory.
  10758. After creating one of these, call its next() method to get the
  10759. first file - e.g. @code
  10760. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  10761. while (iter.next())
  10762. {
  10763. File theFileItFound (iter.getFile());
  10764. ... etc
  10765. }
  10766. @endcode
  10767. @param directory the directory to search in
  10768. @param isRecursive whether all the subdirectories should also be searched
  10769. @param wildCard the file pattern to match
  10770. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  10771. whether to look for files, directories, or both.
  10772. */
  10773. DirectoryIterator (const File& directory,
  10774. bool isRecursive,
  10775. const String& wildCard = JUCE_T("*"),
  10776. const int whatToLookFor = File::findFiles);
  10777. /** Destructor. */
  10778. ~DirectoryIterator();
  10779. /** Call this to move the iterator along to the next file.
  10780. @returns true if a file was found (you can then use getFile() to see what it was) - or
  10781. false if there are no more matching files.
  10782. */
  10783. bool next();
  10784. /** Returns the file that the iterator is currently pointing at.
  10785. The result of this call is only valid after a call to next() has returned true.
  10786. */
  10787. const File getFile() const;
  10788. /** Returns a guess of how far through the search the iterator has got.
  10789. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  10790. very accurate.
  10791. */
  10792. float getEstimatedProgress() const;
  10793. juce_UseDebuggingNewOperator
  10794. private:
  10795. OwnedArray <File> filesFound;
  10796. OwnedArray <File> dirsFound;
  10797. String wildCard;
  10798. int index;
  10799. const int whatToLookFor;
  10800. ScopedPointer <DirectoryIterator> subIterator;
  10801. DirectoryIterator (const DirectoryIterator&);
  10802. const DirectoryIterator& operator= (const DirectoryIterator&);
  10803. };
  10804. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10805. /********* End of inlined file: juce_DirectoryIterator.h *********/
  10806. #endif
  10807. #ifndef __JUCE_FILE_JUCEHEADER__
  10808. #endif
  10809. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10810. /********* Start of inlined file: juce_FileInputStream.h *********/
  10811. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10812. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10813. /**
  10814. An input stream that reads from a local file.
  10815. @see InputStream, FileOutputStream, File::createInputStream
  10816. */
  10817. class JUCE_API FileInputStream : public InputStream
  10818. {
  10819. public:
  10820. /** Creates a FileInputStream.
  10821. @param fileToRead the file to read from - if the file can't be accessed for some
  10822. reason, then the stream will just contain no data
  10823. */
  10824. FileInputStream (const File& fileToRead);
  10825. /** Destructor. */
  10826. ~FileInputStream();
  10827. const File& getFile() const throw() { return file; }
  10828. int64 getTotalLength();
  10829. int read (void* destBuffer, int maxBytesToRead);
  10830. bool isExhausted();
  10831. int64 getPosition();
  10832. bool setPosition (int64 pos);
  10833. juce_UseDebuggingNewOperator
  10834. private:
  10835. File file;
  10836. void* fileHandle;
  10837. int64 currentPosition, totalSize;
  10838. bool needToSeek;
  10839. FileInputStream (const FileInputStream&);
  10840. const FileInputStream& operator= (const FileInputStream&);
  10841. };
  10842. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10843. /********* End of inlined file: juce_FileInputStream.h *********/
  10844. #endif
  10845. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10846. /********* Start of inlined file: juce_FileOutputStream.h *********/
  10847. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10848. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10849. /**
  10850. An output stream that writes into a local file.
  10851. @see OutputStream, FileInputStream, File::createOutputStream
  10852. */
  10853. class JUCE_API FileOutputStream : public OutputStream
  10854. {
  10855. public:
  10856. /** Creates a FileOutputStream.
  10857. If the file doesn't exist, it will first be created. If the file can't be
  10858. created or opened, the failedToOpen() method will return
  10859. true.
  10860. If the file already exists when opened, the stream's write-postion will
  10861. be set to the end of the file. To overwrite an existing file,
  10862. use File::deleteFile() before opening the stream, or use setPosition(0)
  10863. after it's opened (although this won't truncate the file).
  10864. It's better to use File::createOutputStream() to create one of these, rather
  10865. than using the class directly.
  10866. */
  10867. FileOutputStream (const File& fileToWriteTo,
  10868. const int bufferSizeToUse = 16384);
  10869. /** Destructor. */
  10870. ~FileOutputStream();
  10871. /** Returns the file that this stream is writing to.
  10872. */
  10873. const File& getFile() const { return file; }
  10874. /** Returns true if the stream couldn't be opened for some reason.
  10875. */
  10876. bool failedToOpen() const { return fileHandle == 0; }
  10877. void flush();
  10878. int64 getPosition();
  10879. bool setPosition (int64 pos);
  10880. bool write (const void* data, int numBytes);
  10881. juce_UseDebuggingNewOperator
  10882. private:
  10883. File file;
  10884. void* fileHandle;
  10885. int64 currentPosition;
  10886. int bufferSize, bytesInBuffer;
  10887. HeapBlock <char> buffer;
  10888. };
  10889. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10890. /********* End of inlined file: juce_FileOutputStream.h *********/
  10891. #endif
  10892. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  10893. /********* Start of inlined file: juce_FileSearchPath.h *********/
  10894. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  10895. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  10896. /**
  10897. Encapsulates a set of folders that make up a search path.
  10898. @see File
  10899. */
  10900. class JUCE_API FileSearchPath
  10901. {
  10902. public:
  10903. /** Creates an empty search path. */
  10904. FileSearchPath();
  10905. /** Creates a search path from a string of pathnames.
  10906. The path can be semicolon- or comma-separated, e.g.
  10907. "/foo/bar;/foo/moose;/fish/moose"
  10908. The separate folders are tokenised and added to the search path.
  10909. */
  10910. FileSearchPath (const String& path);
  10911. /** Creates a copy of another search path. */
  10912. FileSearchPath (const FileSearchPath& other);
  10913. /** Destructor. */
  10914. ~FileSearchPath();
  10915. /** Uses a string containing a list of pathnames to re-initialise this list.
  10916. This search path is cleared and the semicolon- or comma-separated folders
  10917. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  10918. */
  10919. const FileSearchPath& operator= (const String& path);
  10920. /** Returns the number of folders in this search path.
  10921. @see operator[]
  10922. */
  10923. int getNumPaths() const;
  10924. /** Returns one of the folders in this search path.
  10925. The file returned isn't guaranteed to actually be a valid directory.
  10926. @see getNumPaths
  10927. */
  10928. const File operator[] (const int index) const;
  10929. /** Returns the search path as a semicolon-separated list of directories. */
  10930. const String toString() const;
  10931. /** Adds a new directory to the search path.
  10932. The new directory is added to the end of the list if the insertIndex parameter is
  10933. less than zero, otherwise it is inserted at the given index.
  10934. */
  10935. void add (const File& directoryToAdd,
  10936. const int insertIndex = -1);
  10937. /** Adds a new directory to the search path if it's not already in there. */
  10938. void addIfNotAlreadyThere (const File& directoryToAdd);
  10939. /** Removes a directory from the search path. */
  10940. void remove (const int indexToRemove);
  10941. /** Merges another search path into this one.
  10942. This will remove any duplicate directories.
  10943. */
  10944. void addPath (const FileSearchPath& other);
  10945. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  10946. If the search is intended to be recursive, there's no point having nested folders in the search
  10947. path, because they'll just get searched twice and you'll get duplicate results.
  10948. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  10949. */
  10950. void removeRedundantPaths();
  10951. /** Removes any directories that don't actually exist. */
  10952. void removeNonExistentPaths();
  10953. /** Searches the path for a wildcard.
  10954. This will search all the directories in the search path in order, adding any
  10955. matching files to the results array.
  10956. @param results an array to append the results to
  10957. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  10958. return files, directories, or both.
  10959. @param searchRecursively whether to recursively search the subdirectories too
  10960. @param wildCardPattern a pattern to match against the filenames
  10961. @returns the number of files added to the array
  10962. @see File::findChildFiles
  10963. */
  10964. int findChildFiles (OwnedArray<File>& results,
  10965. const int whatToLookFor,
  10966. const bool searchRecursively,
  10967. const String& wildCardPattern = JUCE_T("*")) const;
  10968. /** Finds out whether a file is inside one of the path's directories.
  10969. This will return true if the specified file is a child of one of the
  10970. directories specified by this path. Note that this doesn't actually do any
  10971. searching or check that the files exist - it just looks at the pathnames
  10972. to work out whether the file would be inside a directory.
  10973. @param fileToCheck the file to look for
  10974. @param checkRecursively if true, then this will return true if the file is inside a
  10975. subfolder of one of the path's directories (at any depth). If false
  10976. it will only return true if the file is actually a direct child
  10977. of one of the directories.
  10978. @see File::isAChildOf
  10979. */
  10980. bool isFileInPath (const File& fileToCheck,
  10981. const bool checkRecursively) const;
  10982. juce_UseDebuggingNewOperator
  10983. private:
  10984. StringArray directories;
  10985. void init (const String& path);
  10986. };
  10987. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  10988. /********* End of inlined file: juce_FileSearchPath.h *********/
  10989. #endif
  10990. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  10991. /********* Start of inlined file: juce_NamedPipe.h *********/
  10992. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  10993. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  10994. /**
  10995. A cross-process pipe that can have data written to and read from it.
  10996. Two or more processes can use these for inter-process communication.
  10997. @see InterprocessConnection
  10998. */
  10999. class JUCE_API NamedPipe
  11000. {
  11001. public:
  11002. /** Creates a NamedPipe. */
  11003. NamedPipe();
  11004. /** Destructor. */
  11005. ~NamedPipe();
  11006. /** Tries to open a pipe that already exists.
  11007. Returns true if it succeeds.
  11008. */
  11009. bool openExisting (const String& pipeName);
  11010. /** Tries to create a new pipe.
  11011. Returns true if it succeeds.
  11012. */
  11013. bool createNewPipe (const String& pipeName);
  11014. /** Closes the pipe, if it's open. */
  11015. void close();
  11016. /** True if the pipe is currently open. */
  11017. bool isOpen() const;
  11018. /** Returns the last name that was used to try to open this pipe. */
  11019. const String getName() const;
  11020. /** Reads data from the pipe.
  11021. This will block until another thread has written enough data into the pipe to fill
  11022. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11023. method.
  11024. If the operation fails, it returns -1, otherwise, it will return the number of
  11025. bytes read.
  11026. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11027. this is a maximum timeout for reading from the pipe.
  11028. */
  11029. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11030. /** Writes some data to the pipe.
  11031. If the operation fails, it returns -1, otherwise, it will return the number of
  11032. bytes written.
  11033. */
  11034. int write (const void* sourceBuffer, int numBytesToWrite,
  11035. int timeOutMilliseconds = 2000);
  11036. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11037. */
  11038. void cancelPendingReads();
  11039. juce_UseDebuggingNewOperator
  11040. private:
  11041. void* internal;
  11042. String currentPipeName;
  11043. NamedPipe (const NamedPipe&);
  11044. const NamedPipe& operator= (const NamedPipe&);
  11045. bool openInternal (const String& pipeName, const bool createPipe);
  11046. };
  11047. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11048. /********* End of inlined file: juce_NamedPipe.h *********/
  11049. #endif
  11050. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11051. /********* Start of inlined file: juce_ZipFile.h *********/
  11052. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11053. #define __JUCE_ZIPFILE_JUCEHEADER__
  11054. /********* Start of inlined file: juce_InputSource.h *********/
  11055. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11056. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  11057. /**
  11058. A lightweight object that can create a stream to read some kind of resource.
  11059. This may be used to refer to a file, or some other kind of source, allowing a
  11060. caller to create an input stream that can read from it when required.
  11061. @see FileInputSource
  11062. */
  11063. class JUCE_API InputSource
  11064. {
  11065. public:
  11066. InputSource() throw() {}
  11067. /** Destructor. */
  11068. virtual ~InputSource() {}
  11069. /** Returns a new InputStream to read this item.
  11070. @returns an inputstream that the caller will delete, or 0 if
  11071. the filename isn't found.
  11072. */
  11073. virtual InputStream* createInputStream() = 0;
  11074. /** Returns a new InputStream to read an item, relative.
  11075. @param relatedItemPath the relative pathname of the resource that is required
  11076. @returns an inputstream that the caller will delete, or 0 if
  11077. the item isn't found.
  11078. */
  11079. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  11080. /** Returns a hash code that uniquely represents this item.
  11081. */
  11082. virtual int64 hashCode() const = 0;
  11083. juce_UseDebuggingNewOperator
  11084. };
  11085. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  11086. /********* End of inlined file: juce_InputSource.h *********/
  11087. /**
  11088. Decodes a ZIP file from a stream.
  11089. This can enumerate the items in a ZIP file and can create suitable stream objects
  11090. to read each one.
  11091. */
  11092. class JUCE_API ZipFile
  11093. {
  11094. public:
  11095. /** Creates a ZipFile for a given stream.
  11096. @param inputStream the stream to read from
  11097. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  11098. will be deleted when this ZipFile object is deleted
  11099. */
  11100. ZipFile (InputStream* const inputStream,
  11101. const bool deleteStreamWhenDestroyed) throw();
  11102. /** Creates a ZipFile based for a file. */
  11103. ZipFile (const File& file);
  11104. /** Creates a ZipFile for an input source.
  11105. The inputSource object will be owned by the zip file, which will delete
  11106. it later when not needed.
  11107. */
  11108. ZipFile (InputSource* const inputSource);
  11109. /** Destructor. */
  11110. ~ZipFile() throw();
  11111. /**
  11112. Contains information about one of the entries in a ZipFile.
  11113. @see ZipFile::getEntry
  11114. */
  11115. struct ZipEntry
  11116. {
  11117. /** The name of the file, which may also include a partial pathname. */
  11118. String filename;
  11119. /** The file's original size. */
  11120. unsigned int uncompressedSize;
  11121. /** The last time the file was modified. */
  11122. Time fileTime;
  11123. };
  11124. /** Returns the number of items in the zip file. */
  11125. int getNumEntries() const throw();
  11126. /** Returns a structure that describes one of the entries in the zip file.
  11127. This may return zero if the index is out of range.
  11128. @see ZipFile::ZipEntry
  11129. */
  11130. const ZipEntry* getEntry (const int index) const throw();
  11131. /** Returns the index of the first entry with a given filename.
  11132. This uses a case-sensitive comparison to look for a filename in the
  11133. list of entries. It might return -1 if no match is found.
  11134. @see ZipFile::ZipEntry
  11135. */
  11136. int getIndexOfFileName (const String& fileName) const throw();
  11137. /** Returns a structure that describes one of the entries in the zip file.
  11138. This uses a case-sensitive comparison to look for a filename in the
  11139. list of entries. It might return 0 if no match is found.
  11140. @see ZipFile::ZipEntry
  11141. */
  11142. const ZipEntry* getEntry (const String& fileName) const throw();
  11143. /** Sorts the list of entries, based on the filename.
  11144. */
  11145. void sortEntriesByFilename();
  11146. /** Creates a stream that can read from one of the zip file's entries.
  11147. The stream that is returned must be deleted by the caller (and
  11148. zero might be returned if a stream can't be opened for some reason).
  11149. The stream must not be used after the ZipFile object that created
  11150. has been deleted.
  11151. */
  11152. InputStream* createStreamForEntry (const int index);
  11153. /** Uncompresses all of the files in the zip file.
  11154. This will expand all the entires into a target directory. The relative
  11155. paths of the entries are used.
  11156. @param targetDirectory the root folder to uncompress to
  11157. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  11158. */
  11159. void uncompressTo (const File& targetDirectory,
  11160. const bool shouldOverwriteFiles = true);
  11161. juce_UseDebuggingNewOperator
  11162. private:
  11163. VoidArray entries;
  11164. friend class ZipInputStream;
  11165. CriticalSection lock;
  11166. InputStream* inputStream;
  11167. ScopedPointer <InputStream> streamToDelete;
  11168. ScopedPointer <InputSource> inputSource;
  11169. int numEntries, centralRecStart;
  11170. #ifdef JUCE_DEBUG
  11171. int numOpenStreams;
  11172. #endif
  11173. void init();
  11174. int findEndOfZipEntryTable (InputStream* in);
  11175. ZipFile (const ZipFile&);
  11176. const ZipFile& operator= (const ZipFile&);
  11177. };
  11178. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  11179. /********* End of inlined file: juce_ZipFile.h *********/
  11180. #endif
  11181. #ifndef __JUCE_SOCKET_JUCEHEADER__
  11182. /********* Start of inlined file: juce_Socket.h *********/
  11183. #ifndef __JUCE_SOCKET_JUCEHEADER__
  11184. #define __JUCE_SOCKET_JUCEHEADER__
  11185. /**
  11186. A wrapper for a streaming (TCP) socket.
  11187. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  11188. sockets, you could also try the InterprocessConnection class.
  11189. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  11190. */
  11191. class JUCE_API StreamingSocket
  11192. {
  11193. public:
  11194. /** Creates an uninitialised socket.
  11195. To connect it, use the connect() method, after which you can read() or write()
  11196. to it.
  11197. To wait for other sockets to connect to this one, the createListener() method
  11198. enters "listener" mode, and can be used to spawn new sockets for each connection
  11199. that comes along.
  11200. */
  11201. StreamingSocket();
  11202. /** Destructor. */
  11203. ~StreamingSocket();
  11204. /** Binds the socket to the specified local port.
  11205. @returns true on success; false may indicate that another socket is already bound
  11206. on the same port
  11207. */
  11208. bool bindToPort (const int localPortNumber);
  11209. /** Tries to connect the socket to hostname:port.
  11210. If timeOutMillisecs is 0, then this method will block until the operating system
  11211. rejects the connection (which could take a long time).
  11212. @returns true if it succeeds.
  11213. @see isConnected
  11214. */
  11215. bool connect (const String& remoteHostname,
  11216. const int remotePortNumber,
  11217. const int timeOutMillisecs = 3000);
  11218. /** True if the socket is currently connected. */
  11219. bool isConnected() const throw() { return connected; }
  11220. /** Closes the connection. */
  11221. void close();
  11222. /** Returns the name of the currently connected host. */
  11223. const String& getHostName() const throw() { return hostName; }
  11224. /** Returns the port number that's currently open. */
  11225. int getPort() const throw() { return portNumber; }
  11226. /** True if the socket is connected to this machine rather than over the network. */
  11227. bool isLocal() const throw();
  11228. /** Waits until the socket is ready for reading or writing.
  11229. If readyForReading is true, it will wait until the socket is ready for
  11230. reading; if false, it will wait until it's ready for writing.
  11231. If the timeout is < 0, it will wait forever, or else will give up after
  11232. the specified time.
  11233. If the socket is ready on return, this returns 1. If it times-out before
  11234. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  11235. */
  11236. int waitUntilReady (const bool readyForReading,
  11237. const int timeoutMsecs) const;
  11238. /** Reads bytes from the socket.
  11239. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  11240. maxBytesToRead bytes have been read, (or until an error occurs). If this
  11241. flag is false, the method will return as much data as is currently available
  11242. without blocking.
  11243. @returns the number of bytes read, or -1 if there was an error.
  11244. @see waitUntilReady
  11245. */
  11246. int read (void* destBuffer, const int maxBytesToRead,
  11247. const bool blockUntilSpecifiedAmountHasArrived);
  11248. /** Writes bytes to the socket from a buffer.
  11249. Note that this method will block unless you have checked the socket is ready
  11250. for writing before calling it (see the waitUntilReady() method).
  11251. @returns the number of bytes written, or -1 if there was an error.
  11252. */
  11253. int write (const void* sourceBuffer, const int numBytesToWrite);
  11254. /** Puts this socket into "listener" mode.
  11255. When in this mode, your thread can call waitForNextConnection() repeatedly,
  11256. which will spawn new sockets for each new connection, so that these can
  11257. be handled in parallel by other threads.
  11258. @param portNumber the port number to listen on
  11259. @param localHostName the interface address to listen on - pass an empty
  11260. string to listen on all addresses
  11261. @returns true if it manages to open the socket successfully.
  11262. @see waitForNextConnection
  11263. */
  11264. bool createListener (const int portNumber, const String& localHostName = String::empty);
  11265. /** When in "listener" mode, this waits for a connection and spawns it as a new
  11266. socket.
  11267. The object that gets returned will be owned by the caller.
  11268. This method can only be called after using createListener().
  11269. @see createListener
  11270. */
  11271. StreamingSocket* waitForNextConnection() const;
  11272. juce_UseDebuggingNewOperator
  11273. private:
  11274. String hostName;
  11275. int volatile portNumber, handle;
  11276. bool connected, isListener;
  11277. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  11278. StreamingSocket (const StreamingSocket&);
  11279. const StreamingSocket& operator= (const StreamingSocket&);
  11280. };
  11281. /**
  11282. A wrapper for a datagram (UDP) socket.
  11283. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  11284. sockets, you could also try the InterprocessConnection class.
  11285. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  11286. */
  11287. class JUCE_API DatagramSocket
  11288. {
  11289. public:
  11290. /**
  11291. Creates an (uninitialised) datagram socket.
  11292. The localPortNumber is the port on which to bind this socket. If this value is 0,
  11293. the port number is assigned by the operating system.
  11294. To use the socket for sending, call the connect() method. This will not immediately
  11295. make a connection, but will save the destination you've provided. After this, you can
  11296. call read() or write().
  11297. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  11298. (may require extra privileges on linux)
  11299. To wait for other sockets to connect to this one, call waitForNextConnection().
  11300. */
  11301. DatagramSocket (const int localPortNumber,
  11302. const bool enableBroadcasting = false);
  11303. /** Destructor. */
  11304. ~DatagramSocket();
  11305. /** Binds the socket to the specified local port.
  11306. @returns true on success; false may indicate that another socket is already bound
  11307. on the same port
  11308. */
  11309. bool bindToPort (const int localPortNumber);
  11310. /** Tries to connect the socket to hostname:port.
  11311. If timeOutMillisecs is 0, then this method will block until the operating system
  11312. rejects the connection (which could take a long time).
  11313. @returns true if it succeeds.
  11314. @see isConnected
  11315. */
  11316. bool connect (const String& remoteHostname,
  11317. const int remotePortNumber,
  11318. const int timeOutMillisecs = 3000);
  11319. /** True if the socket is currently connected. */
  11320. bool isConnected() const throw() { return connected; }
  11321. /** Closes the connection. */
  11322. void close();
  11323. /** Returns the name of the currently connected host. */
  11324. const String& getHostName() const throw() { return hostName; }
  11325. /** Returns the port number that's currently open. */
  11326. int getPort() const throw() { return portNumber; }
  11327. /** True if the socket is connected to this machine rather than over the network. */
  11328. bool isLocal() const throw();
  11329. /** Waits until the socket is ready for reading or writing.
  11330. If readyForReading is true, it will wait until the socket is ready for
  11331. reading; if false, it will wait until it's ready for writing.
  11332. If the timeout is < 0, it will wait forever, or else will give up after
  11333. the specified time.
  11334. If the socket is ready on return, this returns 1. If it times-out before
  11335. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  11336. */
  11337. int waitUntilReady (const bool readyForReading,
  11338. const int timeoutMsecs) const;
  11339. /** Reads bytes from the socket.
  11340. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  11341. maxBytesToRead bytes have been read, (or until an error occurs). If this
  11342. flag is false, the method will return as much data as is currently available
  11343. without blocking.
  11344. @returns the number of bytes read, or -1 if there was an error.
  11345. @see waitUntilReady
  11346. */
  11347. int read (void* destBuffer, const int maxBytesToRead,
  11348. const bool blockUntilSpecifiedAmountHasArrived);
  11349. /** Writes bytes to the socket from a buffer.
  11350. Note that this method will block unless you have checked the socket is ready
  11351. for writing before calling it (see the waitUntilReady() method).
  11352. @returns the number of bytes written, or -1 if there was an error.
  11353. */
  11354. int write (const void* sourceBuffer, const int numBytesToWrite);
  11355. /** This waits for incoming data to be sent, and returns a socket that can be used
  11356. to read it.
  11357. The object that gets returned is owned by the caller, and can't be used for
  11358. sending, but can be used to read the data.
  11359. */
  11360. DatagramSocket* waitForNextConnection() const;
  11361. juce_UseDebuggingNewOperator
  11362. private:
  11363. String hostName;
  11364. int volatile portNumber, handle;
  11365. bool connected, allowBroadcast;
  11366. void* serverAddress;
  11367. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  11368. DatagramSocket (const DatagramSocket&);
  11369. const DatagramSocket& operator= (const DatagramSocket&);
  11370. };
  11371. #endif // __JUCE_SOCKET_JUCEHEADER__
  11372. /********* End of inlined file: juce_Socket.h *********/
  11373. #endif
  11374. #ifndef __JUCE_URL_JUCEHEADER__
  11375. /********* Start of inlined file: juce_URL.h *********/
  11376. #ifndef __JUCE_URL_JUCEHEADER__
  11377. #define __JUCE_URL_JUCEHEADER__
  11378. /**
  11379. Represents a URL and has a bunch of useful functions to manipulate it.
  11380. This class can be used to launch URLs in browsers, and also to create
  11381. InputStreams that can read from remote http or ftp sources.
  11382. */
  11383. class JUCE_API URL
  11384. {
  11385. public:
  11386. /** Creates an empty URL. */
  11387. URL();
  11388. /** Creates a URL from a string. */
  11389. URL (const String& url);
  11390. /** Creates a copy of another URL. */
  11391. URL (const URL& other);
  11392. /** Destructor. */
  11393. ~URL();
  11394. /** Copies this URL from another one. */
  11395. const URL& operator= (const URL& other);
  11396. /** Returns a string version of the URL.
  11397. If includeGetParameters is true and any parameters have been set with the
  11398. withParameter() method, then the string will have these appended on the
  11399. end and url-encoded.
  11400. */
  11401. const String toString (const bool includeGetParameters) const;
  11402. /** True if it seems to be valid. */
  11403. bool isWellFormed() const;
  11404. /** Returns just the domain part of the URL.
  11405. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  11406. */
  11407. const String getDomain() const;
  11408. /** Returns the path part of the URL.
  11409. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  11410. */
  11411. const String getSubPath() const;
  11412. /** Returns the scheme of the URL.
  11413. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  11414. include the colon).
  11415. */
  11416. const String getScheme() const;
  11417. /** Returns a new version of this URL that uses a different sub-path.
  11418. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  11419. "bar", it'll return "http://www.xyz.com/bar?x=1".
  11420. */
  11421. const URL withNewSubPath (const String& newPath) const;
  11422. /** Returns a copy of this URL, with a GET parameter added to the end.
  11423. Any control characters in the value will be encoded.
  11424. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  11425. would produce a new url whose toString(true) method would return
  11426. "www.fish.com?amount=some+fish".
  11427. */
  11428. const URL withParameter (const String& parameterName,
  11429. const String& parameterValue) const;
  11430. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  11431. When performing a POST where one of your parameters is a binary file, this
  11432. lets you specify the file.
  11433. Note that the filename is stored, but the file itself won't actually be read
  11434. until this URL is later used to create a network input stream.
  11435. */
  11436. const URL withFileToUpload (const String& parameterName,
  11437. const File& fileToUpload,
  11438. const String& mimeType) const;
  11439. /** Returns a set of all the parameters encoded into the url.
  11440. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  11441. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  11442. The values returned will have been cleaned up to remove any escape characters.
  11443. @see getNamedParameter, withParameter
  11444. */
  11445. const StringPairArray& getParameters() const;
  11446. /** Returns the set of files that should be uploaded as part of a POST operation.
  11447. This is the set of files that were added to the URL with the withFileToUpload()
  11448. method.
  11449. */
  11450. const StringPairArray& getFilesToUpload() const;
  11451. /** Returns the set of mime types associated with each of the upload files.
  11452. */
  11453. const StringPairArray& getMimeTypesOfUploadFiles() const;
  11454. /** Returns a copy of this URL, with a block of data to send as the POST data.
  11455. If you're setting the POST data, be careful not to have any parameters set
  11456. as well, otherwise it'll all get thrown in together, and might not have the
  11457. desired effect.
  11458. If the URL already contains some POST data, this will replace it, rather
  11459. than being appended to it.
  11460. This data will only be used if you specify a post operation when you call
  11461. createInputStream().
  11462. */
  11463. const URL withPOSTData (const String& postData) const;
  11464. /** Returns the data that was set using withPOSTData().
  11465. */
  11466. const String getPostData() const { return postData; }
  11467. /** Tries to launch the system's default browser to open the URL.
  11468. Returns true if this seems to have worked.
  11469. */
  11470. bool launchInDefaultBrowser() const;
  11471. /** Takes a guess as to whether a string might be a valid website address.
  11472. This isn't foolproof!
  11473. */
  11474. static bool isProbablyAWebsiteURL (const String& possibleURL);
  11475. /** Takes a guess as to whether a string might be a valid email address.
  11476. This isn't foolproof!
  11477. */
  11478. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  11479. /** This callback function can be used by the createInputStream() method.
  11480. It allows your app to receive progress updates during a lengthy POST operation. If you
  11481. want to continue the operation, this should return true, or false to abort.
  11482. */
  11483. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  11484. /** Attempts to open a stream that can read from this URL.
  11485. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  11486. the paramters, otherwise it'll encode them into the
  11487. URL and do a 'GET'.
  11488. @param progressCallback if this is non-zero, it lets you supply a callback function
  11489. to keep track of the operation's progress. This can be useful
  11490. for lengthy POST operations, so that you can provide user feedback.
  11491. @param progressCallbackContext if a callback is specified, this value will be passed to
  11492. the function
  11493. @param extraHeaders if not empty, this string is appended onto the headers that
  11494. are used for the request. It must therefore be a valid set of HTML
  11495. header directives, separated by newlines.
  11496. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  11497. a negative number, it will be infinite. Otherwise it specifies a
  11498. time in milliseconds.
  11499. */
  11500. InputStream* createInputStream (const bool usePostCommand,
  11501. OpenStreamProgressCallback* const progressCallback = 0,
  11502. void* const progressCallbackContext = 0,
  11503. const String& extraHeaders = String::empty,
  11504. const int connectionTimeOutMs = 0) const;
  11505. /** Tries to download the entire contents of this URL into a binary data block.
  11506. If it succeeds, this will return true and append the data it read onto the end
  11507. of the memory block.
  11508. @param destData the memory block to append the new data to
  11509. @param usePostCommand whether to use a POST command to get the data (uses
  11510. a GET command if this is false)
  11511. @see readEntireTextStream, readEntireXmlStream
  11512. */
  11513. bool readEntireBinaryStream (MemoryBlock& destData,
  11514. const bool usePostCommand = false) const;
  11515. /** Tries to download the entire contents of this URL as a string.
  11516. If it fails, this will return an empty string, otherwise it will return the
  11517. contents of the downloaded file. If you need to distinguish between a read
  11518. operation that fails and one that returns an empty string, you'll need to use
  11519. a different method, such as readEntireBinaryStream().
  11520. @param usePostCommand whether to use a POST command to get the data (uses
  11521. a GET command if this is false)
  11522. @see readEntireBinaryStream, readEntireXmlStream
  11523. */
  11524. const String readEntireTextStream (const bool usePostCommand = false) const;
  11525. /** Tries to download the entire contents of this URL and parse it as XML.
  11526. If it fails, or if the text that it reads can't be parsed as XML, this will
  11527. return 0.
  11528. When it returns a valid XmlElement object, the caller is responsibile for deleting
  11529. this object when no longer needed.
  11530. @param usePostCommand whether to use a POST command to get the data (uses
  11531. a GET command if this is false)
  11532. @see readEntireBinaryStream, readEntireTextStream
  11533. */
  11534. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  11535. /** Adds escape sequences to a string to encode any characters that aren't
  11536. legal in a URL.
  11537. E.g. any spaces will be replaced with "%20".
  11538. This is the opposite of removeEscapeChars().
  11539. If isParameter is true, it means that the string is going to be used
  11540. as a parameter, so it also encodes '$' and ',' (which would otherwise
  11541. be legal in a URL.
  11542. @see removeEscapeChars
  11543. */
  11544. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  11545. const bool isParameter);
  11546. /** Replaces any escape character sequences in a string with their original
  11547. character codes.
  11548. E.g. any instances of "%20" will be replaced by a space.
  11549. This is the opposite of addEscapeChars().
  11550. @see addEscapeChars
  11551. */
  11552. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  11553. juce_UseDebuggingNewOperator
  11554. private:
  11555. String url, postData;
  11556. StringPairArray parameters, filesToUpload, mimeTypes;
  11557. };
  11558. #endif // __JUCE_URL_JUCEHEADER__
  11559. /********* End of inlined file: juce_URL.h *********/
  11560. #endif
  11561. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11562. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  11563. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11564. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11565. /** Wraps another input stream, and reads from it using an intermediate buffer
  11566. If you're using an input stream such as a file input stream, and making lots of
  11567. small read accesses to it, it's probably sensible to wrap it in one of these,
  11568. so that the source stream gets accessed in larger chunk sizes, meaning less
  11569. work for the underlying stream.
  11570. */
  11571. class JUCE_API BufferedInputStream : public InputStream
  11572. {
  11573. public:
  11574. /** Creates a BufferedInputStream from an input source.
  11575. @param sourceStream the source stream to read from
  11576. @param bufferSize the size of reservoir to use to buffer the source
  11577. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  11578. deleted by this object when it is itself deleted.
  11579. */
  11580. BufferedInputStream (InputStream* const sourceStream,
  11581. const int bufferSize,
  11582. const bool deleteSourceWhenDestroyed);
  11583. /** Destructor.
  11584. This may also delete the source stream, if that option was chosen when the
  11585. buffered stream was created.
  11586. */
  11587. ~BufferedInputStream();
  11588. int64 getTotalLength();
  11589. int64 getPosition();
  11590. bool setPosition (int64 newPosition);
  11591. int read (void* destBuffer, int maxBytesToRead);
  11592. const String readString();
  11593. bool isExhausted();
  11594. juce_UseDebuggingNewOperator
  11595. private:
  11596. InputStream* const source;
  11597. ScopedPointer <InputStream> sourceToDelete;
  11598. int bufferSize;
  11599. int64 position, lastReadPos, bufferStart, bufferOverlap;
  11600. HeapBlock <char> buffer;
  11601. void ensureBuffered();
  11602. BufferedInputStream (const BufferedInputStream&);
  11603. const BufferedInputStream& operator= (const BufferedInputStream&);
  11604. };
  11605. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11606. /********* End of inlined file: juce_BufferedInputStream.h *********/
  11607. #endif
  11608. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11609. /********* Start of inlined file: juce_FileInputSource.h *********/
  11610. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11611. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11612. /**
  11613. A type of InputSource that represents a normal file.
  11614. @see InputSource
  11615. */
  11616. class JUCE_API FileInputSource : public InputSource
  11617. {
  11618. public:
  11619. FileInputSource (const File& file);
  11620. ~FileInputSource();
  11621. InputStream* createInputStream();
  11622. InputStream* createInputStreamFor (const String& relatedItemPath);
  11623. int64 hashCode() const;
  11624. juce_UseDebuggingNewOperator
  11625. private:
  11626. const File file;
  11627. FileInputSource (const FileInputSource&);
  11628. const FileInputSource& operator= (const FileInputSource&);
  11629. };
  11630. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11631. /********* End of inlined file: juce_FileInputSource.h *********/
  11632. #endif
  11633. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11634. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  11635. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11636. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11637. class GZIPCompressorHelper;
  11638. /**
  11639. A stream which uses zlib to compress the data written into it.
  11640. @see GZIPDecompressorInputStream
  11641. */
  11642. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  11643. {
  11644. public:
  11645. /** Creates a compression stream.
  11646. @param destStream the stream into which the compressed data should
  11647. be written
  11648. @param compressionLevel how much to compress the data, between 1 and 9, where
  11649. 1 is the fastest/lowest compression, and 9 is the
  11650. slowest/highest compression. Any value outside this range
  11651. indicates that a default compression level should be used.
  11652. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  11653. this stream is destroyed
  11654. @param noWrap this is used internally by the ZipFile class
  11655. and should be ignored by user applications
  11656. */
  11657. GZIPCompressorOutputStream (OutputStream* const destStream,
  11658. int compressionLevel = 0,
  11659. const bool deleteDestStreamWhenDestroyed = false,
  11660. const bool noWrap = false);
  11661. /** Destructor. */
  11662. ~GZIPCompressorOutputStream();
  11663. void flush();
  11664. int64 getPosition();
  11665. bool setPosition (int64 newPosition);
  11666. bool write (const void* destBuffer, int howMany);
  11667. juce_UseDebuggingNewOperator
  11668. private:
  11669. OutputStream* const destStream;
  11670. ScopedPointer <OutputStream> streamToDelete;
  11671. HeapBlock <uint8> buffer;
  11672. ScopedPointer <GZIPCompressorHelper> helper;
  11673. bool doNextBlock();
  11674. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  11675. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  11676. };
  11677. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11678. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  11679. #endif
  11680. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11681. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  11682. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11683. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11684. class GZIPDecompressHelper;
  11685. /**
  11686. This stream will decompress a source-stream using zlib.
  11687. Tip: if you're reading lots of small items from one of these streams, you
  11688. can increase the performance enormously by passing it through a
  11689. BufferedInputStream, so that it has to read larger blocks less often.
  11690. @see GZIPCompressorOutputStream
  11691. */
  11692. class JUCE_API GZIPDecompressorInputStream : public InputStream
  11693. {
  11694. public:
  11695. /** Creates a decompressor stream.
  11696. @param sourceStream the stream to read from
  11697. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  11698. when this object is destroyed
  11699. @param noWrap this is used internally by the ZipFile class
  11700. and should be ignored by user applications
  11701. @param uncompressedStreamLength if the creator knows the length that the
  11702. uncompressed stream will be, then it can supply this
  11703. value, which will be returned by getTotalLength()
  11704. */
  11705. GZIPDecompressorInputStream (InputStream* const sourceStream,
  11706. const bool deleteSourceWhenDestroyed,
  11707. const bool noWrap = false,
  11708. const int64 uncompressedStreamLength = -1);
  11709. /** Destructor. */
  11710. ~GZIPDecompressorInputStream();
  11711. int64 getPosition();
  11712. bool setPosition (int64 pos);
  11713. int64 getTotalLength();
  11714. bool isExhausted();
  11715. int read (void* destBuffer, int maxBytesToRead);
  11716. juce_UseDebuggingNewOperator
  11717. private:
  11718. InputStream* const sourceStream;
  11719. ScopedPointer <InputStream> streamToDelete;
  11720. const int64 uncompressedStreamLength;
  11721. const bool noWrap;
  11722. bool isEof;
  11723. int activeBufferSize;
  11724. int64 originalSourcePos, currentPos;
  11725. HeapBlock <uint8> buffer;
  11726. ScopedPointer <GZIPDecompressHelper> helper;
  11727. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  11728. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  11729. };
  11730. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11731. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  11732. #endif
  11733. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11734. #endif
  11735. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  11736. #endif
  11737. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11738. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  11739. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11740. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11741. /**
  11742. Allows a block of data and to be accessed as a stream.
  11743. This can either be used to refer to a shared block of memory, or can make its
  11744. own internal copy of the data when the MemoryInputStream is created.
  11745. */
  11746. class JUCE_API MemoryInputStream : public InputStream
  11747. {
  11748. public:
  11749. /** Creates a MemoryInputStream.
  11750. @param sourceData the block of data to use as the stream's source
  11751. @param sourceDataSize the number of bytes in the source data block
  11752. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  11753. the source data, so this data shouldn't be changed
  11754. for the lifetime of the stream; if this parameter is
  11755. true, the stream will make its own copy of the
  11756. data and use that.
  11757. */
  11758. MemoryInputStream (const void* const sourceData,
  11759. const int sourceDataSize,
  11760. const bool keepInternalCopyOfData);
  11761. /** Destructor. */
  11762. ~MemoryInputStream();
  11763. int64 getPosition();
  11764. bool setPosition (int64 pos);
  11765. int64 getTotalLength();
  11766. bool isExhausted();
  11767. int read (void* destBuffer, int maxBytesToRead);
  11768. juce_UseDebuggingNewOperator
  11769. private:
  11770. const char* data;
  11771. int dataSize, position;
  11772. MemoryBlock internalCopy;
  11773. };
  11774. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11775. /********* End of inlined file: juce_MemoryInputStream.h *********/
  11776. #endif
  11777. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11778. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  11779. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11780. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11781. /** Writes data to an internal memory buffer, which grows as required.
  11782. The data that was written into the stream can then be accessed later as
  11783. a contiguous block of memory.
  11784. */
  11785. class JUCE_API MemoryOutputStream : public OutputStream
  11786. {
  11787. public:
  11788. /** Creates a memory stream ready for writing into.
  11789. @param initialSize the intial amount of space to allocate for writing into
  11790. @param granularity the increments by which the internal storage will be increased
  11791. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  11792. place that the data gets stored. If it's zero, the stream
  11793. will allocate its own storage internally, which you can
  11794. access using getData() and getDataSize()
  11795. */
  11796. MemoryOutputStream (const int initialSize = 256,
  11797. const int granularity = 256,
  11798. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  11799. /** Destructor.
  11800. This will free any data that was written to it.
  11801. */
  11802. ~MemoryOutputStream() throw();
  11803. /** Returns a pointer to the data that has been written to the stream.
  11804. @see getDataSize
  11805. */
  11806. const char* getData() throw();
  11807. /** Returns the number of bytes of data that have been written to the stream.
  11808. @see getData
  11809. */
  11810. int getDataSize() const throw();
  11811. /** Resets the stream, clearing any data that has been written to it so far. */
  11812. void reset() throw();
  11813. void flush();
  11814. bool write (const void* buffer, int howMany);
  11815. int64 getPosition();
  11816. bool setPosition (int64 newPosition);
  11817. juce_UseDebuggingNewOperator
  11818. private:
  11819. MemoryBlock* data;
  11820. ScopedPointer <MemoryBlock> dataToDelete;
  11821. int position, size, blockSize;
  11822. };
  11823. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11824. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  11825. #endif
  11826. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  11827. #endif
  11828. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11829. /********* Start of inlined file: juce_SubregionStream.h *********/
  11830. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11831. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11832. /** Wraps another input stream, and reads from a specific part of it.
  11833. This lets you take a subsection of a stream and present it as an entire
  11834. stream in its own right.
  11835. */
  11836. class JUCE_API SubregionStream : public InputStream
  11837. {
  11838. public:
  11839. /** Creates a SubregionStream from an input source.
  11840. @param sourceStream the source stream to read from
  11841. @param startPositionInSourceStream this is the position in the source stream that
  11842. corresponds to position 0 in this stream
  11843. @param lengthOfSourceStream this specifies the maximum number of bytes
  11844. from the source stream that will be passed through
  11845. by this stream. When the position of this stream
  11846. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  11847. If the length passed in here is greater than the length
  11848. of the source stream (as returned by getTotalLength()),
  11849. then the smaller value will be used.
  11850. Passing a negative value for this parameter means it
  11851. will keep reading until the source's end-of-stream.
  11852. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  11853. deleted by this object when it is itself deleted.
  11854. */
  11855. SubregionStream (InputStream* const sourceStream,
  11856. const int64 startPositionInSourceStream,
  11857. const int64 lengthOfSourceStream,
  11858. const bool deleteSourceWhenDestroyed) throw();
  11859. /** Destructor.
  11860. This may also delete the source stream, if that option was chosen when the
  11861. buffered stream was created.
  11862. */
  11863. ~SubregionStream() throw();
  11864. int64 getTotalLength();
  11865. int64 getPosition();
  11866. bool setPosition (int64 newPosition);
  11867. int read (void* destBuffer, int maxBytesToRead);
  11868. bool isExhausted();
  11869. juce_UseDebuggingNewOperator
  11870. private:
  11871. InputStream* const source;
  11872. ScopedPointer <InputStream> sourceToDelete;
  11873. const int64 startPositionInSourceStream, lengthOfSourceStream;
  11874. SubregionStream (const SubregionStream&);
  11875. const SubregionStream& operator= (const SubregionStream&);
  11876. };
  11877. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11878. /********* End of inlined file: juce_SubregionStream.h *********/
  11879. #endif
  11880. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  11881. #endif
  11882. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11883. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  11884. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11885. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11886. /** Used in the same way as the T(text) macro, this will attempt to translate a
  11887. string into a localised version using the LocalisedStrings class.
  11888. @see LocalisedStrings
  11889. */
  11890. #define TRANS(stringLiteral) \
  11891. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  11892. /**
  11893. Used to convert strings to localised foreign-language versions.
  11894. This is basically a look-up table of strings and their translated equivalents.
  11895. It can be loaded from a text file, so that you can supply a set of localised
  11896. versions of strings that you use in your app.
  11897. To use it in your code, simply call the translate() method on each string that
  11898. might have foreign versions, and if none is found, the method will just return
  11899. the original string.
  11900. The translation file should start with some lines specifying a description of
  11901. the language it contains, and also a list of ISO country codes where it might
  11902. be appropriate to use the file. After that, each line of the file should contain
  11903. a pair of quoted strings with an '=' sign.
  11904. E.g. for a french translation, the file might be:
  11905. @code
  11906. language: French
  11907. countries: fr be mc ch lu
  11908. "hello" = "bonjour"
  11909. "goodbye" = "au revoir"
  11910. @endcode
  11911. If the strings need to contain a quote character, they can use '\"' instead, and
  11912. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  11913. (you can use this to add comments).
  11914. Note that this is a singleton class, so don't create or destroy the object directly.
  11915. There's also a TRANS(text) macro defined to make it easy to use the this.
  11916. E.g. @code
  11917. printSomething (TRANS("hello"));
  11918. @endcode
  11919. This macro is used in the Juce classes themselves, so your application has a chance to
  11920. intercept and translate any internal Juce text strings that might be shown. (You can easily
  11921. get a list of all the messages by searching for the TRANS() macro in the Juce source
  11922. code).
  11923. */
  11924. class JUCE_API LocalisedStrings
  11925. {
  11926. public:
  11927. /** Creates a set of translations from the text of a translation file.
  11928. When you create one of these, you can call setCurrentMappings() to make it
  11929. the set of mappings that the system's using.
  11930. */
  11931. LocalisedStrings (const String& fileContents);
  11932. /** Creates a set of translations from a file.
  11933. When you create one of these, you can call setCurrentMappings() to make it
  11934. the set of mappings that the system's using.
  11935. */
  11936. LocalisedStrings (const File& fileToLoad);
  11937. /** Destructor. */
  11938. ~LocalisedStrings();
  11939. /** Selects the current set of mappings to be used by the system.
  11940. The object you pass in will be automatically deleted when no longer needed, so
  11941. don't keep a pointer to it. You can also pass in zero to remove the current
  11942. mappings.
  11943. See also the TRANS() macro, which uses the current set to do its translation.
  11944. @see translateWithCurrentMappings
  11945. */
  11946. static void setCurrentMappings (LocalisedStrings* newTranslations);
  11947. /** Returns the currently selected set of mappings.
  11948. This is the object that was last passed to setCurrentMappings(). It may
  11949. be 0 if none has been created.
  11950. */
  11951. static LocalisedStrings* getCurrentMappings();
  11952. /** Tries to translate a string using the currently selected set of mappings.
  11953. If no mapping has been set, or if the mapping doesn't contain a translation
  11954. for the string, this will just return the original string.
  11955. See also the TRANS() macro, which uses this method to do its translation.
  11956. @see setCurrentMappings, getCurrentMappings
  11957. */
  11958. static const String translateWithCurrentMappings (const String& text);
  11959. /** Tries to translate a string using the currently selected set of mappings.
  11960. If no mapping has been set, or if the mapping doesn't contain a translation
  11961. for the string, this will just return the original string.
  11962. See also the TRANS() macro, which uses this method to do its translation.
  11963. @see setCurrentMappings, getCurrentMappings
  11964. */
  11965. static const String translateWithCurrentMappings (const char* text);
  11966. /** Attempts to look up a string and return its localised version.
  11967. If the string isn't found in the list, the original string will be returned.
  11968. */
  11969. const String translate (const String& text) const;
  11970. /** Returns the name of the language specified in the translation file.
  11971. This is specified in the file using a line starting with "language:", e.g.
  11972. @code
  11973. language: german
  11974. @endcode
  11975. */
  11976. const String getLanguageName() const { return languageName; }
  11977. /** Returns the list of suitable country codes listed in the translation file.
  11978. These is specified in the file using a line starting with "countries:", e.g.
  11979. @code
  11980. countries: fr be mc ch lu
  11981. @endcode
  11982. The country codes are supposed to be 2-character ISO complient codes.
  11983. */
  11984. const StringArray getCountryCodes() const { return countryCodes; }
  11985. /** Indicates whether to use a case-insensitive search when looking up a string.
  11986. This defaults to true.
  11987. */
  11988. void setIgnoresCase (const bool shouldIgnoreCase);
  11989. juce_UseDebuggingNewOperator
  11990. private:
  11991. String languageName;
  11992. StringArray countryCodes;
  11993. StringPairArray translations;
  11994. void loadFromText (const String& fileContents);
  11995. };
  11996. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11997. /********* End of inlined file: juce_LocalisedStrings.h *********/
  11998. #endif
  11999. #ifndef __JUCE_STRING_JUCEHEADER__
  12000. #endif
  12001. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  12002. #endif
  12003. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  12004. #endif
  12005. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12006. /********* Start of inlined file: juce_XmlDocument.h *********/
  12007. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12008. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  12009. /**
  12010. Parses a text-based XML document and creates an XmlElement object from it.
  12011. The parser will parse DTDs to load external entities but won't
  12012. check the document for validity against the DTD.
  12013. e.g.
  12014. @code
  12015. XmlDocument myDocument (File ("myfile.xml"));
  12016. XmlElement* mainElement = myDocument.getDocumentElement();
  12017. if (mainElement == 0)
  12018. {
  12019. String error = myDocument.getLastParseError();
  12020. }
  12021. else
  12022. {
  12023. ..use the element
  12024. }
  12025. @endcode
  12026. @see XmlElement
  12027. */
  12028. class JUCE_API XmlDocument
  12029. {
  12030. public:
  12031. /** Creates an XmlDocument from the xml text.
  12032. The text doesn't actually get parsed until the getDocumentElement() method is
  12033. called.
  12034. */
  12035. XmlDocument (const String& documentText) throw();
  12036. /** Creates an XmlDocument from a file.
  12037. The text doesn't actually get parsed until the getDocumentElement() method is
  12038. called.
  12039. */
  12040. XmlDocument (const File& file);
  12041. /** Destructor. */
  12042. ~XmlDocument() throw();
  12043. /** Creates an XmlElement object to represent the main document node.
  12044. This method will do the actual parsing of the text, and if there's a
  12045. parse error, it may returns 0 (and you can find out the error using
  12046. the getLastParseError() method).
  12047. @param onlyReadOuterDocumentElement if true, the parser will only read the
  12048. first section of the file, and will only
  12049. return the outer document element - this
  12050. allows quick checking of large files to
  12051. see if they contain the correct type of
  12052. tag, without having to parse the entire file
  12053. @returns a new XmlElement which the caller will need to delete, or null if
  12054. there was an error.
  12055. @see getLastParseError
  12056. */
  12057. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  12058. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  12059. @returns the error, or an empty string if there was no error.
  12060. */
  12061. const String& getLastParseError() const throw();
  12062. /** Sets an input source object to use for parsing documents that reference external entities.
  12063. If the document has been created from a file, this probably won't be needed, but
  12064. if you're parsing some text and there might be a DTD that references external
  12065. files, you may need to create a custom input source that can retrieve the
  12066. other files it needs.
  12067. The object that is passed-in will be deleted automatically when no longer needed.
  12068. @see InputSource
  12069. */
  12070. void setInputSource (InputSource* const newSource) throw();
  12071. /** Sets a flag to change the treatment of empty text elements.
  12072. If this is true (the default state), then any text elements that contain only
  12073. whitespace characters will be ingored during parsing. If you need to catch
  12074. whitespace-only text, then you should set this to false before calling the
  12075. getDocumentElement() method.
  12076. */
  12077. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  12078. juce_UseDebuggingNewOperator
  12079. private:
  12080. String originalText;
  12081. const tchar* input;
  12082. bool outOfData, errorOccurred;
  12083. bool identifierLookupTable [128];
  12084. String lastError, dtdText;
  12085. StringArray tokenisedDTD;
  12086. bool needToLoadDTD, ignoreEmptyTextElements;
  12087. ScopedPointer <InputSource> inputSource;
  12088. void setLastError (const String& desc, const bool carryOn) throw();
  12089. void skipHeader() throw();
  12090. void skipNextWhiteSpace() throw();
  12091. tchar readNextChar() throw();
  12092. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  12093. void readChildElements (XmlElement* parent) throw();
  12094. int findNextTokenLength() throw();
  12095. void readQuotedString (String& result) throw();
  12096. void readEntity (String& result) throw();
  12097. static bool isXmlIdentifierCharSlow (const tchar c) throw();
  12098. bool isXmlIdentifierChar (const tchar c) const throw();
  12099. const String getFileContents (const String& filename) const;
  12100. const String expandEntity (const String& entity);
  12101. const String expandExternalEntity (const String& entity);
  12102. const String getParameterEntity (const String& entity);
  12103. };
  12104. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  12105. /********* End of inlined file: juce_XmlDocument.h *********/
  12106. #endif
  12107. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  12108. #endif
  12109. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  12110. #endif
  12111. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12112. /********* Start of inlined file: juce_InterProcessLock.h *********/
  12113. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12114. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12115. /**
  12116. Acts as a critical section which processes can use to block each other.
  12117. @see CriticalSection
  12118. */
  12119. class JUCE_API InterProcessLock
  12120. {
  12121. public:
  12122. /** Creates a lock object.
  12123. @param name a name that processes will use to identify this lock object
  12124. */
  12125. InterProcessLock (const String& name);
  12126. /** Destructor.
  12127. This will also release the lock if it's currently held by this process.
  12128. */
  12129. ~InterProcessLock();
  12130. /** Attempts to lock the critical section.
  12131. @param timeOutMillisecs how many milliseconds to wait if the lock
  12132. is already held by another process - a value of
  12133. 0 will return immediately, negative values will wait
  12134. forever
  12135. @returns true if the lock could be gained within the timeout period, or
  12136. false if the timeout expired.
  12137. */
  12138. bool enter (int timeOutMillisecs = -1);
  12139. /** Releases the lock if it's currently held by this process.
  12140. */
  12141. void exit();
  12142. juce_UseDebuggingNewOperator
  12143. private:
  12144. void* internal;
  12145. String name;
  12146. int reentrancyLevel;
  12147. InterProcessLock (const InterProcessLock&);
  12148. const InterProcessLock& operator= (const InterProcessLock&);
  12149. };
  12150. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12151. /********* End of inlined file: juce_InterProcessLock.h *********/
  12152. #endif
  12153. #ifndef __JUCE_PROCESS_JUCEHEADER__
  12154. /********* Start of inlined file: juce_Process.h *********/
  12155. #ifndef __JUCE_PROCESS_JUCEHEADER__
  12156. #define __JUCE_PROCESS_JUCEHEADER__
  12157. /** Represents the current executable's process.
  12158. This contains methods for controlling the current application at the
  12159. process-level.
  12160. @see Thread, JUCEApplication
  12161. */
  12162. class JUCE_API Process
  12163. {
  12164. public:
  12165. enum ProcessPriority
  12166. {
  12167. LowPriority = 0,
  12168. NormalPriority = 1,
  12169. HighPriority = 2,
  12170. RealtimePriority = 3
  12171. };
  12172. /** Changes the current process's priority.
  12173. @param priority the process priority, where
  12174. 0=low, 1=normal, 2=high, 3=realtime
  12175. */
  12176. static void setPriority (const ProcessPriority priority);
  12177. /** Kills the current process immediately.
  12178. This is an emergency process terminator that kills the application
  12179. immediately - it's intended only for use only when something goes
  12180. horribly wrong.
  12181. @see JUCEApplication::quit
  12182. */
  12183. static void terminate();
  12184. /** Returns true if this application process is the one that the user is
  12185. currently using.
  12186. */
  12187. static bool isForegroundProcess();
  12188. /** Raises the current process's privilege level.
  12189. Does nothing if this isn't supported by the current OS, or if process
  12190. privilege level is fixed.
  12191. */
  12192. static void raisePrivilege();
  12193. /** Lowers the current process's privilege level.
  12194. Does nothing if this isn't supported by the current OS, or if process
  12195. privilege level is fixed.
  12196. */
  12197. static void lowerPrivilege();
  12198. /** Returns true if this process is being hosted by a debugger.
  12199. */
  12200. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  12201. };
  12202. #endif // __JUCE_PROCESS_JUCEHEADER__
  12203. /********* End of inlined file: juce_Process.h *********/
  12204. #endif
  12205. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  12206. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  12207. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  12208. #define __JUCE_READWRITELOCK_JUCEHEADER__
  12209. /********* Start of inlined file: juce_WaitableEvent.h *********/
  12210. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  12211. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  12212. /**
  12213. Allows threads to wait for events triggered by other threads.
  12214. A thread can call wait() on a WaitableObject, and this will suspend the
  12215. calling thread until another thread wakes it up by calling the signal()
  12216. method.
  12217. */
  12218. class JUCE_API WaitableEvent
  12219. {
  12220. public:
  12221. /** Creates a WaitableEvent object. */
  12222. WaitableEvent() throw();
  12223. /** Destructor.
  12224. If other threads are waiting on this object when it gets deleted, this
  12225. can cause nasty errors, so be careful!
  12226. */
  12227. ~WaitableEvent() throw();
  12228. /** Suspends the calling thread until the event has been signalled.
  12229. This will wait until the object's signal() method is called by another thread,
  12230. or until the timeout expires.
  12231. After the event has been signalled, this method will return true and reset
  12232. the event.
  12233. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  12234. value will cause it to wait forever.
  12235. @returns true if the object has been signalled, false if the timeout expires first.
  12236. @see signal, reset
  12237. */
  12238. bool wait (const int timeOutMilliseconds = -1) const throw();
  12239. /** Wakes up any threads that are currently waiting on this object.
  12240. If signal() is called when nothing is waiting, the next thread to call wait()
  12241. will return immediately and reset the signal.
  12242. @see wait, reset
  12243. */
  12244. void signal() const throw();
  12245. /** Resets the event to an unsignalled state.
  12246. If it's not already signalled, this does nothing.
  12247. */
  12248. void reset() const throw();
  12249. juce_UseDebuggingNewOperator
  12250. private:
  12251. void* internal;
  12252. WaitableEvent (const WaitableEvent&);
  12253. const WaitableEvent& operator= (const WaitableEvent&);
  12254. };
  12255. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  12256. /********* End of inlined file: juce_WaitableEvent.h *********/
  12257. /********* Start of inlined file: juce_Thread.h *********/
  12258. #ifndef __JUCE_THREAD_JUCEHEADER__
  12259. #define __JUCE_THREAD_JUCEHEADER__
  12260. /**
  12261. Encapsulates a thread.
  12262. Subclasses derive from Thread and implement the run() method, in which they
  12263. do their business. The thread can then be started with the startThread() method
  12264. and controlled with various other methods.
  12265. This class also contains some thread-related static methods, such
  12266. as sleep(), yield(), getCurrentThreadId() etc.
  12267. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  12268. MessageManagerLock
  12269. */
  12270. class JUCE_API Thread
  12271. {
  12272. public:
  12273. /**
  12274. Creates a thread.
  12275. When first created, the thread is not running. Use the startThread()
  12276. method to start it.
  12277. */
  12278. Thread (const String& threadName);
  12279. /** Destructor.
  12280. Deleting a Thread object that is running will only give the thread a
  12281. brief opportunity to stop itself cleanly, so it's recommended that you
  12282. should always call stopThread() with a decent timeout before deleting,
  12283. to avoid the thread being forcibly killed (which is a Bad Thing).
  12284. */
  12285. virtual ~Thread();
  12286. /** Must be implemented to perform the thread's actual code.
  12287. Remember that the thread must regularly check the threadShouldExit()
  12288. method whilst running, and if this returns true it should return from
  12289. the run() method as soon as possible to avoid being forcibly killed.
  12290. @see threadShouldExit, startThread
  12291. */
  12292. virtual void run() = 0;
  12293. // Thread control functions..
  12294. /** Starts the thread running.
  12295. This will start the thread's run() method.
  12296. (if it's already started, startThread() won't do anything).
  12297. @see stopThread
  12298. */
  12299. void startThread();
  12300. /** Starts the thread with a given priority.
  12301. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  12302. If the thread is already running, its priority will be changed.
  12303. @see startThread, setPriority
  12304. */
  12305. void startThread (const int priority);
  12306. /** Attempts to stop the thread running.
  12307. This method will cause the threadShouldExit() method to return true
  12308. and call notify() in case the thread is currently waiting.
  12309. Hopefully the thread will then respond to this by exiting cleanly, and
  12310. the stopThread method will wait for a given time-period for this to
  12311. happen.
  12312. If the thread is stuck and fails to respond after the time-out, it gets
  12313. forcibly killed, which is a very bad thing to happen, as it could still
  12314. be holding locks, etc. which are needed by other parts of your program.
  12315. @param timeOutMilliseconds The number of milliseconds to wait for the
  12316. thread to finish before killing it by force. A negative
  12317. value in here will wait forever.
  12318. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  12319. */
  12320. void stopThread (const int timeOutMilliseconds);
  12321. /** Returns true if the thread is currently active */
  12322. bool isThreadRunning() const;
  12323. /** Sets a flag to tell the thread it should stop.
  12324. Calling this means that the threadShouldExit() method will then return true.
  12325. The thread should be regularly checking this to see whether it should exit.
  12326. @see threadShouldExit
  12327. @see waitForThreadToExit
  12328. */
  12329. void signalThreadShouldExit();
  12330. /** Checks whether the thread has been told to stop running.
  12331. Threads need to check this regularly, and if it returns true, they should
  12332. return from their run() method at the first possible opportunity.
  12333. @see signalThreadShouldExit
  12334. */
  12335. inline bool threadShouldExit() const { return threadShouldExit_; }
  12336. /** Waits for the thread to stop.
  12337. This will waits until isThreadRunning() is false or until a timeout expires.
  12338. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  12339. is less than zero, it will wait forever.
  12340. @returns true if the thread exits, or false if the timeout expires first.
  12341. */
  12342. bool waitForThreadToExit (const int timeOutMilliseconds) const;
  12343. /** Changes the thread's priority.
  12344. May return false if for some reason the priority can't be changed.
  12345. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  12346. of 5 is normal.
  12347. */
  12348. bool setPriority (const int priority);
  12349. /** Changes the priority of the caller thread.
  12350. Similar to setPriority(), but this static method acts on the caller thread.
  12351. May return false if for some reason the priority can't be changed.
  12352. @see setPriority
  12353. */
  12354. static bool setCurrentThreadPriority (const int priority);
  12355. /** Sets the affinity mask for the thread.
  12356. This will only have an effect next time the thread is started - i.e. if the
  12357. thread is already running when called, it'll have no effect.
  12358. @see setCurrentThreadAffinityMask
  12359. */
  12360. void setAffinityMask (const uint32 affinityMask);
  12361. /** Changes the affinity mask for the caller thread.
  12362. This will change the affinity mask for the thread that calls this static method.
  12363. @see setAffinityMask
  12364. */
  12365. static void setCurrentThreadAffinityMask (const uint32 affinityMask);
  12366. // this can be called from any thread that needs to pause..
  12367. static void JUCE_CALLTYPE sleep (int milliseconds);
  12368. /** Yields the calling thread's current time-slot. */
  12369. static void JUCE_CALLTYPE yield();
  12370. /** Makes the thread wait for a notification.
  12371. This puts the thread to sleep until either the timeout period expires, or
  12372. another thread calls the notify() method to wake it up.
  12373. @returns true if the event has been signalled, false if the timeout expires.
  12374. */
  12375. bool wait (const int timeOutMilliseconds) const;
  12376. /** Wakes up the thread.
  12377. If the thread has called the wait() method, this will wake it up.
  12378. @see wait
  12379. */
  12380. void notify() const;
  12381. /** A value type used for thread IDs.
  12382. @see getCurrentThreadId(), getThreadId()
  12383. */
  12384. typedef void* ThreadID;
  12385. /** Returns an id that identifies the caller thread.
  12386. To find the ID of a particular thread object, use getThreadId().
  12387. @returns a unique identifier that identifies the calling thread.
  12388. @see getThreadId
  12389. */
  12390. static ThreadID getCurrentThreadId();
  12391. /** Finds the thread object that is currently running.
  12392. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  12393. object associated with them, so this will return 0.
  12394. */
  12395. static Thread* getCurrentThread();
  12396. /** Returns the ID of this thread.
  12397. That means the ID of this thread object - not of the thread that's calling the method.
  12398. This can change when the thread is started and stopped, and will be invalid if the
  12399. thread's not actually running.
  12400. @see getCurrentThreadId
  12401. */
  12402. ThreadID getThreadId() const { return threadId_; }
  12403. /** Returns the name of the thread.
  12404. This is the name that gets set in the constructor.
  12405. */
  12406. const String getThreadName() const { return threadName_; }
  12407. /** Returns the number of currently-running threads.
  12408. @returns the number of Thread objects known to be currently running.
  12409. @see stopAllThreads
  12410. */
  12411. static int getNumRunningThreads();
  12412. /** Tries to stop all currently-running threads.
  12413. This will attempt to stop all the threads known to be running at the moment.
  12414. */
  12415. static void stopAllThreads (const int timeoutInMillisecs);
  12416. juce_UseDebuggingNewOperator
  12417. private:
  12418. const String threadName_;
  12419. void* volatile threadHandle_;
  12420. CriticalSection startStopLock;
  12421. WaitableEvent startSuspensionEvent_, defaultEvent_;
  12422. int threadPriority_;
  12423. ThreadID threadId_;
  12424. uint32 affinityMask_;
  12425. bool volatile threadShouldExit_;
  12426. friend void JUCE_API juce_threadEntryPoint (void*);
  12427. static void threadEntryPoint (Thread* thread);
  12428. Thread (const Thread&);
  12429. const Thread& operator= (const Thread&);
  12430. };
  12431. #endif // __JUCE_THREAD_JUCEHEADER__
  12432. /********* End of inlined file: juce_Thread.h *********/
  12433. /**
  12434. A critical section that allows multiple simultaneous readers.
  12435. Features of this type of lock are:
  12436. - Multiple readers can hold the lock at the same time, but only one writer
  12437. can hold it at once.
  12438. - Writers trying to gain the lock will be blocked until all readers and writers
  12439. have released it
  12440. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  12441. blocked until the writer has obtained and released it
  12442. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  12443. there are no other readers
  12444. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  12445. - Recursive locking is supported.
  12446. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  12447. */
  12448. class JUCE_API ReadWriteLock
  12449. {
  12450. public:
  12451. /**
  12452. Creates a ReadWriteLock object.
  12453. */
  12454. ReadWriteLock() throw();
  12455. /** Destructor.
  12456. If the object is deleted whilst locked, any subsequent behaviour
  12457. is unpredictable.
  12458. */
  12459. ~ReadWriteLock() throw();
  12460. /** Locks this object for reading.
  12461. Multiple threads can simulaneously lock the object for reading, but if another
  12462. thread has it locked for writing, then this will block until it releases the
  12463. lock.
  12464. @see exitRead, ScopedReadLock
  12465. */
  12466. void enterRead() const throw();
  12467. /** Releases the read-lock.
  12468. If the caller thread hasn't got the lock, this can have unpredictable results.
  12469. If the enterRead() method has been called multiple times by the thread, each
  12470. call must be matched by a call to exitRead() before other threads will be allowed
  12471. to take over the lock.
  12472. @see enterRead, ScopedReadLock
  12473. */
  12474. void exitRead() const throw();
  12475. /** Locks this object for writing.
  12476. This will block until any other threads that have it locked for reading or
  12477. writing have released their lock.
  12478. @see exitWrite, ScopedWriteLock
  12479. */
  12480. void enterWrite() const throw();
  12481. /** Tries to lock this object for writing.
  12482. This is like enterWrite(), but doesn't block - it returns true if it manages
  12483. to obtain the lock.
  12484. @see enterWrite
  12485. */
  12486. bool tryEnterWrite() const throw();
  12487. /** Releases the write-lock.
  12488. If the caller thread hasn't got the lock, this can have unpredictable results.
  12489. If the enterWrite() method has been called multiple times by the thread, each
  12490. call must be matched by a call to exit() before other threads will be allowed
  12491. to take over the lock.
  12492. @see enterWrite, ScopedWriteLock
  12493. */
  12494. void exitWrite() const throw();
  12495. juce_UseDebuggingNewOperator
  12496. private:
  12497. CriticalSection accessLock;
  12498. WaitableEvent waitEvent;
  12499. mutable int numWaitingWriters, numWriters;
  12500. mutable Thread::ThreadID writerThreadId;
  12501. mutable Array <Thread::ThreadID> readerThreads;
  12502. ReadWriteLock (const ReadWriteLock&);
  12503. const ReadWriteLock& operator= (const ReadWriteLock&);
  12504. };
  12505. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  12506. /********* End of inlined file: juce_ReadWriteLock.h *********/
  12507. #endif
  12508. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  12509. #endif
  12510. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12511. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  12512. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12513. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12514. /**
  12515. Automatically locks and unlocks a ReadWriteLock object.
  12516. Use one of these as a local variable to control access to a ReadWriteLock.
  12517. e.g. @code
  12518. ReadWriteLock myLock;
  12519. for (;;)
  12520. {
  12521. const ScopedReadLock myScopedLock (myLock);
  12522. // myLock is now locked
  12523. ...do some stuff...
  12524. // myLock gets unlocked here.
  12525. }
  12526. @endcode
  12527. @see ReadWriteLock, ScopedWriteLock
  12528. */
  12529. class JUCE_API ScopedReadLock
  12530. {
  12531. public:
  12532. /** Creates a ScopedReadLock.
  12533. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  12534. when the ScopedReadLock object is deleted, the ReadWriteLock will
  12535. be unlocked.
  12536. Make sure this object is created and deleted by the same thread,
  12537. otherwise there are no guarantees what will happen! Best just to use it
  12538. as a local stack object, rather than creating one with the new() operator.
  12539. */
  12540. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  12541. /** Destructor.
  12542. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  12543. Make sure this object is created and deleted by the same thread,
  12544. otherwise there are no guarantees what will happen!
  12545. */
  12546. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  12547. private:
  12548. const ReadWriteLock& lock_;
  12549. ScopedReadLock (const ScopedReadLock&);
  12550. const ScopedReadLock& operator= (const ScopedReadLock&);
  12551. };
  12552. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12553. /********* End of inlined file: juce_ScopedReadLock.h *********/
  12554. #endif
  12555. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12556. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  12557. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12558. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12559. /**
  12560. Automatically tries to lock and unlock a CriticalSection object.
  12561. Use one of these as a local variable to control access to a CriticalSection.
  12562. e.g. @code
  12563. CriticalSection myCriticalSection;
  12564. for (;;)
  12565. {
  12566. const ScopedTryLock myScopedTryLock (myCriticalSection);
  12567. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  12568. // should test this with the isLocked() method before doing your thread-unsafe
  12569. // action..
  12570. if (myScopedTryLock.isLocked())
  12571. {
  12572. ...do some stuff...
  12573. }
  12574. else
  12575. {
  12576. ..our attempt at locking failed because another thread had already locked it..
  12577. }
  12578. // myCriticalSection gets unlocked here (if it was locked)
  12579. }
  12580. @endcode
  12581. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  12582. */
  12583. class JUCE_API ScopedTryLock
  12584. {
  12585. public:
  12586. /** Creates a ScopedTryLock.
  12587. As soon as it is created, this will try to lock the CriticalSection, and
  12588. when the ScopedTryLock object is deleted, the CriticalSection will
  12589. be unlocked if the lock was successful.
  12590. Make sure this object is created and deleted by the same thread,
  12591. otherwise there are no guarantees what will happen! Best just to use it
  12592. as a local stack object, rather than creating one with the new() operator.
  12593. */
  12594. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  12595. /** Destructor.
  12596. The CriticalSection will be unlocked (if locked) when the destructor is called.
  12597. Make sure this object is created and deleted by the same thread,
  12598. otherwise there are no guarantees what will happen!
  12599. */
  12600. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  12601. /** Lock state
  12602. @return True if the CriticalSection is locked.
  12603. */
  12604. bool isLocked() const throw() { return lockWasSuccessful; }
  12605. private:
  12606. const CriticalSection& lock_;
  12607. const bool lockWasSuccessful;
  12608. ScopedTryLock (const ScopedTryLock&);
  12609. const ScopedTryLock& operator= (const ScopedTryLock&);
  12610. };
  12611. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12612. /********* End of inlined file: juce_ScopedTryLock.h *********/
  12613. #endif
  12614. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12615. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  12616. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12617. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12618. /**
  12619. Automatically locks and unlocks a ReadWriteLock object.
  12620. Use one of these as a local variable to control access to a ReadWriteLock.
  12621. e.g. @code
  12622. ReadWriteLock myLock;
  12623. for (;;)
  12624. {
  12625. const ScopedWriteLock myScopedLock (myLock);
  12626. // myLock is now locked
  12627. ...do some stuff...
  12628. // myLock gets unlocked here.
  12629. }
  12630. @endcode
  12631. @see ReadWriteLock, ScopedReadLock
  12632. */
  12633. class JUCE_API ScopedWriteLock
  12634. {
  12635. public:
  12636. /** Creates a ScopedWriteLock.
  12637. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  12638. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  12639. be unlocked.
  12640. Make sure this object is created and deleted by the same thread,
  12641. otherwise there are no guarantees what will happen! Best just to use it
  12642. as a local stack object, rather than creating one with the new() operator.
  12643. */
  12644. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  12645. /** Destructor.
  12646. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  12647. Make sure this object is created and deleted by the same thread,
  12648. otherwise there are no guarantees what will happen!
  12649. */
  12650. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  12651. private:
  12652. const ReadWriteLock& lock_;
  12653. ScopedWriteLock (const ScopedWriteLock&);
  12654. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  12655. };
  12656. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12657. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  12658. #endif
  12659. #ifndef __JUCE_THREAD_JUCEHEADER__
  12660. #endif
  12661. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  12662. /********* Start of inlined file: juce_ThreadPool.h *********/
  12663. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  12664. #define __JUCE_THREADPOOL_JUCEHEADER__
  12665. class ThreadPool;
  12666. class ThreadPoolThread;
  12667. /**
  12668. A task that is executed by a ThreadPool object.
  12669. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  12670. its threads.
  12671. The runJob() method needs to be implemented to do the task, and if the code that
  12672. does the work takes a significant time to run, it must keep checking the shouldExit()
  12673. method to see if something is trying to interrupt the job. If shouldExit() returns
  12674. true, the runJob() method must return immediately.
  12675. @see ThreadPool, Thread
  12676. */
  12677. class JUCE_API ThreadPoolJob
  12678. {
  12679. public:
  12680. /** Creates a thread pool job object.
  12681. After creating your job, add it to a thread pool with ThreadPool::addJob().
  12682. */
  12683. ThreadPoolJob (const String& name);
  12684. /** Destructor. */
  12685. virtual ~ThreadPoolJob();
  12686. /** Returns the name of this job.
  12687. @see setJobName
  12688. */
  12689. const String getJobName() const;
  12690. /** Changes the job's name.
  12691. @see getJobName
  12692. */
  12693. void setJobName (const String& newName);
  12694. /** These are the values that can be returned by the runJob() method.
  12695. */
  12696. enum JobStatus
  12697. {
  12698. jobHasFinished = 0, /**< indicates that the job has finished and can be
  12699. removed from the pool. */
  12700. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  12701. should be automatically deleted by the pool. */
  12702. jobNeedsRunningAgain /**< indicates that the job would like to be called
  12703. again when a thread is free. */
  12704. };
  12705. /** Peforms the actual work that this job needs to do.
  12706. Your subclass must implement this method, in which is does its work.
  12707. If the code in this method takes a significant time to run, it must repeatedly check
  12708. the shouldExit() method to see if something is trying to interrupt the job.
  12709. If shouldExit() ever returns true, the runJob() method must return immediately.
  12710. If this method returns jobHasFinished, then the job will be removed from the pool
  12711. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  12712. pool and will get a chance to run again as soon as a thread is free.
  12713. @see shouldExit()
  12714. */
  12715. virtual JobStatus runJob() = 0;
  12716. /** Returns true if this job is currently running its runJob() method. */
  12717. bool isRunning() const { return isActive; }
  12718. /** Returns true if something is trying to interrupt this job and make it stop.
  12719. Your runJob() method must call this whenever it gets a chance, and if it ever
  12720. returns true, the runJob() method must return immediately.
  12721. @see signalJobShouldExit()
  12722. */
  12723. bool shouldExit() const { return shouldStop; }
  12724. /** Calling this will cause the shouldExit() method to return true, and the job
  12725. should (if it's been implemented correctly) stop as soon as possible.
  12726. @see shouldExit()
  12727. */
  12728. void signalJobShouldExit();
  12729. juce_UseDebuggingNewOperator
  12730. private:
  12731. friend class ThreadPool;
  12732. friend class ThreadPoolThread;
  12733. String jobName;
  12734. ThreadPool* pool;
  12735. bool shouldStop, isActive, shouldBeDeleted;
  12736. ThreadPoolJob (const ThreadPoolJob&);
  12737. const ThreadPoolJob& operator= (const ThreadPoolJob&);
  12738. };
  12739. /**
  12740. A set of threads that will run a list of jobs.
  12741. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  12742. will be called by the next pooled thread that becomes free.
  12743. @see ThreadPoolJob, Thread
  12744. */
  12745. class JUCE_API ThreadPool
  12746. {
  12747. public:
  12748. /** Creates a thread pool.
  12749. Once you've created a pool, you can give it some things to do with the addJob()
  12750. method.
  12751. @param numberOfThreads the maximum number of actual threads to run.
  12752. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  12753. until there are some jobs to run. If false, then
  12754. all the threads will be fired-up immediately so that
  12755. they're ready for action
  12756. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  12757. inactive for this length of time, they will automatically
  12758. be stopped until more jobs come along and they're needed
  12759. */
  12760. ThreadPool (const int numberOfThreads,
  12761. const bool startThreadsOnlyWhenNeeded = true,
  12762. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  12763. /** Destructor.
  12764. This will attempt to remove all the jobs before deleting, but if you want to
  12765. specify a timeout, you should call removeAllJobs() explicitly before deleting
  12766. the pool.
  12767. */
  12768. ~ThreadPool();
  12769. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  12770. for some kind of operation.
  12771. @see ThreadPool::removeAllJobs
  12772. */
  12773. class JUCE_API JobSelector
  12774. {
  12775. public:
  12776. virtual ~JobSelector() {}
  12777. /** Should return true if the specified thread matches your criteria for whatever
  12778. operation that this object is being used for.
  12779. Any implementation of this method must be extremely fast and thread-safe!
  12780. */
  12781. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  12782. };
  12783. /** Adds a job to the queue.
  12784. Once a job has been added, then the next time a thread is free, it will run
  12785. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  12786. runJob() method, the pool will either remove the job from the pool or add it to
  12787. the back of the queue to be run again.
  12788. */
  12789. void addJob (ThreadPoolJob* const job);
  12790. /** Tries to remove a job from the pool.
  12791. If the job isn't yet running, this will simply remove it. If it is running, it
  12792. will wait for it to finish.
  12793. If the timeout period expires before the job finishes running, then the job will be
  12794. left in the pool and this will return false. It returns true if the job is sucessfully
  12795. stopped and removed.
  12796. @param job the job to remove
  12797. @param interruptIfRunning if true, then if the job is currently busy, its
  12798. ThreadPoolJob::signalJobShouldExit() method will be called to try
  12799. to interrupt it. If false, then if the job will be allowed to run
  12800. until it stops normally (or the timeout expires)
  12801. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  12802. before giving up and returning false
  12803. */
  12804. bool removeJob (ThreadPoolJob* const job,
  12805. const bool interruptIfRunning,
  12806. const int timeOutMilliseconds);
  12807. /** Tries to remove all jobs from the pool.
  12808. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  12809. methods called to try to interrupt them
  12810. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  12811. before giving up and returning false
  12812. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  12813. they will simply be removed from the pool. Jobs that are already running when
  12814. this method is called can choose whether they should be deleted by
  12815. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  12816. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  12817. jobs should be removed. If it is zero, all jobs are removed
  12818. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  12819. expires while waiting for one or more jobs to stop
  12820. */
  12821. bool removeAllJobs (const bool interruptRunningJobs,
  12822. const int timeOutMilliseconds,
  12823. const bool deleteInactiveJobs = false,
  12824. JobSelector* selectedJobsToRemove = 0);
  12825. /** Returns the number of jobs currently running or queued.
  12826. */
  12827. int getNumJobs() const;
  12828. /** Returns one of the jobs in the queue.
  12829. Note that this can be a very volatile list as jobs might be continuously getting shifted
  12830. around in the list, and this method may return 0 if the index is currently out-of-range.
  12831. */
  12832. ThreadPoolJob* getJob (const int index) const;
  12833. /** Returns true if the given job is currently queued or running.
  12834. @see isJobRunning()
  12835. */
  12836. bool contains (const ThreadPoolJob* const job) const;
  12837. /** Returns true if the given job is currently being run by a thread.
  12838. */
  12839. bool isJobRunning (const ThreadPoolJob* const job) const;
  12840. /** Waits until a job has finished running and has been removed from the pool.
  12841. This will wait until the job is no longer in the pool - i.e. until its
  12842. runJob() method returns ThreadPoolJob::jobHasFinished.
  12843. If the timeout period expires before the job finishes, this will return false;
  12844. it returns true if the job has finished successfully.
  12845. */
  12846. bool waitForJobToFinish (const ThreadPoolJob* const job,
  12847. const int timeOutMilliseconds) const;
  12848. /** Returns a list of the names of all the jobs currently running or queued.
  12849. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  12850. */
  12851. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  12852. /** Changes the priority of all the threads.
  12853. This will call Thread::setPriority() for each thread in the pool.
  12854. May return false if for some reason the priority can't be changed.
  12855. */
  12856. bool setThreadPriorities (const int newPriority);
  12857. juce_UseDebuggingNewOperator
  12858. private:
  12859. const int numThreads, threadStopTimeout;
  12860. int priority;
  12861. HeapBlock <Thread*> threads;
  12862. VoidArray jobs;
  12863. CriticalSection lock;
  12864. uint32 lastJobEndTime;
  12865. WaitableEvent jobFinishedSignal;
  12866. friend class ThreadPoolThread;
  12867. bool runNextJob();
  12868. ThreadPool (const ThreadPool&);
  12869. const ThreadPool& operator= (const ThreadPool&);
  12870. };
  12871. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  12872. /********* End of inlined file: juce_ThreadPool.h *********/
  12873. #endif
  12874. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12875. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  12876. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12877. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12878. /**
  12879. Used by the TimeSliceThread class.
  12880. To register your class with a TimeSliceThread, derive from this class and
  12881. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  12882. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  12883. deleting your client!
  12884. @see TimeSliceThread
  12885. */
  12886. class JUCE_API TimeSliceClient
  12887. {
  12888. public:
  12889. /** Destructor. */
  12890. virtual ~TimeSliceClient() {}
  12891. /** Called back by a TimeSliceThread.
  12892. When you register this class with it, a TimeSliceThread will repeatedly call
  12893. this method.
  12894. The implementation of this method should use its time-slice to do something that's
  12895. quick - never block for longer than absolutely necessary.
  12896. @returns Your method should return true if it needs more time, or false if it's
  12897. not too busy and doesn't need calling back urgently. If all the thread's
  12898. clients indicate that they're not busy, then it'll save CPU by sleeping for
  12899. up to half a second in between callbacks. You can force the TimeSliceThread
  12900. to wake up and poll again immediately by calling its notify() method.
  12901. */
  12902. virtual bool useTimeSlice() = 0;
  12903. };
  12904. /**
  12905. A thread that keeps a list of clients, and calls each one in turn, giving them
  12906. all a chance to run some sort of short task.
  12907. @see TimeSliceClient, Thread
  12908. */
  12909. class JUCE_API TimeSliceThread : public Thread
  12910. {
  12911. public:
  12912. /**
  12913. Creates a TimeSliceThread.
  12914. When first created, the thread is not running. Use the startThread()
  12915. method to start it.
  12916. */
  12917. TimeSliceThread (const String& threadName);
  12918. /** Destructor.
  12919. Deleting a Thread object that is running will only give the thread a
  12920. brief opportunity to stop itself cleanly, so it's recommended that you
  12921. should always call stopThread() with a decent timeout before deleting,
  12922. to avoid the thread being forcibly killed (which is a Bad Thing).
  12923. */
  12924. ~TimeSliceThread();
  12925. /** Adds a client to the list.
  12926. The client's callbacks will start immediately (possibly before the method
  12927. has returned).
  12928. */
  12929. void addTimeSliceClient (TimeSliceClient* const client);
  12930. /** Removes a client from the list.
  12931. This method will make sure that all callbacks to the client have completely
  12932. finished before the method returns.
  12933. */
  12934. void removeTimeSliceClient (TimeSliceClient* const client);
  12935. /** Returns the number of registered clients. */
  12936. int getNumClients() const;
  12937. /** Returns one of the registered clients. */
  12938. TimeSliceClient* getClient (const int index) const;
  12939. /** @internal */
  12940. void run();
  12941. juce_UseDebuggingNewOperator
  12942. private:
  12943. CriticalSection callbackLock, listLock;
  12944. Array <TimeSliceClient*> clients;
  12945. int index;
  12946. TimeSliceClient* clientBeingCalled;
  12947. bool clientsChanged;
  12948. TimeSliceThread (const TimeSliceThread&);
  12949. const TimeSliceThread& operator= (const TimeSliceThread&);
  12950. };
  12951. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12952. /********* End of inlined file: juce_TimeSliceThread.h *********/
  12953. #endif
  12954. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  12955. #endif
  12956. #endif
  12957. /********* End of inlined file: juce_core_includes.h *********/
  12958. // if you're compiling a command-line app, you might want to just include the core headers,
  12959. // so you can set this macro before including juce.h
  12960. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12961. /********* Start of inlined file: juce_app_includes.h *********/
  12962. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  12963. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  12964. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  12965. /********* Start of inlined file: juce_Application.h *********/
  12966. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  12967. #define __JUCE_APPLICATION_JUCEHEADER__
  12968. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  12969. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  12970. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  12971. /********* Start of inlined file: juce_Component.h *********/
  12972. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  12973. #define __JUCE_COMPONENT_JUCEHEADER__
  12974. /********* Start of inlined file: juce_MouseCursor.h *********/
  12975. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  12976. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  12977. class Image;
  12978. class SharedMouseCursorInternal;
  12979. class ComponentPeer;
  12980. class Component;
  12981. /**
  12982. Represents a mouse cursor image.
  12983. This object can either be used to represent one of the standard mouse
  12984. cursor shapes, or a custom one generated from an image.
  12985. */
  12986. class JUCE_API MouseCursor
  12987. {
  12988. public:
  12989. /** The set of available standard mouse cursors. */
  12990. enum StandardCursorType
  12991. {
  12992. NoCursor = 0, /**< An invisible cursor. */
  12993. NormalCursor, /**< The stardard arrow cursor. */
  12994. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  12995. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  12996. CrosshairCursor, /**< A pair of crosshairs. */
  12997. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  12998. that you're dragging a copy of something. */
  12999. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  13000. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  13001. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  13002. UpDownResizeCursor, /**< an arrow pointing up and down. */
  13003. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  13004. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  13005. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  13006. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  13007. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  13008. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  13009. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  13010. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  13011. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  13012. };
  13013. /** Creates the standard arrow cursor. */
  13014. MouseCursor() throw();
  13015. /** Creates one of the standard mouse cursor */
  13016. MouseCursor (const StandardCursorType type) throw();
  13017. /** Creates a custom cursor from an image.
  13018. @param image the image to use for the cursor - if this is bigger than the
  13019. system can manage, it might get scaled down first, and might
  13020. also have to be turned to black-and-white if it can't do colour
  13021. cursors.
  13022. @param hotSpotX the x position of the cursor's hotspot within the image
  13023. @param hotSpotY the y position of the cursor's hotspot within the image
  13024. */
  13025. MouseCursor (const Image& image,
  13026. const int hotSpotX,
  13027. const int hotSpotY) throw();
  13028. /** Creates a copy of another cursor object. */
  13029. MouseCursor (const MouseCursor& other) throw();
  13030. /** Copies this cursor from another object. */
  13031. const MouseCursor& operator= (const MouseCursor& other) throw();
  13032. /** Destructor. */
  13033. ~MouseCursor() throw();
  13034. /** Checks whether two mouse cursors are the same.
  13035. For custom cursors, two cursors created from the same image won't be
  13036. recognised as the same, only MouseCursor objects that have been
  13037. copied from the same object.
  13038. */
  13039. bool operator== (const MouseCursor& other) const throw();
  13040. /** Checks whether two mouse cursors are the same.
  13041. For custom cursors, two cursors created from the same image won't be
  13042. recognised as the same, only MouseCursor objects that have been
  13043. copied from the same object.
  13044. */
  13045. bool operator!= (const MouseCursor& other) const throw();
  13046. /** Makes the system show its default 'busy' cursor.
  13047. This will turn the system cursor to an hourglass or spinning beachball
  13048. until the next time the mouse is moved, or hideWaitCursor() is called.
  13049. This is handy if the message loop is about to block for a couple of
  13050. seconds while busy and you want to give the user feedback about this.
  13051. @see MessageManager::setTimeBeforeShowingWaitCursor
  13052. */
  13053. static void showWaitCursor() throw();
  13054. /** If showWaitCursor has been called, this will return the mouse to its
  13055. normal state.
  13056. This will look at what component is under the mouse, and update the
  13057. cursor to be the correct one for that component.
  13058. @see showWaitCursor
  13059. */
  13060. static void hideWaitCursor() throw();
  13061. juce_UseDebuggingNewOperator
  13062. private:
  13063. ReferenceCountedObjectPtr <SharedMouseCursorInternal> cursorHandle;
  13064. friend class Component;
  13065. void showInWindow (ComponentPeer* window) const throw();
  13066. void showInAllWindows() const throw();
  13067. void* getHandle() const throw();
  13068. };
  13069. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  13070. /********* End of inlined file: juce_MouseCursor.h *********/
  13071. /********* Start of inlined file: juce_MouseListener.h *********/
  13072. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  13073. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  13074. /********* Start of inlined file: juce_MouseEvent.h *********/
  13075. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  13076. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  13077. class Component;
  13078. /********* Start of inlined file: juce_ModifierKeys.h *********/
  13079. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  13080. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  13081. /**
  13082. Represents the state of the mouse buttons and modifier keys.
  13083. This is used both by mouse events and by KeyPress objects to describe
  13084. the state of keys such as shift, control, alt, etc.
  13085. @see KeyPress, MouseEvent::mods
  13086. */
  13087. class JUCE_API ModifierKeys
  13088. {
  13089. public:
  13090. /** Creates a ModifierKeys object from a raw set of flags.
  13091. @param flags to represent the keys that are down
  13092. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  13093. rightButtonModifier, commandModifier, popupMenuClickModifier
  13094. */
  13095. ModifierKeys (const int flags = 0) throw();
  13096. /** Creates a copy of another object. */
  13097. ModifierKeys (const ModifierKeys& other) throw();
  13098. /** Copies this object from another one. */
  13099. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  13100. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  13101. This is a platform-agnostic way of checking for the operating system's
  13102. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  13103. Windows/Linux, it's actually checking for the CTRL key.
  13104. */
  13105. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  13106. /** Checks whether the user is trying to launch a pop-up menu.
  13107. This checks for platform-specific modifiers that might indicate that the user
  13108. is following the operating system's normal method of showing a pop-up menu.
  13109. So on Windows/Linux, this method is really testing for a right-click.
  13110. On the Mac, it tests for either the CTRL key being down, or a right-click.
  13111. */
  13112. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  13113. /** Checks whether the flag is set for the left mouse-button. */
  13114. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  13115. /** Checks whether the flag is set for the right mouse-button.
  13116. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  13117. this is platform-independent (and makes your code more explanatory too).
  13118. */
  13119. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  13120. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  13121. /** Tests for any of the mouse-button flags. */
  13122. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  13123. /** Tests for any of the modifier key flags. */
  13124. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  13125. /** Checks whether the shift key's flag is set. */
  13126. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  13127. /** Checks whether the CTRL key's flag is set.
  13128. Remember that it's better to use the platform-agnostic routines to test for command-key and
  13129. popup-menu modifiers.
  13130. @see isCommandDown, isPopupMenu
  13131. */
  13132. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  13133. /** Checks whether the shift key's flag is set. */
  13134. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  13135. /** Flags that represent the different keys. */
  13136. enum Flags
  13137. {
  13138. /** Shift key flag. */
  13139. shiftModifier = 1,
  13140. /** CTRL key flag. */
  13141. ctrlModifier = 2,
  13142. /** ALT key flag. */
  13143. altModifier = 4,
  13144. /** Left mouse button flag. */
  13145. leftButtonModifier = 16,
  13146. /** Right mouse button flag. */
  13147. rightButtonModifier = 32,
  13148. /** Middle mouse button flag. */
  13149. middleButtonModifier = 64,
  13150. #if JUCE_MAC
  13151. /** Command key flag - on windows this is the same as the CTRL key flag. */
  13152. commandModifier = 8,
  13153. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  13154. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  13155. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  13156. #else
  13157. /** Command key flag - on windows this is the same as the CTRL key flag. */
  13158. commandModifier = ctrlModifier,
  13159. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  13160. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  13161. popupMenuClickModifier = rightButtonModifier,
  13162. #endif
  13163. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  13164. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  13165. /** Represents a combination of all the mouse buttons at once. */
  13166. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  13167. };
  13168. /** Returns the raw flags for direct testing. */
  13169. inline int getRawFlags() const throw() { return flags; }
  13170. /** Tests a combination of flags and returns true if any of them are set. */
  13171. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  13172. /** Creates a ModifierKeys object to represent the last-known state of the
  13173. keyboard and mouse buttons.
  13174. @see getCurrentModifiersRealtime
  13175. */
  13176. static const ModifierKeys getCurrentModifiers() throw();
  13177. /** Creates a ModifierKeys object to represent the current state of the
  13178. keyboard and mouse buttons.
  13179. This isn't often needed and isn't recommended, but will actively check all the
  13180. mouse and key states rather than just returning their last-known state like
  13181. getCurrentModifiers() does.
  13182. This is only needed in special circumstances for up-to-date modifier information
  13183. at times when the app's event loop isn't running normally.
  13184. */
  13185. static const ModifierKeys getCurrentModifiersRealtime() throw();
  13186. private:
  13187. int flags;
  13188. static int currentModifierFlags;
  13189. friend class ComponentPeer;
  13190. static void updateCurrentModifiers() throw();
  13191. };
  13192. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  13193. /********* End of inlined file: juce_ModifierKeys.h *********/
  13194. /**
  13195. Contains position and status information about a mouse event.
  13196. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  13197. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  13198. */
  13199. class JUCE_API MouseEvent
  13200. {
  13201. public:
  13202. /** Creates a MouseEvent.
  13203. Normally an application will never need to use this.
  13204. @param x the x position of the mouse, relative to the component that is passed-in
  13205. @param y the y position of the mouse, relative to the component that is passed-in
  13206. @param modifiers the key modifiers at the time of the event
  13207. @param originator the component that the mouse event applies to
  13208. @param eventTime the time the event happened
  13209. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  13210. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  13211. the same as the current mouse-x position.
  13212. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  13213. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  13214. the same as the current mouse-y position.
  13215. @param mouseDownTime the time at which the corresponding mouse-down event happened
  13216. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  13217. the same as the current mouse-event time.
  13218. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  13219. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  13220. */
  13221. MouseEvent (const int x, const int y,
  13222. const ModifierKeys& modifiers,
  13223. Component* const originator,
  13224. const Time& eventTime,
  13225. const int mouseDownX,
  13226. const int mouseDownY,
  13227. const Time& mouseDownTime,
  13228. const int numberOfClicks,
  13229. const bool mouseWasDragged) throw();
  13230. /** Destructor. */
  13231. ~MouseEvent() throw();
  13232. /** The x-position of the mouse when the event occurred.
  13233. This value is relative to the top-left of the component to which the
  13234. event applies (as indicated by the MouseEvent::eventComponent field).
  13235. */
  13236. int x;
  13237. /** The y-position of the mouse when the event occurred.
  13238. This value is relative to the top-left of the component to which the
  13239. event applies (as indicated by the MouseEvent::eventComponent field).
  13240. */
  13241. int y;
  13242. /** The key modifiers associated with the event.
  13243. This will let you find out which mouse buttons were down, as well as which
  13244. modifier keys were held down.
  13245. When used for mouse-up events, this will indicate the state of the mouse buttons
  13246. just before they were released, so that you can tell which button they let go of.
  13247. */
  13248. ModifierKeys mods;
  13249. /** The component that this event applies to.
  13250. This is usually the component that the mouse was over at the time, but for mouse-drag
  13251. events the mouse could actually be over a different component and the events are
  13252. still sent to the component that the button was originally pressed on.
  13253. The x and y member variables are relative to this component's position.
  13254. If you use getEventRelativeTo() to retarget this object to be relative to a different
  13255. component, this pointer will be updated, but originalComponent remains unchanged.
  13256. @see originalComponent
  13257. */
  13258. Component* eventComponent;
  13259. /** The component that the event first occurred on.
  13260. If you use getEventRelativeTo() to retarget this object to be relative to a different
  13261. component, this value remains unchanged to indicate the first component that received it.
  13262. @see eventComponent
  13263. */
  13264. Component* originalComponent;
  13265. /** The time that this mouse-event occurred.
  13266. */
  13267. Time eventTime;
  13268. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  13269. The co-ordinate is relative to the component specified in MouseEvent::component.
  13270. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  13271. */
  13272. int getMouseDownX() const throw();
  13273. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  13274. The co-ordinate is relative to the component specified in MouseEvent::component.
  13275. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  13276. */
  13277. int getMouseDownY() const throw();
  13278. /** Returns the straight-line distance between where the mouse is now and where it
  13279. was the last time the button was pressed.
  13280. This is quite handy for things like deciding whether the user has moved far enough
  13281. for it to be considered a drag operation.
  13282. @see getDistanceFromDragStartX
  13283. */
  13284. int getDistanceFromDragStart() const throw();
  13285. /** Returns the difference between the mouse's current x postion and where it was
  13286. when the button was last pressed.
  13287. @see getDistanceFromDragStart
  13288. */
  13289. int getDistanceFromDragStartX() const throw();
  13290. /** Returns the difference between the mouse's current y postion and where it was
  13291. when the button was last pressed.
  13292. @see getDistanceFromDragStart
  13293. */
  13294. int getDistanceFromDragStartY() const throw();
  13295. /** Returns true if the mouse has just been clicked.
  13296. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  13297. the user has dragged the mouse more than a few pixels from the place where the
  13298. mouse-down occurred.
  13299. Once they have dragged it far enough for this method to return false, it will continue
  13300. to return false until the mouse-up, even if they move the mouse back to the same
  13301. position where they originally pressed it. This means that it's very handy for
  13302. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  13303. callback to ignore any small movements they might make while clicking.
  13304. @returns true if the mouse wasn't dragged by more than a few pixels between
  13305. the last time the button was pressed and released.
  13306. */
  13307. bool mouseWasClicked() const throw();
  13308. /** For a click event, the number of times the mouse was clicked in succession.
  13309. So for example a double-click event will return 2, a triple-click 3, etc.
  13310. */
  13311. int getNumberOfClicks() const throw() { return numberOfClicks; }
  13312. /** Returns the time that the mouse button has been held down for.
  13313. If called from a mouseDrag or mouseUp callback, this will return the
  13314. number of milliseconds since the corresponding mouseDown event occurred.
  13315. If called in other contexts, e.g. a mouseMove, then the returned value
  13316. may be 0 or an undefined value.
  13317. */
  13318. int getLengthOfMousePress() const throw();
  13319. /** Returns the mouse x position of this event, in global screen co-ordinates.
  13320. The co-ordinates are relative to the top-left of the main monitor.
  13321. @see getMouseDownScreenX, Desktop::getMousePosition
  13322. */
  13323. int getScreenX() const throw();
  13324. /** Returns the mouse y position of this event, in global screen co-ordinates.
  13325. The co-ordinates are relative to the top-left of the main monitor.
  13326. @see getMouseDownScreenY, Desktop::getMousePosition
  13327. */
  13328. int getScreenY() const throw();
  13329. /** Returns the x co-ordinate at which the mouse button was last pressed.
  13330. The co-ordinates are relative to the top-left of the main monitor.
  13331. @see getScreenX, Desktop::getMousePosition
  13332. */
  13333. int getMouseDownScreenX() const throw();
  13334. /** Returns the y co-ordinate at which the mouse button was last pressed.
  13335. The co-ordinates are relative to the top-left of the main monitor.
  13336. @see getScreenY, Desktop::getMousePosition
  13337. */
  13338. int getMouseDownScreenY() const throw();
  13339. /** Creates a version of this event that is relative to a different component.
  13340. The x and y positions of the event that is returned will have been
  13341. adjusted to be relative to the new component.
  13342. */
  13343. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  13344. /** Changes the application-wide setting for the double-click time limit.
  13345. This is the maximum length of time between mouse-clicks for it to be
  13346. considered a double-click. It's used by the Component class.
  13347. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  13348. */
  13349. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  13350. /** Returns the application-wide setting for the double-click time limit.
  13351. This is the maximum length of time between mouse-clicks for it to be
  13352. considered a double-click. It's used by the Component class.
  13353. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  13354. */
  13355. static int getDoubleClickTimeout() throw();
  13356. juce_UseDebuggingNewOperator
  13357. private:
  13358. int mouseDownX, mouseDownY;
  13359. Time mouseDownTime;
  13360. int numberOfClicks;
  13361. bool wasMovedSinceMouseDown;
  13362. };
  13363. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  13364. /********* End of inlined file: juce_MouseEvent.h *********/
  13365. /**
  13366. A MouseListener can be registered with a component to receive callbacks
  13367. about mouse events that happen to that component.
  13368. @see Component::addMouseListener, Component::removeMouseListener
  13369. */
  13370. class JUCE_API MouseListener
  13371. {
  13372. public:
  13373. /** Destructor. */
  13374. virtual ~MouseListener() {}
  13375. /** Called when the mouse moves inside a component.
  13376. If the mouse button isn't pressed and the mouse moves over a component,
  13377. this will be called to let the component react to this.
  13378. A component will always get a mouseEnter callback before a mouseMove.
  13379. @param e details about the position and status of the mouse event, including
  13380. the source component in which it occurred
  13381. @see mouseEnter, mouseExit, mouseDrag, contains
  13382. */
  13383. virtual void mouseMove (const MouseEvent& e);
  13384. /** Called when the mouse first enters a component.
  13385. If the mouse button isn't pressed and the mouse moves into a component,
  13386. this will be called to let the component react to this.
  13387. When the mouse button is pressed and held down while being moved in
  13388. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  13389. mouseDrag messages are sent to the component that the mouse was originally
  13390. clicked on, until the button is released.
  13391. @param e details about the position and status of the mouse event, including
  13392. the source component in which it occurred
  13393. @see mouseExit, mouseDrag, mouseMove, contains
  13394. */
  13395. virtual void mouseEnter (const MouseEvent& e);
  13396. /** Called when the mouse moves out of a component.
  13397. This will be called when the mouse moves off the edge of this
  13398. component.
  13399. If the mouse button was pressed, and it was then dragged off the
  13400. edge of the component and released, then this callback will happen
  13401. when the button is released, after the mouseUp callback.
  13402. @param e details about the position and status of the mouse event, including
  13403. the source component in which it occurred
  13404. @see mouseEnter, mouseDrag, mouseMove, contains
  13405. */
  13406. virtual void mouseExit (const MouseEvent& e);
  13407. /** Called when a mouse button is pressed.
  13408. The MouseEvent object passed in contains lots of methods for finding out
  13409. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  13410. were held down at the time.
  13411. Once a button is held down, the mouseDrag method will be called when the
  13412. mouse moves, until the button is released.
  13413. @param e details about the position and status of the mouse event, including
  13414. the source component in which it occurred
  13415. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  13416. */
  13417. virtual void mouseDown (const MouseEvent& e);
  13418. /** Called when the mouse is moved while a button is held down.
  13419. When a mouse button is pressed inside a component, that component
  13420. receives mouseDrag callbacks each time the mouse moves, even if the
  13421. mouse strays outside the component's bounds.
  13422. @param e details about the position and status of the mouse event, including
  13423. the source component in which it occurred
  13424. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  13425. */
  13426. virtual void mouseDrag (const MouseEvent& e);
  13427. /** Called when a mouse button is released.
  13428. A mouseUp callback is sent to the component in which a button was pressed
  13429. even if the mouse is actually over a different component when the
  13430. button is released.
  13431. The MouseEvent object passed in contains lots of methods for finding out
  13432. which buttons were down just before they were released.
  13433. @param e details about the position and status of the mouse event, including
  13434. the source component in which it occurred
  13435. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  13436. */
  13437. virtual void mouseUp (const MouseEvent& e);
  13438. /** Called when a mouse button has been double-clicked on a component.
  13439. The MouseEvent object passed in contains lots of methods for finding out
  13440. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  13441. were held down at the time.
  13442. @param e details about the position and status of the mouse event, including
  13443. the source component in which it occurred
  13444. @see mouseDown, mouseUp
  13445. */
  13446. virtual void mouseDoubleClick (const MouseEvent& e);
  13447. /** Called when the mouse-wheel is moved.
  13448. This callback is sent to the component that the mouse is over when the
  13449. wheel is moved.
  13450. If not overridden, the component will forward this message to its parent, so
  13451. that parent components can collect mouse-wheel messages that happen to
  13452. child components which aren't interested in them.
  13453. @param e details about the position and status of the mouse event, including
  13454. the source component in which it occurred
  13455. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  13456. value means the wheel has been pushed to the right, negative means it
  13457. was pushed to the left
  13458. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  13459. value means the wheel has been pushed upwards, negative means it
  13460. was pushed downwards
  13461. */
  13462. virtual void mouseWheelMove (const MouseEvent& e,
  13463. float wheelIncrementX,
  13464. float wheelIncrementY);
  13465. };
  13466. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  13467. /********* End of inlined file: juce_MouseListener.h *********/
  13468. /********* Start of inlined file: juce_ComponentListener.h *********/
  13469. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  13470. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  13471. class Component;
  13472. /**
  13473. Gets informed about changes to a component's hierarchy or position.
  13474. To monitor a component for changes, register a subclass of ComponentListener
  13475. with the component using Component::addComponentListener().
  13476. Be sure to deregister listeners before you delete them!
  13477. @see Component::addComponentListener, Component::removeComponentListener
  13478. */
  13479. class JUCE_API ComponentListener
  13480. {
  13481. public:
  13482. /** Destructor. */
  13483. virtual ~ComponentListener() {}
  13484. /** Called when the component's position or size changes.
  13485. @param component the component that was moved or resized
  13486. @param wasMoved true if the component's top-left corner has just moved
  13487. @param wasResized true if the component's width or height has just changed
  13488. @see Component::setBounds, Component::resized, Component::moved
  13489. */
  13490. virtual void componentMovedOrResized (Component& component,
  13491. bool wasMoved,
  13492. bool wasResized);
  13493. /** Called when the component is brought to the top of the z-order.
  13494. @param component the component that was moved
  13495. @see Component::toFront, Component::broughtToFront
  13496. */
  13497. virtual void componentBroughtToFront (Component& component);
  13498. /** Called when the component is made visible or invisible.
  13499. @param component the component that changed
  13500. @see Component::setVisible
  13501. */
  13502. virtual void componentVisibilityChanged (Component& component);
  13503. /** Called when the component has children added or removed.
  13504. @param component the component whose children were changed
  13505. @see Component::childrenChanged, Component::addChildComponent,
  13506. Component::removeChildComponent
  13507. */
  13508. virtual void componentChildrenChanged (Component& component);
  13509. /** Called to indicate that the component's parents have changed.
  13510. When a component is added or removed from its parent, all of its children
  13511. will produce this notification (recursively - so all children of its
  13512. children will also be called as well).
  13513. @param component the component that this listener is registered with
  13514. @see Component::parentHierarchyChanged
  13515. */
  13516. virtual void componentParentHierarchyChanged (Component& component);
  13517. /** Called when the component's name is changed.
  13518. @see Component::setName, Component::getName
  13519. */
  13520. virtual void componentNameChanged (Component& component);
  13521. };
  13522. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  13523. /********* End of inlined file: juce_ComponentListener.h *********/
  13524. /********* Start of inlined file: juce_KeyListener.h *********/
  13525. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  13526. #define __JUCE_KEYLISTENER_JUCEHEADER__
  13527. /********* Start of inlined file: juce_KeyPress.h *********/
  13528. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  13529. #define __JUCE_KEYPRESS_JUCEHEADER__
  13530. /**
  13531. Represents a key press, including any modifier keys that are needed.
  13532. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  13533. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  13534. */
  13535. class JUCE_API KeyPress
  13536. {
  13537. public:
  13538. /** Creates an (invalid) KeyPress.
  13539. @see isValid
  13540. */
  13541. KeyPress() throw();
  13542. /** Creates a KeyPress for a key and some modifiers.
  13543. e.g.
  13544. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  13545. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  13546. @param keyCode a code that represents the key - this value must be
  13547. one of special constants listed in this class, or an
  13548. 8-bit character code such as a letter (case is ignored),
  13549. digit or a simple key like "," or ".". Note that this
  13550. isn't the same as the textCharacter parameter, so for example
  13551. a keyCode of 'a' and a shift-key modifier should have a
  13552. textCharacter value of 'A'.
  13553. @param modifiers the modifiers to associate with the keystroke
  13554. @param textCharacter the character that would be printed if someone typed
  13555. this keypress into a text editor. This value may be
  13556. null if the keypress is a non-printing character
  13557. @see getKeyCode, isKeyCode, getModifiers
  13558. */
  13559. KeyPress (const int keyCode,
  13560. const ModifierKeys& modifiers,
  13561. const juce_wchar textCharacter) throw();
  13562. /** Creates a keypress with a keyCode but no modifiers or text character.
  13563. */
  13564. KeyPress (const int keyCode) throw();
  13565. /** Creates a copy of another KeyPress. */
  13566. KeyPress (const KeyPress& other) throw();
  13567. /** Copies this KeyPress from another one. */
  13568. const KeyPress& operator= (const KeyPress& other) throw();
  13569. /** Compares two KeyPress objects. */
  13570. bool operator== (const KeyPress& other) const throw();
  13571. /** Compares two KeyPress objects. */
  13572. bool operator!= (const KeyPress& other) const throw();
  13573. /** Returns true if this is a valid KeyPress.
  13574. A null keypress can be created by the default constructor, in case it's
  13575. needed.
  13576. */
  13577. bool isValid() const throw() { return keyCode != 0; }
  13578. /** Returns the key code itself.
  13579. This will either be one of the special constants defined in this class,
  13580. or an 8-bit character code.
  13581. */
  13582. int getKeyCode() const throw() { return keyCode; }
  13583. /** Returns the key modifiers.
  13584. @see ModifierKeys
  13585. */
  13586. const ModifierKeys getModifiers() const throw() { return mods; }
  13587. /** Returns the character that is associated with this keypress.
  13588. This is the character that you'd expect to see printed if you press this
  13589. keypress in a text editor or similar component.
  13590. */
  13591. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  13592. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  13593. the modifiers.
  13594. The values for key codes can either be one of the special constants defined in
  13595. this class, or an 8-bit character code.
  13596. @see getKeyCode
  13597. */
  13598. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  13599. /** Converts a textual key description to a KeyPress.
  13600. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  13601. This isn't designed to cope with any kind of input, but should be given the
  13602. strings that are created by the getTextDescription() method.
  13603. If the string can't be parsed, the object returned will be invalid.
  13604. @see getTextDescription
  13605. */
  13606. static const KeyPress createFromDescription (const String& textVersion) throw();
  13607. /** Creates a textual description of the key combination.
  13608. e.g. "CTRL + C" or "DELETE".
  13609. To store a keypress in a file, use this method, along with createFromDescription()
  13610. to retrieve it later.
  13611. */
  13612. const String getTextDescription() const throw();
  13613. /** Checks whether the user is currently holding down the keys that make up this
  13614. KeyPress.
  13615. Note that this will return false if any extra modifier keys are
  13616. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  13617. then it will be false.
  13618. */
  13619. bool isCurrentlyDown() const throw();
  13620. /** Checks whether a particular key is held down, irrespective of modifiers.
  13621. The values for key codes can either be one of the special constants defined in
  13622. this class, or an 8-bit character code.
  13623. */
  13624. static bool isKeyCurrentlyDown (int keyCode) throw();
  13625. // Key codes
  13626. //
  13627. // Note that the actual values of these are platform-specific and may change
  13628. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  13629. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  13630. //
  13631. static const int spaceKey; /**< key-code for the space bar */
  13632. static const int escapeKey; /**< key-code for the escape key */
  13633. static const int returnKey; /**< key-code for the return key*/
  13634. static const int tabKey; /**< key-code for the tab key*/
  13635. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  13636. static const int backspaceKey; /**< key-code for the backspace key */
  13637. static const int insertKey; /**< key-code for the insert key */
  13638. static const int upKey; /**< key-code for the cursor-up key */
  13639. static const int downKey; /**< key-code for the cursor-down key */
  13640. static const int leftKey; /**< key-code for the cursor-left key */
  13641. static const int rightKey; /**< key-code for the cursor-right key */
  13642. static const int pageUpKey; /**< key-code for the page-up key */
  13643. static const int pageDownKey; /**< key-code for the page-down key */
  13644. static const int homeKey; /**< key-code for the home key */
  13645. static const int endKey; /**< key-code for the end key */
  13646. static const int F1Key; /**< key-code for the F1 key */
  13647. static const int F2Key; /**< key-code for the F2 key */
  13648. static const int F3Key; /**< key-code for the F3 key */
  13649. static const int F4Key; /**< key-code for the F4 key */
  13650. static const int F5Key; /**< key-code for the F5 key */
  13651. static const int F6Key; /**< key-code for the F6 key */
  13652. static const int F7Key; /**< key-code for the F7 key */
  13653. static const int F8Key; /**< key-code for the F8 key */
  13654. static const int F9Key; /**< key-code for the F9 key */
  13655. static const int F10Key; /**< key-code for the F10 key */
  13656. static const int F11Key; /**< key-code for the F11 key */
  13657. static const int F12Key; /**< key-code for the F12 key */
  13658. static const int F13Key; /**< key-code for the F13 key */
  13659. static const int F14Key; /**< key-code for the F14 key */
  13660. static const int F15Key; /**< key-code for the F15 key */
  13661. static const int F16Key; /**< key-code for the F16 key */
  13662. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  13663. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  13664. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  13665. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  13666. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  13667. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  13668. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  13669. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  13670. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  13671. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  13672. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  13673. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  13674. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  13675. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  13676. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  13677. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  13678. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  13679. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  13680. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  13681. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  13682. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  13683. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  13684. juce_UseDebuggingNewOperator
  13685. private:
  13686. int keyCode;
  13687. ModifierKeys mods;
  13688. juce_wchar textCharacter;
  13689. };
  13690. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  13691. /********* End of inlined file: juce_KeyPress.h *********/
  13692. class Component;
  13693. /**
  13694. Receives callbacks when keys are pressed.
  13695. You can add a key listener to a component to be informed when that component
  13696. gets key events. See the Component::addListener method for more details.
  13697. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  13698. */
  13699. class JUCE_API KeyListener
  13700. {
  13701. public:
  13702. /** Destructor. */
  13703. virtual ~KeyListener() {}
  13704. /** Called to indicate that a key has been pressed.
  13705. If your implementation returns true, then the key event is considered to have
  13706. been consumed, and will not be passed on to any other components. If it returns
  13707. false, then the key will be passed to other components that might want to use it.
  13708. @param key the keystroke, including modifier keys
  13709. @param originatingComponent the component that received the key event
  13710. @see keyStateChanged, Component::keyPressed
  13711. */
  13712. virtual bool keyPressed (const KeyPress& key,
  13713. Component* originatingComponent) = 0;
  13714. /** Called when any key is pressed or released.
  13715. When this is called, classes that might be interested in
  13716. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  13717. check whether their key has changed.
  13718. If your implementation returns true, then the key event is considered to have
  13719. been consumed, and will not be passed on to any other components. If it returns
  13720. false, then the key will be passed to other components that might want to use it.
  13721. @param originatingComponent the component that received the key event
  13722. @param isKeyDown true if a key is being pressed, false if one is being released
  13723. @see KeyPress, Component::keyStateChanged
  13724. */
  13725. virtual bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  13726. };
  13727. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  13728. /********* End of inlined file: juce_KeyListener.h *********/
  13729. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  13730. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13731. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13732. class Component;
  13733. /**
  13734. Controls the order in which focus moves between components.
  13735. The default algorithm used by this class to work out the order of traversal
  13736. is as follows:
  13737. - if two components both have an explicit focus order specified, then the
  13738. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  13739. method).
  13740. - any component with an explicit focus order greater than 0 comes before ones
  13741. that don't have an order specified.
  13742. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  13743. order.
  13744. If you need traversal in a more customised way, you can create a subclass
  13745. of KeyboardFocusTraverser that uses your own algorithm, and use
  13746. Component::createFocusTraverser() to create it.
  13747. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  13748. */
  13749. class JUCE_API KeyboardFocusTraverser
  13750. {
  13751. public:
  13752. KeyboardFocusTraverser();
  13753. /** Destructor. */
  13754. virtual ~KeyboardFocusTraverser();
  13755. /** Returns the component that should be given focus after the specified one
  13756. when moving "forwards".
  13757. The default implementation will return the next component which is to the
  13758. right of or below this one.
  13759. This may return 0 if there's no suitable candidate.
  13760. */
  13761. virtual Component* getNextComponent (Component* current);
  13762. /** Returns the component that should be given focus after the specified one
  13763. when moving "backwards".
  13764. The default implementation will return the next component which is to the
  13765. left of or above this one.
  13766. This may return 0 if there's no suitable candidate.
  13767. */
  13768. virtual Component* getPreviousComponent (Component* current);
  13769. /** Returns the component that should receive focus be default within the given
  13770. parent component.
  13771. The default implementation will just return the foremost child component that
  13772. wants focus.
  13773. This may return 0 if there's no suitable candidate.
  13774. */
  13775. virtual Component* getDefaultComponent (Component* parentComponent);
  13776. };
  13777. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13778. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  13779. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  13780. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  13781. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  13782. /********* Start of inlined file: juce_Graphics.h *********/
  13783. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  13784. #define __JUCE_GRAPHICS_JUCEHEADER__
  13785. /********* Start of inlined file: juce_Font.h *********/
  13786. #ifndef __JUCE_FONT_JUCEHEADER__
  13787. #define __JUCE_FONT_JUCEHEADER__
  13788. /********* Start of inlined file: juce_Typeface.h *********/
  13789. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  13790. #define __JUCE_TYPEFACE_JUCEHEADER__
  13791. /********* Start of inlined file: juce_Path.h *********/
  13792. #ifndef __JUCE_PATH_JUCEHEADER__
  13793. #define __JUCE_PATH_JUCEHEADER__
  13794. /********* Start of inlined file: juce_AffineTransform.h *********/
  13795. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13796. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13797. /**
  13798. Represents a 2D affine-transformation matrix.
  13799. An affine transformation is a transformation such as a rotation, scale, shear,
  13800. resize or translation.
  13801. These are used for various 2D transformation tasks, e.g. with Path objects.
  13802. @see Path, Point, Line
  13803. */
  13804. class JUCE_API AffineTransform
  13805. {
  13806. public:
  13807. /** Creates an identity transform. */
  13808. AffineTransform() throw();
  13809. /** Creates a copy of another transform. */
  13810. AffineTransform (const AffineTransform& other) throw();
  13811. /** Creates a transform from a set of raw matrix values.
  13812. The resulting matrix is:
  13813. (mat00 mat01 mat02)
  13814. (mat10 mat11 mat12)
  13815. ( 0 0 1 )
  13816. */
  13817. AffineTransform (const float mat00, const float mat01, const float mat02,
  13818. const float mat10, const float mat11, const float mat12) throw();
  13819. /** Copies from another AffineTransform object */
  13820. const AffineTransform& operator= (const AffineTransform& other) throw();
  13821. /** Compares two transforms. */
  13822. bool operator== (const AffineTransform& other) const throw();
  13823. /** Compares two transforms. */
  13824. bool operator!= (const AffineTransform& other) const throw();
  13825. /** A ready-to-use identity transform, which you can use to append other
  13826. transformations to.
  13827. e.g. @code
  13828. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  13829. .scaled (2.0f);
  13830. @endcode
  13831. */
  13832. static const AffineTransform identity;
  13833. /** Transforms a 2D co-ordinate using this matrix. */
  13834. void transformPoint (float& x,
  13835. float& y) const throw();
  13836. /** Transforms a 2D co-ordinate using this matrix. */
  13837. void transformPoint (double& x,
  13838. double& y) const throw();
  13839. /** Returns a new transform which is the same as this one followed by a translation. */
  13840. const AffineTransform translated (const float deltaX,
  13841. const float deltaY) const throw();
  13842. /** Returns a new transform which is a translation. */
  13843. static const AffineTransform translation (const float deltaX,
  13844. const float deltaY) throw();
  13845. /** Returns a transform which is the same as this one followed by a rotation.
  13846. The rotation is specified by a number of radians to rotate clockwise, centred around
  13847. the origin (0, 0).
  13848. */
  13849. const AffineTransform rotated (const float angleInRadians) const throw();
  13850. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  13851. The rotation is specified by a number of radians to rotate clockwise, centred around
  13852. the co-ordinates passed in.
  13853. */
  13854. const AffineTransform rotated (const float angleInRadians,
  13855. const float pivotX,
  13856. const float pivotY) const throw();
  13857. /** Returns a new transform which is a rotation about (0, 0). */
  13858. static const AffineTransform rotation (const float angleInRadians) throw();
  13859. /** Returns a new transform which is a rotation about a given point. */
  13860. static const AffineTransform rotation (const float angleInRadians,
  13861. const float pivotX,
  13862. const float pivotY) throw();
  13863. /** Returns a transform which is the same as this one followed by a re-scaling.
  13864. The scaling is centred around the origin (0, 0).
  13865. */
  13866. const AffineTransform scaled (const float factorX,
  13867. const float factorY) const throw();
  13868. /** Returns a new transform which is a re-scale about the origin. */
  13869. static const AffineTransform scale (const float factorX,
  13870. const float factorY) throw();
  13871. /** Returns a transform which is the same as this one followed by a shear.
  13872. The shear is centred around the origin (0, 0).
  13873. */
  13874. const AffineTransform sheared (const float shearX,
  13875. const float shearY) const throw();
  13876. /** Returns a matrix which is the inverse operation of this one.
  13877. Some matrices don't have an inverse - in this case, the method will just return
  13878. an identity transform.
  13879. */
  13880. const AffineTransform inverted() const throw();
  13881. /** Returns the result of concatenating another transformation after this one. */
  13882. const AffineTransform followedBy (const AffineTransform& other) const throw();
  13883. /** Returns true if this transform has no effect on points. */
  13884. bool isIdentity() const throw();
  13885. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  13886. bool isSingularity() const throw();
  13887. /** Returns true if the transform only translates, and doesn't scale or rotate the
  13888. points. */
  13889. bool isOnlyTranslation() const throw();
  13890. /** If this transform is only a translation, this returns the X offset.
  13891. @see isOnlyTranslation
  13892. */
  13893. float getTranslationX() const throw() { return mat02; }
  13894. /** If this transform is only a translation, this returns the X offset.
  13895. @see isOnlyTranslation
  13896. */
  13897. float getTranslationY() const throw() { return mat12; }
  13898. juce_UseDebuggingNewOperator
  13899. /* The transform matrix is:
  13900. (mat00 mat01 mat02)
  13901. (mat10 mat11 mat12)
  13902. ( 0 0 1 )
  13903. */
  13904. float mat00, mat01, mat02;
  13905. float mat10, mat11, mat12;
  13906. private:
  13907. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  13908. const float mat10, const float mat11, const float mat12) const throw();
  13909. };
  13910. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13911. /********* End of inlined file: juce_AffineTransform.h *********/
  13912. /********* Start of inlined file: juce_Point.h *********/
  13913. #ifndef __JUCE_POINT_JUCEHEADER__
  13914. #define __JUCE_POINT_JUCEHEADER__
  13915. /**
  13916. A pair of (x, y) co-ordinates.
  13917. Uses 32-bit floating point accuracy.
  13918. @see Line, Path, AffineTransform
  13919. */
  13920. class JUCE_API Point
  13921. {
  13922. public:
  13923. /** Creates a point with co-ordinates (0, 0). */
  13924. Point() throw();
  13925. /** Creates a copy of another point. */
  13926. Point (const Point& other) throw();
  13927. /** Creates a point from an (x, y) position. */
  13928. Point (const float x, const float y) throw();
  13929. /** Copies this point from another one.
  13930. @see setXY
  13931. */
  13932. const Point& operator= (const Point& other) throw();
  13933. /** Destructor. */
  13934. ~Point() throw();
  13935. /** Returns the point's x co-ordinate. */
  13936. inline float getX() const throw() { return x; }
  13937. /** Returns the point's y co-ordinate. */
  13938. inline float getY() const throw() { return y; }
  13939. /** Changes the point's x and y co-ordinates. */
  13940. void setXY (const float x,
  13941. const float y) throw();
  13942. /** Uses a transform to change the point's co-ordinates.
  13943. @see AffineTransform::transformPoint
  13944. */
  13945. void applyTransform (const AffineTransform& transform) throw();
  13946. juce_UseDebuggingNewOperator
  13947. private:
  13948. float x, y;
  13949. };
  13950. #endif // __JUCE_POINT_JUCEHEADER__
  13951. /********* End of inlined file: juce_Point.h *********/
  13952. /********* Start of inlined file: juce_Rectangle.h *********/
  13953. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13954. #define __JUCE_RECTANGLE_JUCEHEADER__
  13955. /**
  13956. A rectangle, specified using integer co-ordinates.
  13957. @see RectangleList, Path, Line, Point
  13958. */
  13959. class JUCE_API Rectangle
  13960. {
  13961. public:
  13962. /** Creates a rectangle of zero size.
  13963. The default co-ordinates will be (0, 0, 0, 0).
  13964. */
  13965. Rectangle() throw();
  13966. /** Creates a copy of another rectangle. */
  13967. Rectangle (const Rectangle& other) throw();
  13968. /** Creates a rectangle with a given position and size. */
  13969. Rectangle (const int x, const int y,
  13970. const int width, const int height) throw();
  13971. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13972. Rectangle (const int width, const int height) throw();
  13973. /** Destructor. */
  13974. ~Rectangle() throw();
  13975. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13976. inline int getX() const throw() { return x; }
  13977. /** Returns the y co-ordinate of the rectangle's top edge. */
  13978. inline int getY() const throw() { return y; }
  13979. /** Returns the width of the rectangle. */
  13980. inline int getWidth() const throw() { return w; }
  13981. /** Returns the height of the rectangle. */
  13982. inline int getHeight() const throw() { return h; }
  13983. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13984. inline int getRight() const throw() { return x + w; }
  13985. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13986. inline int getBottom() const throw() { return y + h; }
  13987. /** Returns the x co-ordinate of the rectangle's centre. */
  13988. inline int getCentreX() const throw() { return x + (w >> 1); }
  13989. /** Returns the y co-ordinate of the rectangle's centre. */
  13990. inline int getCentreY() const throw() { return y + (h >> 1); }
  13991. /** Returns true if the rectangle's width and height are both zero or less */
  13992. bool isEmpty() const throw();
  13993. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13994. void setPosition (const int x, const int y) throw();
  13995. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13996. void setSize (const int w, const int h) throw();
  13997. /** Changes all the rectangle's co-ordinates. */
  13998. void setBounds (const int newX, const int newY,
  13999. const int newWidth, const int newHeight) throw();
  14000. /** Changes the rectangle's width */
  14001. void setWidth (const int newWidth) throw();
  14002. /** Changes the rectangle's height */
  14003. void setHeight (const int newHeight) throw();
  14004. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  14005. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  14006. */
  14007. void setLeft (const int newLeft) throw();
  14008. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  14009. If the y is moved to be below the current bottom edge, the height will be set to zero.
  14010. */
  14011. void setTop (const int newTop) throw();
  14012. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  14013. If the new right is below the current X value, the X will be pushed down to match it.
  14014. @see getRight
  14015. */
  14016. void setRight (const int newRight) throw();
  14017. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  14018. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  14019. @see getBottom
  14020. */
  14021. void setBottom (const int newBottom) throw();
  14022. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  14023. void translate (const int deltaX,
  14024. const int deltaY) throw();
  14025. /** Returns a rectangle which is the same as this one moved by a given amount. */
  14026. const Rectangle translated (const int deltaX,
  14027. const int deltaY) const throw();
  14028. /** Expands the rectangle by a given amount.
  14029. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  14030. @see expanded, reduce, reduced
  14031. */
  14032. void expand (const int deltaX,
  14033. const int deltaY) throw();
  14034. /** Returns a rectangle that is larger than this one by a given amount.
  14035. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  14036. @see expand, reduce, reduced
  14037. */
  14038. const Rectangle expanded (const int deltaX,
  14039. const int deltaY) const throw();
  14040. /** Shrinks the rectangle by a given amount.
  14041. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  14042. @see reduced, expand, expanded
  14043. */
  14044. void reduce (const int deltaX,
  14045. const int deltaY) throw();
  14046. /** Returns a rectangle that is smaller than this one by a given amount.
  14047. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  14048. @see reduce, expand, expanded
  14049. */
  14050. const Rectangle reduced (const int deltaX,
  14051. const int deltaY) const throw();
  14052. /** Returns true if the two rectangles are identical. */
  14053. bool operator== (const Rectangle& other) const throw();
  14054. /** Returns true if the two rectangles are not identical. */
  14055. bool operator!= (const Rectangle& other) const throw();
  14056. /** Returns true if this co-ordinate is inside the rectangle. */
  14057. bool contains (const int x, const int y) const throw();
  14058. /** Returns true if this other rectangle is completely inside this one. */
  14059. bool contains (const Rectangle& other) const throw();
  14060. /** Returns true if any part of another rectangle overlaps this one. */
  14061. bool intersects (const Rectangle& other) const throw();
  14062. /** Returns the region that is the overlap between this and another rectangle.
  14063. If the two rectangles don't overlap, the rectangle returned will be empty.
  14064. */
  14065. const Rectangle getIntersection (const Rectangle& other) const throw();
  14066. /** Clips a rectangle so that it lies only within this one.
  14067. This is a non-static version of intersectRectangles().
  14068. Returns false if the two regions didn't overlap.
  14069. */
  14070. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  14071. /** Returns the smallest rectangle that contains both this one and the one
  14072. passed-in.
  14073. */
  14074. const Rectangle getUnion (const Rectangle& other) const throw();
  14075. /** If this rectangle merged with another one results in a simple rectangle, this
  14076. will set this rectangle to the result, and return true.
  14077. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  14078. or if they form a complex region.
  14079. */
  14080. bool enlargeIfAdjacent (const Rectangle& other) throw();
  14081. /** If after removing another rectangle from this one the result is a simple rectangle,
  14082. this will set this object's bounds to be the result, and return true.
  14083. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  14084. or if removing the other one would form a complex region.
  14085. */
  14086. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  14087. /** Static utility to intersect two sets of rectangular co-ordinates.
  14088. Returns false if the two regions didn't overlap.
  14089. @see intersectRectangle
  14090. */
  14091. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  14092. int x2, int y2, int w2, int h2) throw();
  14093. /** Creates a string describing this rectangle.
  14094. The string will be of the form "x y width height", e.g. "100 100 400 200".
  14095. Coupled with the fromString() method, this is very handy for things like
  14096. storing rectangles (particularly component positions) in XML attributes.
  14097. @see fromString
  14098. */
  14099. const String toString() const throw();
  14100. /** Parses a string containing a rectangle's details.
  14101. The string should contain 4 integer tokens, in the form "x y width height". They
  14102. can be comma or whitespace separated.
  14103. This method is intended to go with the toString() method, to form an easy way
  14104. of saving/loading rectangles as strings.
  14105. @see toString
  14106. */
  14107. static const Rectangle fromString (const String& stringVersion);
  14108. juce_UseDebuggingNewOperator
  14109. private:
  14110. friend class RectangleList;
  14111. int x, y, w, h;
  14112. };
  14113. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  14114. /********* End of inlined file: juce_Rectangle.h *********/
  14115. /********* Start of inlined file: juce_Justification.h *********/
  14116. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  14117. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  14118. /**
  14119. Represents a type of justification to be used when positioning graphical items.
  14120. e.g. it indicates whether something should be placed top-left, top-right,
  14121. centred, etc.
  14122. It is used in various places wherever this kind of information is needed.
  14123. */
  14124. class JUCE_API Justification
  14125. {
  14126. public:
  14127. /** Creates a Justification object using a combination of flags. */
  14128. inline Justification (const int flags_) throw() : flags (flags_) {}
  14129. /** Creates a copy of another Justification object. */
  14130. Justification (const Justification& other) throw();
  14131. /** Copies another Justification object. */
  14132. const Justification& operator= (const Justification& other) throw();
  14133. /** Returns the raw flags that are set for this Justification object. */
  14134. inline int getFlags() const throw() { return flags; }
  14135. /** Tests a set of flags for this object.
  14136. @returns true if any of the flags passed in are set on this object.
  14137. */
  14138. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14139. /** Returns just the flags from this object that deal with vertical layout. */
  14140. int getOnlyVerticalFlags() const throw();
  14141. /** Returns just the flags from this object that deal with horizontal layout. */
  14142. int getOnlyHorizontalFlags() const throw();
  14143. /** Adjusts the position of a rectangle to fit it into a space.
  14144. The (x, y) position of the rectangle will be updated to position it inside the
  14145. given space according to the justification flags.
  14146. */
  14147. void applyToRectangle (int& x, int& y,
  14148. const int w, const int h,
  14149. const int spaceX, const int spaceY,
  14150. const int spaceW, const int spaceH) const throw();
  14151. /** Flag values that can be combined and used in the constructor. */
  14152. enum
  14153. {
  14154. /** Indicates that the item should be aligned against the left edge of the available space. */
  14155. left = 1,
  14156. /** Indicates that the item should be aligned against the right edge of the available space. */
  14157. right = 2,
  14158. /** Indicates that the item should be placed in the centre between the left and right
  14159. sides of the available space. */
  14160. horizontallyCentred = 4,
  14161. /** Indicates that the item should be aligned against the top edge of the available space. */
  14162. top = 8,
  14163. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  14164. bottom = 16,
  14165. /** Indicates that the item should be placed in the centre between the top and bottom
  14166. sides of the available space. */
  14167. verticallyCentred = 32,
  14168. /** Indicates that lines of text should be spread out to fill the maximum width
  14169. available, so that both margins are aligned vertically.
  14170. */
  14171. horizontallyJustified = 64,
  14172. /** Indicates that the item should be centred vertically and horizontally.
  14173. This is equivalent to (horizontallyCentred | verticallyCentred)
  14174. */
  14175. centred = 36,
  14176. /** Indicates that the item should be centred vertically but placed on the left hand side.
  14177. This is equivalent to (left | verticallyCentred)
  14178. */
  14179. centredLeft = 33,
  14180. /** Indicates that the item should be centred vertically but placed on the right hand side.
  14181. This is equivalent to (right | verticallyCentred)
  14182. */
  14183. centredRight = 34,
  14184. /** Indicates that the item should be centred horizontally and placed at the top.
  14185. This is equivalent to (horizontallyCentred | top)
  14186. */
  14187. centredTop = 12,
  14188. /** Indicates that the item should be centred horizontally and placed at the bottom.
  14189. This is equivalent to (horizontallyCentred | bottom)
  14190. */
  14191. centredBottom = 20,
  14192. /** Indicates that the item should be placed in the top-left corner.
  14193. This is equivalent to (left | top)
  14194. */
  14195. topLeft = 9,
  14196. /** Indicates that the item should be placed in the top-right corner.
  14197. This is equivalent to (right | top)
  14198. */
  14199. topRight = 10,
  14200. /** Indicates that the item should be placed in the bottom-left corner.
  14201. This is equivalent to (left | bottom)
  14202. */
  14203. bottomLeft = 17,
  14204. /** Indicates that the item should be placed in the bottom-left corner.
  14205. This is equivalent to (right | bottom)
  14206. */
  14207. bottomRight = 18
  14208. };
  14209. private:
  14210. int flags;
  14211. };
  14212. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  14213. /********* End of inlined file: juce_Justification.h *********/
  14214. /********* Start of inlined file: juce_EdgeTable.h *********/
  14215. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  14216. #define __JUCE_EDGETABLE_JUCEHEADER__
  14217. class Path;
  14218. class RectangleList;
  14219. class Image;
  14220. /**
  14221. A table of horizontal scan-line segments - used for rasterising Paths.
  14222. @see Path, Graphics
  14223. */
  14224. class JUCE_API EdgeTable
  14225. {
  14226. public:
  14227. /** Creates an edge table containing a path.
  14228. A table is created with a fixed vertical range, and only sections of the path
  14229. which lie within this range will be added to the table.
  14230. @param clipLimits only the region of the path that lies within this area will be added
  14231. @param pathToAdd the path to add to the table
  14232. @param transform a transform to apply to the path being added
  14233. */
  14234. EdgeTable (const Rectangle& clipLimits,
  14235. const Path& pathToAdd,
  14236. const AffineTransform& transform) throw();
  14237. /** Creates an edge table containing a rectangle.
  14238. */
  14239. EdgeTable (const Rectangle& rectangleToAdd) throw();
  14240. /** Creates an edge table containing a rectangle list.
  14241. */
  14242. EdgeTable (const RectangleList& rectanglesToAdd) throw();
  14243. /** Creates an edge table containing a rectangle.
  14244. */
  14245. EdgeTable (const float x, const float y,
  14246. const float w, const float h) throw();
  14247. /** Creates a copy of another edge table. */
  14248. EdgeTable (const EdgeTable& other) throw();
  14249. /** Copies from another edge table. */
  14250. const EdgeTable& operator= (const EdgeTable& other) throw();
  14251. /** Destructor. */
  14252. ~EdgeTable() throw();
  14253. void clipToRectangle (const Rectangle& r) throw();
  14254. void excludeRectangle (const Rectangle& r) throw();
  14255. void clipToEdgeTable (const EdgeTable& other);
  14256. void clipLineToMask (int x, int y, uint8* mask, int maskStride, int numPixels) throw();
  14257. bool isEmpty() throw();
  14258. const Rectangle& getMaximumBounds() const throw() { return bounds; }
  14259. void translate (float dx, int dy) throw();
  14260. /** Reduces the amount of space the table has allocated.
  14261. This will shrink the table down to use as little memory as possible - useful for
  14262. read-only tables that get stored and re-used for rendering.
  14263. */
  14264. void optimiseTable() throw();
  14265. /** Iterates the lines in the table, for rendering.
  14266. This function will iterate each line in the table, and call a user-defined class
  14267. to render each pixel or continuous line of pixels that the table contains.
  14268. @param iterationCallback this templated class must contain the following methods:
  14269. @code
  14270. inline void setEdgeTableYPos (int y);
  14271. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  14272. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  14273. @endcode
  14274. (these don't necessarily have to be 'const', but it might help it go faster)
  14275. */
  14276. template <class EdgeTableIterationCallback>
  14277. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  14278. {
  14279. const int* lineStart = table;
  14280. for (int y = 0; y < bounds.getHeight(); ++y)
  14281. {
  14282. const int* line = lineStart;
  14283. lineStart += lineStrideElements;
  14284. int numPoints = line[0];
  14285. if (--numPoints > 0)
  14286. {
  14287. int x = *++line;
  14288. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  14289. int levelAccumulator = 0;
  14290. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  14291. while (--numPoints >= 0)
  14292. {
  14293. const int level = *++line;
  14294. jassert (((unsigned int) level) < (unsigned int) 256);
  14295. const int endX = *++line;
  14296. jassert (endX >= x);
  14297. const int endOfRun = (endX >> 8);
  14298. if (endOfRun == (x >> 8))
  14299. {
  14300. // small segment within the same pixel, so just save it for the next
  14301. // time round..
  14302. levelAccumulator += (endX - x) * level;
  14303. }
  14304. else
  14305. {
  14306. // plot the fist pixel of this segment, including any accumulated
  14307. // levels from smaller segments that haven't been drawn yet
  14308. levelAccumulator += (0xff - (x & 0xff)) * level;
  14309. levelAccumulator >>= 8;
  14310. x >>= 8;
  14311. if (levelAccumulator > 0)
  14312. {
  14313. if (levelAccumulator >> 8)
  14314. levelAccumulator = 0xff;
  14315. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  14316. }
  14317. // if there's a run of similar pixels, do it all in one go..
  14318. if (level > 0)
  14319. {
  14320. jassert (endOfRun <= bounds.getRight());
  14321. const int numPix = endOfRun - ++x;
  14322. if (numPix > 0)
  14323. iterationCallback.handleEdgeTableLine (x, numPix, level);
  14324. }
  14325. // save the bit at the end to be drawn next time round the loop.
  14326. levelAccumulator = (endX & 0xff) * level;
  14327. }
  14328. x = endX;
  14329. }
  14330. if (levelAccumulator > 0)
  14331. {
  14332. levelAccumulator >>= 8;
  14333. if (levelAccumulator >> 8)
  14334. levelAccumulator = 0xff;
  14335. x >>= 8;
  14336. jassert (x >= bounds.getX() && x < bounds.getRight());
  14337. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  14338. }
  14339. }
  14340. }
  14341. }
  14342. juce_UseDebuggingNewOperator
  14343. private:
  14344. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  14345. HeapBlock <int> table;
  14346. Rectangle bounds;
  14347. int maxEdgesPerLine, lineStrideElements;
  14348. bool needToCheckEmptinesss;
  14349. void addEdgePoint (const int x, const int y, const int winding) throw();
  14350. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  14351. void intersectWithEdgeTableLine (const int y, const int* otherLine) throw();
  14352. void sanitiseLevels (const bool useNonZeroWinding) throw();
  14353. };
  14354. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  14355. /********* End of inlined file: juce_EdgeTable.h *********/
  14356. class Image;
  14357. /**
  14358. A path is a sequence of lines and curves that may either form a closed shape
  14359. or be open-ended.
  14360. To use a path, you can create an empty one, then add lines and curves to it
  14361. to create shapes, then it can be rendered by a Graphics context or used
  14362. for geometric operations.
  14363. e.g. @code
  14364. Path myPath;
  14365. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  14366. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  14367. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  14368. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  14369. // add an ellipse as well, which will form a second sub-path within the path..
  14370. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  14371. // double the width of the whole thing..
  14372. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  14373. // and draw it to a graphics context with a 5-pixel thick outline.
  14374. g.strokePath (myPath, PathStrokeType (5.0f));
  14375. @endcode
  14376. A path object can actually contain multiple sub-paths, which may themselves
  14377. be open or closed.
  14378. @see PathFlatteningIterator, PathStrokeType, Graphics
  14379. */
  14380. class JUCE_API Path
  14381. {
  14382. public:
  14383. /** Creates an empty path. */
  14384. Path() throw();
  14385. /** Creates a copy of another path. */
  14386. Path (const Path& other) throw();
  14387. /** Destructor. */
  14388. ~Path() throw();
  14389. /** Copies this path from another one. */
  14390. const Path& operator= (const Path& other) throw();
  14391. /** Returns true if the path doesn't contain any lines or curves. */
  14392. bool isEmpty() const throw();
  14393. /** Returns the smallest rectangle that contains all points within the path.
  14394. */
  14395. void getBounds (float& x, float& y,
  14396. float& w, float& h) const throw();
  14397. /** Returns the smallest rectangle that contains all points within the path
  14398. after it's been transformed with the given tranasform matrix.
  14399. */
  14400. void getBoundsTransformed (const AffineTransform& transform,
  14401. float& x, float& y,
  14402. float& w, float& h) const throw();
  14403. /** Checks whether a point lies within the path.
  14404. This is only relevent for closed paths (see closeSubPath()), and
  14405. may produce false results if used on a path which has open sub-paths.
  14406. The path's winding rule is taken into account by this method.
  14407. The tolerence parameter is passed to the PathFlatteningIterator that
  14408. is used to trace the path - for more info about it, see the notes for
  14409. the PathFlatteningIterator constructor.
  14410. @see closeSubPath, setUsingNonZeroWinding
  14411. */
  14412. bool contains (const float x,
  14413. const float y,
  14414. const float tolerence = 10.0f) const throw();
  14415. /** Checks whether a line crosses the path.
  14416. This will return positive if the line crosses any of the paths constituent
  14417. lines or curves. It doesn't take into account whether the line is inside
  14418. or outside the path, or whether the path is open or closed.
  14419. The tolerence parameter is passed to the PathFlatteningIterator that
  14420. is used to trace the path - for more info about it, see the notes for
  14421. the PathFlatteningIterator constructor.
  14422. */
  14423. bool intersectsLine (const float x1, const float y1,
  14424. const float x2, const float y2,
  14425. const float tolerence = 10.0f) throw();
  14426. /** Removes all lines and curves, resetting the path completely. */
  14427. void clear() throw();
  14428. /** Begins a new subpath with a given starting position.
  14429. This will move the path's current position to the co-ordinates passed in and
  14430. make it ready to draw lines or curves starting from this position.
  14431. After adding whatever lines and curves are needed, you can either
  14432. close the current sub-path using closeSubPath() or call startNewSubPath()
  14433. to move to a new sub-path, leaving the old one open-ended.
  14434. @see lineTo, quadraticTo, cubicTo, closeSubPath
  14435. */
  14436. void startNewSubPath (const float startX,
  14437. const float startY) throw();
  14438. /** Closes a the current sub-path with a line back to its start-point.
  14439. When creating a closed shape such as a triangle, don't use 3 lineTo()
  14440. calls - instead use two lineTo() calls, followed by a closeSubPath()
  14441. to join the final point back to the start.
  14442. This ensures that closes shapes are recognised as such, and this is
  14443. important for tasks like drawing strokes, which needs to know whether to
  14444. draw end-caps or not.
  14445. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  14446. */
  14447. void closeSubPath() throw();
  14448. /** Adds a line from the shape's last position to a new end-point.
  14449. This will connect the end-point of the last line or curve that was added
  14450. to a new point, using a straight line.
  14451. See the class description for an example of how to add lines and curves to a path.
  14452. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  14453. */
  14454. void lineTo (const float endX,
  14455. const float endY) throw();
  14456. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  14457. This will connect the end-point of the last line or curve that was added
  14458. to a new point, using a quadratic spline with one control-point.
  14459. See the class description for an example of how to add lines and curves to a path.
  14460. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  14461. */
  14462. void quadraticTo (const float controlPointX,
  14463. const float controlPointY,
  14464. const float endPointX,
  14465. const float endPointY) throw();
  14466. /** Adds a cubic bezier curve from the shape's last position to a new position.
  14467. This will connect the end-point of the last line or curve that was added
  14468. to a new point, using a cubic spline with two control-points.
  14469. See the class description for an example of how to add lines and curves to a path.
  14470. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  14471. */
  14472. void cubicTo (const float controlPoint1X,
  14473. const float controlPoint1Y,
  14474. const float controlPoint2X,
  14475. const float controlPoint2Y,
  14476. const float endPointX,
  14477. const float endPointY) throw();
  14478. /** Returns the last point that was added to the path by one of the drawing methods.
  14479. */
  14480. const Point getCurrentPosition() const;
  14481. /** Adds a rectangle to the path.
  14482. The rectangle is added as a new sub-path. (Any currently open paths will be
  14483. left open).
  14484. @see addRoundedRectangle, addTriangle
  14485. */
  14486. void addRectangle (const float x, const float y,
  14487. const float w, const float h) throw();
  14488. /** Adds a rectangle to the path.
  14489. The rectangle is added as a new sub-path. (Any currently open paths will be
  14490. left open).
  14491. @see addRoundedRectangle, addTriangle
  14492. */
  14493. void addRectangle (const Rectangle& rectangle) throw();
  14494. /** Adds a rectangle with rounded corners to the path.
  14495. The rectangle is added as a new sub-path. (Any currently open paths will be
  14496. left open).
  14497. @see addRectangle, addTriangle
  14498. */
  14499. void addRoundedRectangle (const float x, const float y,
  14500. const float w, const float h,
  14501. float cornerSize) throw();
  14502. /** Adds a rectangle with rounded corners to the path.
  14503. The rectangle is added as a new sub-path. (Any currently open paths will be
  14504. left open).
  14505. @see addRectangle, addTriangle
  14506. */
  14507. void addRoundedRectangle (const float x, const float y,
  14508. const float w, const float h,
  14509. float cornerSizeX,
  14510. float cornerSizeY) throw();
  14511. /** Adds a triangle to the path.
  14512. The triangle is added as a new closed sub-path. (Any currently open paths will be
  14513. left open).
  14514. Note that whether the vertices are specified in clockwise or anticlockwise
  14515. order will affect how the triangle is filled when it overlaps other
  14516. shapes (the winding order setting will affect this of course).
  14517. */
  14518. void addTriangle (const float x1, const float y1,
  14519. const float x2, const float y2,
  14520. const float x3, const float y3) throw();
  14521. /** Adds a quadrilateral to the path.
  14522. The quad is added as a new closed sub-path. (Any currently open paths will be
  14523. left open).
  14524. Note that whether the vertices are specified in clockwise or anticlockwise
  14525. order will affect how the quad is filled when it overlaps other
  14526. shapes (the winding order setting will affect this of course).
  14527. */
  14528. void addQuadrilateral (const float x1, const float y1,
  14529. const float x2, const float y2,
  14530. const float x3, const float y3,
  14531. const float x4, const float y4) throw();
  14532. /** Adds an ellipse to the path.
  14533. The shape is added as a new sub-path. (Any currently open paths will be
  14534. left open).
  14535. @see addArc
  14536. */
  14537. void addEllipse (const float x, const float y,
  14538. const float width, const float height) throw();
  14539. /** Adds an elliptical arc to the current path.
  14540. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  14541. or anti-clockwise according to whether the end angle is greater than the start. This means
  14542. that sometimes you may need to use values greater than 2*Pi for the end angle.
  14543. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  14544. @param y the top edge of the rectangle in which the elliptical outline fits
  14545. @param width the width of the rectangle in which the elliptical outline fits
  14546. @param height the height of the rectangle in which the elliptical outline fits
  14547. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14548. top-centre of the ellipse)
  14549. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14550. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  14551. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  14552. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  14553. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  14554. it will be added to the current sub-path, continuing from the current postition
  14555. @see addCentredArc, arcTo, addPieSegment, addEllipse
  14556. */
  14557. void addArc (const float x, const float y,
  14558. const float width, const float height,
  14559. const float fromRadians,
  14560. const float toRadians,
  14561. const bool startAsNewSubPath = false) throw();
  14562. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  14563. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  14564. or anti-clockwise according to whether the end angle is greater than the start. This means
  14565. that sometimes you may need to use values greater than 2*Pi for the end angle.
  14566. @param centreX the centre x of the ellipse
  14567. @param centreY the centre y of the ellipse
  14568. @param radiusX the horizontal radius of the ellipse
  14569. @param radiusY the vertical radius of the ellipse
  14570. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  14571. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14572. top-centre of the ellipse)
  14573. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14574. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  14575. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  14576. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  14577. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  14578. it will be added to the current sub-path, continuing from the current postition
  14579. @see addArc, arcTo
  14580. */
  14581. void addCentredArc (const float centreX, const float centreY,
  14582. const float radiusX, const float radiusY,
  14583. const float rotationOfEllipse,
  14584. const float fromRadians,
  14585. const float toRadians,
  14586. const bool startAsNewSubPath = false) throw();
  14587. /** Adds a "pie-chart" shape to the path.
  14588. The shape is added as a new sub-path. (Any currently open paths will be
  14589. left open).
  14590. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  14591. or anti-clockwise according to whether the end angle is greater than the start. This means
  14592. that sometimes you may need to use values greater than 2*Pi for the end angle.
  14593. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  14594. @param y the top edge of the rectangle in which the elliptical outline fits
  14595. @param width the width of the rectangle in which the elliptical outline fits
  14596. @param height the height of the rectangle in which the elliptical outline fits
  14597. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14598. top-centre of the ellipse)
  14599. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14600. top-centre of the ellipse)
  14601. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  14602. ellipse at its centre, where this value indicates the inner ellipse's size with
  14603. respect to the outer one.
  14604. @see addArc
  14605. */
  14606. void addPieSegment (const float x, const float y,
  14607. const float width, const float height,
  14608. const float fromRadians,
  14609. const float toRadians,
  14610. const float innerCircleProportionalSize);
  14611. /** Adds a line with a specified thickness.
  14612. The line is added as a new closed sub-path. (Any currently open paths will be
  14613. left open).
  14614. @see addArrow
  14615. */
  14616. void addLineSegment (const float startX, const float startY,
  14617. const float endX, const float endY,
  14618. float lineThickness) throw();
  14619. /** Adds a line with an arrowhead on the end.
  14620. The arrow is added as a new closed sub-path. (Any currently open paths will be
  14621. left open).
  14622. */
  14623. void addArrow (const float startX, const float startY,
  14624. const float endX, const float endY,
  14625. float lineThickness,
  14626. float arrowheadWidth,
  14627. float arrowheadLength) throw();
  14628. /** Adds a star shape to the path.
  14629. */
  14630. void addStar (const float centreX,
  14631. const float centreY,
  14632. const int numberOfPoints,
  14633. const float innerRadius,
  14634. const float outerRadius,
  14635. const float startAngle = 0.0f);
  14636. /** Adds a speech-bubble shape to the path.
  14637. @param bodyX the left of the main body area of the bubble
  14638. @param bodyY the top of the main body area of the bubble
  14639. @param bodyW the width of the main body area of the bubble
  14640. @param bodyH the height of the main body area of the bubble
  14641. @param cornerSize the amount by which to round off the corners of the main body rectangle
  14642. @param arrowTipX the x position that the tip of the arrow should connect to
  14643. @param arrowTipY the y position that the tip of the arrow should connect to
  14644. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  14645. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  14646. arrow's base should be - this is a proportional distance between 0 and 1.0
  14647. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  14648. */
  14649. void addBubble (float bodyX, float bodyY,
  14650. float bodyW, float bodyH,
  14651. float cornerSize,
  14652. float arrowTipX,
  14653. float arrowTipY,
  14654. int whichSide,
  14655. float arrowPositionAlongEdgeProportional,
  14656. float arrowWidth);
  14657. /** Adds another path to this one.
  14658. The new path is added as a new sub-path. (Any currently open paths in this
  14659. path will be left open).
  14660. @param pathToAppend the path to add
  14661. */
  14662. void addPath (const Path& pathToAppend) throw();
  14663. /** Adds another path to this one, transforming it on the way in.
  14664. The new path is added as a new sub-path, its points being transformed by the given
  14665. matrix before being added.
  14666. @param pathToAppend the path to add
  14667. @param transformToApply an optional transform to apply to the incoming vertices
  14668. */
  14669. void addPath (const Path& pathToAppend,
  14670. const AffineTransform& transformToApply) throw();
  14671. /** Swaps the contents of this path with another one.
  14672. The internal data of the two paths is swapped over, so this is much faster than
  14673. copying it to a temp variable and back.
  14674. */
  14675. void swapWithPath (Path& other);
  14676. /** Applies a 2D transform to all the vertices in the path.
  14677. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  14678. */
  14679. void applyTransform (const AffineTransform& transform) throw();
  14680. /** Rescales this path to make it fit neatly into a given space.
  14681. This is effectively a quick way of calling
  14682. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  14683. @param x the x position of the rectangle to fit the path inside
  14684. @param y the y position of the rectangle to fit the path inside
  14685. @param width the width of the rectangle to fit the path inside
  14686. @param height the height of the rectangle to fit the path inside
  14687. @param preserveProportions if true, it will fit the path into the space without altering its
  14688. horizontal/vertical scale ratio; if false, it will distort the
  14689. path to fill the specified ratio both horizontally and vertically
  14690. @see applyTransform, getTransformToScaleToFit
  14691. */
  14692. void scaleToFit (const float x, const float y,
  14693. const float width, const float height,
  14694. const bool preserveProportions) throw();
  14695. /** Returns a transform that can be used to rescale the path to fit into a given space.
  14696. @param x the x position of the rectangle to fit the path inside
  14697. @param y the y position of the rectangle to fit the path inside
  14698. @param width the width of the rectangle to fit the path inside
  14699. @param height the height of the rectangle to fit the path inside
  14700. @param preserveProportions if true, it will fit the path into the space without altering its
  14701. horizontal/vertical scale ratio; if false, it will distort the
  14702. path to fill the specified ratio both horizontally and vertically
  14703. @param justificationType if the proportions are preseved, the resultant path may be smaller
  14704. than the available rectangle, so this describes how it should be
  14705. positioned within the space.
  14706. @returns an appropriate transformation
  14707. @see applyTransform, scaleToFit
  14708. */
  14709. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  14710. const float width, const float height,
  14711. const bool preserveProportions,
  14712. const Justification& justificationType = Justification::centred) const throw();
  14713. /** Creates a version of this path where all sharp corners have been replaced by curves.
  14714. Wherever two lines meet at an angle, this will replace the corner with a curve
  14715. of the given radius.
  14716. */
  14717. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  14718. /** Changes the winding-rule to be used when filling the path.
  14719. If set to true (which is the default), then the path uses a non-zero-winding rule
  14720. to determine which points are inside the path. If set to false, it uses an
  14721. alternate-winding rule.
  14722. The winding-rule comes into play when areas of the shape overlap other
  14723. areas, and determines whether the overlapping regions are considered to be
  14724. inside or outside.
  14725. Changing this value just sets a flag - it doesn't affect the contents of the
  14726. path.
  14727. @see isUsingNonZeroWinding
  14728. */
  14729. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  14730. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  14731. The default for a new path is true.
  14732. @see setUsingNonZeroWinding
  14733. */
  14734. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  14735. /** Iterates the lines and curves that a path contains.
  14736. @see Path, PathFlatteningIterator
  14737. */
  14738. class JUCE_API Iterator
  14739. {
  14740. public:
  14741. Iterator (const Path& path);
  14742. ~Iterator();
  14743. /** Moves onto the next element in the path.
  14744. If this returns false, there are no more elements. If it returns true,
  14745. the elementType variable will be set to the type of the current element,
  14746. and some of the x and y variables will be filled in with values.
  14747. */
  14748. bool next();
  14749. enum PathElementType
  14750. {
  14751. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  14752. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  14753. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  14754. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  14755. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  14756. };
  14757. PathElementType elementType;
  14758. float x1, y1, x2, y2, x3, y3;
  14759. private:
  14760. const Path& path;
  14761. int index;
  14762. Iterator (const Iterator&);
  14763. const Iterator& operator= (const Iterator&);
  14764. };
  14765. /** Loads a stored path from a data stream.
  14766. The data in the stream must have been written using writePathToStream().
  14767. Note that this will append the stored path to whatever is currently in
  14768. this path, so you might need to call clear() beforehand.
  14769. @see loadPathFromData, writePathToStream
  14770. */
  14771. void loadPathFromStream (InputStream& source);
  14772. /** Loads a stored path from a block of data.
  14773. This is similar to loadPathFromStream(), but just reads from a block
  14774. of data. Useful if you're including stored shapes in your code as a
  14775. block of static data.
  14776. @see loadPathFromStream, writePathToStream
  14777. */
  14778. void loadPathFromData (const unsigned char* const data,
  14779. const int numberOfBytes) throw();
  14780. /** Stores the path by writing it out to a stream.
  14781. After writing out a path, you can reload it using loadPathFromStream().
  14782. @see loadPathFromStream, loadPathFromData
  14783. */
  14784. void writePathToStream (OutputStream& destination) const;
  14785. /** Creates a string containing a textual representation of this path.
  14786. @see restoreFromString
  14787. */
  14788. const String toString() const;
  14789. /** Restores this path from a string that was created with the toString() method.
  14790. @see toString()
  14791. */
  14792. void restoreFromString (const String& stringVersion);
  14793. juce_UseDebuggingNewOperator
  14794. private:
  14795. friend class PathFlatteningIterator;
  14796. friend class Path::Iterator;
  14797. ArrayAllocationBase <float> data;
  14798. int numElements;
  14799. float pathXMin, pathXMax, pathYMin, pathYMax;
  14800. bool useNonZeroWinding;
  14801. static const float lineMarker;
  14802. static const float moveMarker;
  14803. static const float quadMarker;
  14804. static const float cubicMarker;
  14805. static const float closeSubPathMarker;
  14806. };
  14807. #endif // __JUCE_PATH_JUCEHEADER__
  14808. /********* End of inlined file: juce_Path.h *********/
  14809. class Font;
  14810. class CustomTypefaceGlyphInfo;
  14811. /** A typeface represents a size-independent font.
  14812. This base class is abstract, but calling createSystemTypefaceFor() will return
  14813. a platform-specific subclass that can be used.
  14814. The CustomTypeface subclass allow you to build your own typeface, and to
  14815. load and save it in the Juce typeface format.
  14816. Normally you should never need to deal directly with Typeface objects - the Font
  14817. class does everything you typically need for rendering text.
  14818. @see CustomTypeface, Font
  14819. */
  14820. class JUCE_API Typeface : public ReferenceCountedObject
  14821. {
  14822. public:
  14823. /** A handy typedef for a pointer to a typeface. */
  14824. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  14825. /** Returns the name of the typeface.
  14826. @see Font::getTypefaceName
  14827. */
  14828. const String getName() const throw() { return name; }
  14829. /** Creates a new system typeface. */
  14830. static const Ptr createSystemTypefaceFor (const Font& font);
  14831. /** Destructor. */
  14832. virtual ~Typeface();
  14833. /** Returns the ascent of the font, as a proportion of its height.
  14834. The height is considered to always be normalised as 1.0, so this will be a
  14835. value less that 1.0, indicating the proportion of the font that lies above
  14836. its baseline.
  14837. */
  14838. virtual float getAscent() const = 0;
  14839. /** Returns the descent of the font, as a proportion of its height.
  14840. The height is considered to always be normalised as 1.0, so this will be a
  14841. value less that 1.0, indicating the proportion of the font that lies below
  14842. its baseline.
  14843. */
  14844. virtual float getDescent() const = 0;
  14845. /** Measures the width of a line of text.
  14846. The distance returned is based on the font having an normalised height of 1.0.
  14847. You should never need to call this directly! Use Font::getStringWidth() instead!
  14848. */
  14849. virtual float getStringWidth (const String& text) = 0;
  14850. /** Converts a line of text into its glyph numbers and their positions.
  14851. The distances returned are based on the font having an normalised height of 1.0.
  14852. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  14853. */
  14854. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  14855. /** Returns the outline for a glyph.
  14856. The path returned will be normalised to a font height of 1.0.
  14857. */
  14858. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  14859. juce_UseDebuggingNewOperator
  14860. protected:
  14861. String name;
  14862. Typeface (const String& name) throw();
  14863. private:
  14864. Typeface (const Typeface&);
  14865. const Typeface& operator= (const Typeface&);
  14866. };
  14867. /** A typeface that can be populated with custom glyphs.
  14868. You can create a CustomTypeface if you need one that contains your own glyphs,
  14869. or if you need to load a typeface from a Juce-formatted binary stream.
  14870. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  14871. to copy glyphs into this face.
  14872. @see Typeface, Font
  14873. */
  14874. class JUCE_API CustomTypeface : public Typeface
  14875. {
  14876. public:
  14877. /** Creates a new, empty typeface. */
  14878. CustomTypeface();
  14879. /** Loads a typeface from a previously saved stream.
  14880. The stream must have been created by writeToStream().
  14881. @see writeToStream
  14882. */
  14883. CustomTypeface (InputStream& serialisedTypefaceStream);
  14884. /** Destructor. */
  14885. ~CustomTypeface();
  14886. /** Resets this typeface, deleting all its glyphs and settings. */
  14887. void clear();
  14888. /** Sets the vital statistics for the typeface.
  14889. @param name the typeface's name
  14890. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  14891. the value that will be returned by Typeface::getAscent(). The
  14892. descent is assumed to be (1.0 - ascent)
  14893. @param isBold should be true if the typeface is bold
  14894. @param isItalic should be true if the typeface is italic
  14895. @param defaultCharacter the character to be used as a replacement if there's
  14896. no glyph available for the character that's being drawn
  14897. */
  14898. void setCharacteristics (const String& name, const float ascent,
  14899. const bool isBold, const bool isItalic,
  14900. const juce_wchar defaultCharacter) throw();
  14901. /** Adds a glyph to the typeface.
  14902. The path that is passed in is normalised so that the font height is 1.0, and its
  14903. origin is the anchor point of the character on its baseline.
  14904. The width is the nominal width of the character, and any extra kerning values that
  14905. are specified will be added to this width.
  14906. */
  14907. void addGlyph (const juce_wchar character, const Path& path, const float width) throw();
  14908. /** Specifies an extra kerning amount to be used between a pair of characters.
  14909. The amount will be added to the nominal width of the first character when laying out a string.
  14910. */
  14911. void addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw();
  14912. /** Adds a range of glyphs from another typeface.
  14913. This will attempt to pull in the paths and kerning information from another typeface and
  14914. add it to this one.
  14915. */
  14916. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  14917. /** Saves this typeface as a Juce-formatted font file.
  14918. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  14919. constructor.
  14920. */
  14921. bool writeToStream (OutputStream& outputStream);
  14922. // The following methods implement the basic Typeface behaviour.
  14923. float getAscent() const;
  14924. float getDescent() const;
  14925. float getStringWidth (const String& text);
  14926. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  14927. bool getOutlineForGlyph (int glyphNumber, Path& path);
  14928. int getGlyphForCharacter (juce_wchar character);
  14929. juce_UseDebuggingNewOperator
  14930. protected:
  14931. juce_wchar defaultCharacter;
  14932. float ascent;
  14933. bool isBold, isItalic;
  14934. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  14935. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  14936. particular character and there's no corresponding glyph, they'll call this
  14937. method so that a subclass can try to add that glyph, returning true if it
  14938. manages to do so.
  14939. */
  14940. virtual bool loadGlyphIfPossible (const juce_wchar characterNeeded);
  14941. private:
  14942. OwnedArray <CustomTypefaceGlyphInfo> glyphs;
  14943. short lookupTable [128];
  14944. CustomTypeface (const CustomTypeface&);
  14945. const CustomTypeface& operator= (const CustomTypeface&);
  14946. CustomTypefaceGlyphInfo* findGlyph (const juce_wchar character, const bool loadIfNeeded) throw();
  14947. CustomTypefaceGlyphInfo* findGlyphSubstituting (const juce_wchar character) throw();
  14948. };
  14949. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  14950. /********* End of inlined file: juce_Typeface.h *********/
  14951. class LowLevelGraphicsContext;
  14952. /**
  14953. Represents a particular font, including its size, style, etc.
  14954. Apart from the typeface to be used, a Font object also dictates whether
  14955. the font is bold, italic, underlined, how big it is, and its kerning and
  14956. horizontal scale factor.
  14957. @see Typeface
  14958. */
  14959. class JUCE_API Font
  14960. {
  14961. public:
  14962. /** A combination of these values is used by the constructor to specify the
  14963. style of font to use.
  14964. */
  14965. enum FontStyleFlags
  14966. {
  14967. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  14968. bold = 1, /**< boldens the font. @see setStyleFlags */
  14969. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  14970. underlined = 4 /**< underlines the font. @see setStyleFlags */
  14971. };
  14972. /** Creates a sans-serif font in a given size.
  14973. @param fontHeight the height in pixels (can be fractional)
  14974. @param styleFlags the style to use - this can be a combination of the
  14975. Font::bold, Font::italic and Font::underlined, or
  14976. just Font::plain for the normal style.
  14977. @see FontStyleFlags, getDefaultSansSerifFontName
  14978. */
  14979. Font (const float fontHeight,
  14980. const int styleFlags = plain) throw();
  14981. /** Creates a font with a given typeface and parameters.
  14982. @param typefaceName the name of the typeface to use
  14983. @param fontHeight the height in pixels (can be fractional)
  14984. @param styleFlags the style to use - this can be a combination of the
  14985. Font::bold, Font::italic and Font::underlined, or
  14986. just Font::plain for the normal style.
  14987. @see FontStyleFlags, getDefaultSansSerifFontName
  14988. */
  14989. Font (const String& typefaceName,
  14990. const float fontHeight,
  14991. const int styleFlags) throw();
  14992. /** Creates a copy of another Font object. */
  14993. Font (const Font& other) throw();
  14994. /** Creates a font for a typeface. */
  14995. Font (const Typeface::Ptr& typeface) throw();
  14996. /** Creates a basic sans-serif font at a default height.
  14997. You should use one of the other constructors for creating a font that you're planning
  14998. on drawing with - this constructor is here to help initialise objects before changing
  14999. the font's settings later.
  15000. */
  15001. Font() throw();
  15002. /** Copies this font from another one. */
  15003. const Font& operator= (const Font& other) throw();
  15004. bool operator== (const Font& other) const throw();
  15005. bool operator!= (const Font& other) const throw();
  15006. /** Destructor. */
  15007. ~Font() throw();
  15008. /** Changes the name of the typeface family.
  15009. e.g. "Arial", "Courier", etc.
  15010. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  15011. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  15012. but are generic names that are used to represent the various default fonts.
  15013. If you need to know the exact typeface name being used, you can call
  15014. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  15015. If a suitable font isn't found on the machine, it'll just use a default instead.
  15016. */
  15017. void setTypefaceName (const String& faceName) throw();
  15018. /** Returns the name of the typeface family that this font uses.
  15019. e.g. "Arial", "Courier", etc.
  15020. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  15021. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  15022. but are generic names that are used to represent the various default fonts.
  15023. If you need to know the exact typeface name being used, you can call
  15024. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  15025. */
  15026. const String& getTypefaceName() const throw() { return font->typefaceName; }
  15027. /** Returns a typeface name that represents the default sans-serif font.
  15028. This is also the typeface that will be used when a font is created without
  15029. specifying any typeface details.
  15030. Note that this method just returns a generic placeholder string that means "the default
  15031. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  15032. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  15033. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  15034. */
  15035. static const String getDefaultSansSerifFontName() throw();
  15036. /** Returns a typeface name that represents the default sans-serif font.
  15037. Note that this method just returns a generic placeholder string that means "the default
  15038. serif font" - it's not the actual name of this font. To get the actual name, use
  15039. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  15040. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  15041. */
  15042. static const String getDefaultSerifFontName() throw();
  15043. /** Returns a typeface name that represents the default sans-serif font.
  15044. Note that this method just returns a generic placeholder string that means "the default
  15045. monospaced font" - it's not the actual name of this font. To get the actual name, use
  15046. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  15047. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  15048. */
  15049. static const String getDefaultMonospacedFontName() throw();
  15050. /** Returns the typeface names of the default fonts on the current platform. */
  15051. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  15052. /** Returns the total height of this font.
  15053. This is the maximum height, from the top of the ascent to the bottom of the
  15054. descenders.
  15055. @see setHeight, setHeightWithoutChangingWidth, getAscent
  15056. */
  15057. float getHeight() const throw() { return font->height; }
  15058. /** Changes the font's height.
  15059. @see getHeight, setHeightWithoutChangingWidth
  15060. */
  15061. void setHeight (float newHeight) throw();
  15062. /** Changes the font's height without changing its width.
  15063. This alters the horizontal scale to compensate for the change in height.
  15064. */
  15065. void setHeightWithoutChangingWidth (float newHeight) throw();
  15066. /** Returns the height of the font above its baseline.
  15067. This is the maximum height from the baseline to the top.
  15068. @see getHeight, getDescent
  15069. */
  15070. float getAscent() const throw();
  15071. /** Returns the amount that the font descends below its baseline.
  15072. This is calculated as (getHeight() - getAscent()).
  15073. @see getAscent, getHeight
  15074. */
  15075. float getDescent() const throw();
  15076. /** Returns the font's style flags.
  15077. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  15078. enum, to describe whether the font is bold, italic, etc.
  15079. @see FontStyleFlags
  15080. */
  15081. int getStyleFlags() const throw() { return font->styleFlags; }
  15082. /** Changes the font's style.
  15083. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  15084. enum, to set the font's properties
  15085. @see FontStyleFlags
  15086. */
  15087. void setStyleFlags (const int newFlags) throw();
  15088. /** Makes the font bold or non-bold. */
  15089. void setBold (const bool shouldBeBold) throw();
  15090. /** Returns true if the font is bold. */
  15091. bool isBold() const throw();
  15092. /** Makes the font italic or non-italic. */
  15093. void setItalic (const bool shouldBeItalic) throw();
  15094. /** Returns true if the font is italic. */
  15095. bool isItalic() const throw();
  15096. /** Makes the font underlined or non-underlined. */
  15097. void setUnderline (const bool shouldBeUnderlined) throw();
  15098. /** Returns true if the font is underlined. */
  15099. bool isUnderlined() const throw();
  15100. /** Changes the font's horizontal scale factor.
  15101. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  15102. narrower, greater than 1.0 will be stretched out.
  15103. */
  15104. void setHorizontalScale (const float scaleFactor) throw();
  15105. /** Returns the font's horizontal scale.
  15106. A value of 1.0 is the normal scale, less than this will be narrower, greater
  15107. than 1.0 will be stretched out.
  15108. @see setHorizontalScale
  15109. */
  15110. float getHorizontalScale() const throw() { return font->horizontalScale; }
  15111. /** Changes the font's kerning.
  15112. @param extraKerning a multiple of the font's height that will be added
  15113. to space between the characters. So a value of zero is
  15114. normal spacing, positive values spread the letters out,
  15115. negative values make them closer together.
  15116. */
  15117. void setExtraKerningFactor (const float extraKerning) throw();
  15118. /** Returns the font's kerning.
  15119. This is the extra space added between adjacent characters, as a proportion
  15120. of the font's height.
  15121. A value of zero is normal spacing, positive values will spread the letters
  15122. out more, and negative values make them closer together.
  15123. */
  15124. float getExtraKerningFactor() const throw() { return font->kerning; }
  15125. /** Changes all the font's characteristics with one call. */
  15126. void setSizeAndStyle (float newHeight,
  15127. const int newStyleFlags,
  15128. const float newHorizontalScale,
  15129. const float newKerningAmount) throw();
  15130. /** Returns the total width of a string as it would be drawn using this font.
  15131. For a more accurate floating-point result, use getStringWidthFloat().
  15132. */
  15133. int getStringWidth (const String& text) const throw();
  15134. /** Returns the total width of a string as it would be drawn using this font.
  15135. @see getStringWidth
  15136. */
  15137. float getStringWidthFloat (const String& text) const throw();
  15138. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  15139. An extra x offset is added at the end of the run, to indicate where the right hand
  15140. edge of the last character is.
  15141. */
  15142. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  15143. /** Returns the typeface used by this font.
  15144. Note that the object returned may go out of scope if this font is deleted
  15145. or has its style changed.
  15146. */
  15147. Typeface* getTypeface() const throw();
  15148. /** Creates an array of Font objects to represent all the fonts on the system.
  15149. If you just need the names of the typefaces, you can also use
  15150. findAllTypefaceNames() instead.
  15151. @param results the array to which new Font objects will be added.
  15152. */
  15153. static void findFonts (OwnedArray<Font>& results) throw();
  15154. /** Returns a list of all the available typeface names.
  15155. The names returned can be passed into setTypefaceName().
  15156. You can use this instead of findFonts() if you only need their names, and not
  15157. font objects.
  15158. */
  15159. static const StringArray findAllTypefaceNames() throw();
  15160. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  15161. in the requested typeface.
  15162. */
  15163. static const String getFallbackFontName() throw();
  15164. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  15165. available in whatever font you're trying to use.
  15166. */
  15167. static void setFallbackFontName (const String& name) throw();
  15168. juce_UseDebuggingNewOperator
  15169. private:
  15170. friend class FontGlyphAlphaMap;
  15171. friend class TypefaceCache;
  15172. class SharedFontInternal : public ReferenceCountedObject
  15173. {
  15174. public:
  15175. SharedFontInternal (const String& typefaceName, const float height, const float horizontalScale,
  15176. const float kerning, const float ascent, const int styleFlags,
  15177. Typeface* const typeface) throw();
  15178. SharedFontInternal (const SharedFontInternal& other) throw();
  15179. String typefaceName;
  15180. float height, horizontalScale, kerning, ascent;
  15181. int styleFlags;
  15182. Typeface::Ptr typeface;
  15183. };
  15184. ReferenceCountedObjectPtr <SharedFontInternal> font;
  15185. void dupeInternalIfShared() throw();
  15186. };
  15187. #endif // __JUCE_FONT_JUCEHEADER__
  15188. /********* End of inlined file: juce_Font.h *********/
  15189. /********* Start of inlined file: juce_PathStrokeType.h *********/
  15190. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  15191. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  15192. /**
  15193. Describes a type of stroke used to render a solid outline along a path.
  15194. A PathStrokeType object can be used directly to create the shape of an outline
  15195. around a path, and is used by Graphics::strokePath to specify the type of
  15196. stroke to draw.
  15197. @see Path, Graphics::strokePath
  15198. */
  15199. class JUCE_API PathStrokeType
  15200. {
  15201. public:
  15202. /** The type of shape to use for the corners between two adjacent line segments. */
  15203. enum JointStyle
  15204. {
  15205. mitered, /**< Indicates that corners should be drawn with sharp joints.
  15206. Note that for angles that curve back on themselves, drawing a
  15207. mitre could require extending the point too far away from the
  15208. path, so a mitre limit is imposed and any corners that exceed it
  15209. are drawn as bevelled instead. */
  15210. curved, /**< Indicates that corners should be drawn as rounded-off. */
  15211. beveled /**< Indicates that corners should be drawn with a line flattening their
  15212. outside edge. */
  15213. };
  15214. /** The type shape to use for the ends of lines. */
  15215. enum EndCapStyle
  15216. {
  15217. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  15218. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  15219. the thickness of the stroke. */
  15220. rounded /**< Ends of lines are rounded-off with a circular shape. */
  15221. };
  15222. /** Creates a stroke type.
  15223. @param strokeThickness the width of the line to use
  15224. @param jointStyle the type of joints to use for corners
  15225. @param endStyle the type of end-caps to use for the ends of open paths.
  15226. */
  15227. PathStrokeType (const float strokeThickness,
  15228. const JointStyle jointStyle = mitered,
  15229. const EndCapStyle endStyle = butt) throw();
  15230. /** Createes a copy of another stroke type. */
  15231. PathStrokeType (const PathStrokeType& other) throw();
  15232. /** Copies another stroke onto this one. */
  15233. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  15234. /** Destructor. */
  15235. ~PathStrokeType() throw();
  15236. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  15237. @param destPath the resultant stroked outline shape will be copied into this path.
  15238. Note that it's ok for the source and destination Paths to be
  15239. the same object, so you can easily turn a path into a stroked version
  15240. of itself.
  15241. @param sourcePath the path to use as the source
  15242. @param transform an optional transform to apply to the points from the source path
  15243. as they are being used
  15244. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  15245. a higher resolution, which improved the quality if you'll later want
  15246. to enlarge the stroked path
  15247. @see createDashedStroke
  15248. */
  15249. void createStrokedPath (Path& destPath,
  15250. const Path& sourcePath,
  15251. const AffineTransform& transform = AffineTransform::identity,
  15252. const float extraAccuracy = 1.0f) const throw();
  15253. /** Applies this stroke type to a path, creating a dashed line.
  15254. This is similar to createStrokedPath, but uses the array passed in to
  15255. break the stroke up into a series of dashes.
  15256. @param destPath the resultant stroked outline shape will be copied into this path.
  15257. Note that it's ok for the source and destination Paths to be
  15258. the same object, so you can easily turn a path into a stroked version
  15259. of itself.
  15260. @param sourcePath the path to use as the source
  15261. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  15262. a line of length 2, then skip a length of 3, then add a line of length 4,
  15263. skip 5, and keep repeating this pattern.
  15264. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  15265. an even number, otherwise the pattern will get out of step as it
  15266. repeats.
  15267. @param transform an optional transform to apply to the points from the source path
  15268. as they are being used
  15269. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  15270. a higher resolution, which improved the quality if you'll later want
  15271. to enlarge the stroked path
  15272. */
  15273. void createDashedStroke (Path& destPath,
  15274. const Path& sourcePath,
  15275. const float* dashLengths,
  15276. int numDashLengths,
  15277. const AffineTransform& transform = AffineTransform::identity,
  15278. const float extraAccuracy = 1.0f) const throw();
  15279. /** Returns the stroke thickness. */
  15280. float getStrokeThickness() const throw() { return thickness; }
  15281. /** Returns the joint style. */
  15282. JointStyle getJointStyle() const throw() { return jointStyle; }
  15283. /** Returns the end-cap style. */
  15284. EndCapStyle getEndStyle() const throw() { return endStyle; }
  15285. juce_UseDebuggingNewOperator
  15286. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  15287. bool operator== (const PathStrokeType& other) const throw();
  15288. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  15289. bool operator!= (const PathStrokeType& other) const throw();
  15290. private:
  15291. float thickness;
  15292. JointStyle jointStyle;
  15293. EndCapStyle endStyle;
  15294. };
  15295. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  15296. /********* End of inlined file: juce_PathStrokeType.h *********/
  15297. /********* Start of inlined file: juce_Line.h *********/
  15298. #ifndef __JUCE_LINE_JUCEHEADER__
  15299. #define __JUCE_LINE_JUCEHEADER__
  15300. /**
  15301. Represents a line, using 32-bit float co-ordinates.
  15302. This class contains a bunch of useful methods for various geometric
  15303. tasks.
  15304. @see Point, Rectangle, Path, Graphics::drawLine
  15305. */
  15306. class JUCE_API Line
  15307. {
  15308. public:
  15309. /** Creates a line, using (0, 0) as its start and end points. */
  15310. Line() throw();
  15311. /** Creates a copy of another line. */
  15312. Line (const Line& other) throw();
  15313. /** Creates a line based on the co-ordinates of its start and end points. */
  15314. Line (const float startX,
  15315. const float startY,
  15316. const float endX,
  15317. const float endY) throw();
  15318. /** Creates a line from its start and end points. */
  15319. Line (const Point& start,
  15320. const Point& end) throw();
  15321. /** Copies a line from another one. */
  15322. const Line& operator= (const Line& other) throw();
  15323. /** Destructor. */
  15324. ~Line() throw();
  15325. /** Returns the x co-ordinate of the line's start point. */
  15326. inline float getStartX() const throw() { return startX; }
  15327. /** Returns the y co-ordinate of the line's start point. */
  15328. inline float getStartY() const throw() { return startY; }
  15329. /** Returns the x co-ordinate of the line's end point. */
  15330. inline float getEndX() const throw() { return endX; }
  15331. /** Returns the y co-ordinate of the line's end point. */
  15332. inline float getEndY() const throw() { return endY; }
  15333. /** Returns the line's start point. */
  15334. const Point getStart() const throw();
  15335. /** Returns the line's end point. */
  15336. const Point getEnd() const throw();
  15337. /** Changes this line's start point */
  15338. void setStart (const float newStartX,
  15339. const float newStartY) throw();
  15340. /** Changes this line's end point */
  15341. void setEnd (const float newEndX,
  15342. const float newEndY) throw();
  15343. /** Changes this line's start point */
  15344. void setStart (const Point& newStart) throw();
  15345. /** Changes this line's end point */
  15346. void setEnd (const Point& newEnd) throw();
  15347. /** Applies an affine transform to the line's start and end points. */
  15348. void applyTransform (const AffineTransform& transform) throw();
  15349. /** Returns the length of the line. */
  15350. float getLength() const throw();
  15351. /** Returns true if the line's start and end x co-ordinates are the same. */
  15352. bool isVertical() const throw();
  15353. /** Returns true if the line's start and end y co-ordinates are the same. */
  15354. bool isHorizontal() const throw();
  15355. /** Returns the line's angle.
  15356. This value is the number of radians clockwise from the 3 o'clock direction,
  15357. where the line's start point is considered to be at the centre.
  15358. */
  15359. float getAngle() const throw();
  15360. /** Compares two lines. */
  15361. bool operator== (const Line& other) const throw();
  15362. /** Compares two lines. */
  15363. bool operator!= (const Line& other) const throw();
  15364. /** Finds the intersection between two lines.
  15365. @param line the other line
  15366. @param intersectionX the x co-ordinate of the point where the lines meet (or
  15367. where they would meet if they were infinitely long)
  15368. the intersection (if the lines intersect). If the lines
  15369. are parallel, this will just be set to the position
  15370. of one of the line's endpoints.
  15371. @param intersectionY the y co-ordinate of the point where the lines meet
  15372. @returns true if the line segments intersect; false if they dont. Even if they
  15373. don't intersect, the intersection co-ordinates returned will still
  15374. be valid
  15375. */
  15376. bool intersects (const Line& line,
  15377. float& intersectionX,
  15378. float& intersectionY) const throw();
  15379. /** Returns the location of the point which is a given distance along this line.
  15380. @param distanceFromStart the distance to move along the line from its
  15381. start point. This value can be negative or longer
  15382. than the line itself
  15383. @see getPointAlongLineProportionally
  15384. */
  15385. const Point getPointAlongLine (const float distanceFromStart) const throw();
  15386. /** Returns a point which is a certain distance along and to the side of this line.
  15387. This effectively moves a given distance along the line, then another distance
  15388. perpendicularly to this, and returns the resulting position.
  15389. @param distanceFromStart the distance to move along the line from its
  15390. start point. This value can be negative or longer
  15391. than the line itself
  15392. @param perpendicularDistance how far to move sideways from the line. If you're
  15393. looking along the line from its start towards its
  15394. end, then a positive value here will move to the
  15395. right, negative value move to the left.
  15396. */
  15397. const Point getPointAlongLine (const float distanceFromStart,
  15398. const float perpendicularDistance) const throw();
  15399. /** Returns the location of the point which is a given distance along this line
  15400. proportional to the line's length.
  15401. @param proportionOfLength the distance to move along the line from its
  15402. start point, in multiples of the line's length.
  15403. So a value of 0.0 will return the line's start point
  15404. and a value of 1.0 will return its end point. (This value
  15405. can be negative or greater than 1.0).
  15406. @see getPointAlongLine
  15407. */
  15408. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  15409. /** Returns the smallest distance between this line segment and a given point.
  15410. So if the point is close to the line, this will return the perpendicular
  15411. distance from the line; if the point is a long way beyond one of the line's
  15412. end-point's, it'll return the straight-line distance to the nearest end-point.
  15413. @param x x position of the point to test
  15414. @param y y position of the point to test
  15415. @returns the point's distance from the line
  15416. @see getPositionAlongLineOfNearestPoint
  15417. */
  15418. float getDistanceFromLine (const float x,
  15419. const float y) const throw();
  15420. /** Finds the point on this line which is nearest to a given point, and
  15421. returns its position as a proportional position along the line.
  15422. @param x x position of the point to test
  15423. @param y y position of the point to test
  15424. @returns a value 0 to 1.0 which is the distance along this line from the
  15425. line's start to the point which is nearest to the point passed-in. To
  15426. turn this number into a position, use getPointAlongLineProportionally().
  15427. @see getDistanceFromLine, getPointAlongLineProportionally
  15428. */
  15429. float findNearestPointTo (const float x,
  15430. const float y) const throw();
  15431. /** Returns true if the given point lies above this line.
  15432. The return value is true if the point's y coordinate is less than the y
  15433. coordinate of this line at the given x (assuming the line extends infinitely
  15434. in both directions).
  15435. */
  15436. bool isPointAbove (const float x, const float y) const throw();
  15437. /** Returns a shortened copy of this line.
  15438. This will chop off part of the start of this line by a certain amount, (leaving the
  15439. end-point the same), and return the new line.
  15440. */
  15441. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  15442. /** Returns a shortened copy of this line.
  15443. This will chop off part of the end of this line by a certain amount, (leaving the
  15444. start-point the same), and return the new line.
  15445. */
  15446. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  15447. /** Cuts off parts of this line to keep the parts that are either inside or
  15448. outside a path.
  15449. Note that this isn't smart enough to cope with situations where the
  15450. line would need to be cut into multiple pieces to correctly clip against
  15451. a re-entrant shape.
  15452. @param path the path to clip against
  15453. @param keepSectionOutsidePath if true, it's the section outside the path
  15454. that will be kept; if false its the section inside
  15455. the path
  15456. @returns true if the line was changed.
  15457. */
  15458. bool clipToPath (const Path& path,
  15459. const bool keepSectionOutsidePath) throw();
  15460. juce_UseDebuggingNewOperator
  15461. private:
  15462. float startX, startY, endX, endY;
  15463. };
  15464. #endif // __JUCE_LINE_JUCEHEADER__
  15465. /********* End of inlined file: juce_Line.h *********/
  15466. /********* Start of inlined file: juce_Colours.h *********/
  15467. #ifndef __JUCE_COLOURS_JUCEHEADER__
  15468. #define __JUCE_COLOURS_JUCEHEADER__
  15469. /********* Start of inlined file: juce_Colour.h *********/
  15470. #ifndef __JUCE_COLOUR_JUCEHEADER__
  15471. #define __JUCE_COLOUR_JUCEHEADER__
  15472. /********* Start of inlined file: juce_PixelFormats.h *********/
  15473. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  15474. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  15475. #if JUCE_MSVC
  15476. #pragma pack (push, 1)
  15477. #define PACKED
  15478. #elif JUCE_GCC
  15479. #define PACKED __attribute__((packed))
  15480. #else
  15481. #define PACKED
  15482. #endif
  15483. class PixelRGB;
  15484. class PixelAlpha;
  15485. /**
  15486. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  15487. operations with it.
  15488. This is used internally by the imaging classes.
  15489. @see PixelRGB
  15490. */
  15491. class JUCE_API PixelARGB
  15492. {
  15493. public:
  15494. /** Creates a pixel without defining its colour. */
  15495. PixelARGB() throw() {}
  15496. ~PixelARGB() throw() {}
  15497. /** Creates a pixel from a 32-bit argb value.
  15498. */
  15499. PixelARGB (const uint32 argb_) throw()
  15500. : argb (argb_)
  15501. {
  15502. }
  15503. forcedinline uint32 getARGB() const throw() { return argb; }
  15504. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  15505. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  15506. forcedinline uint8 getAlpha() const throw() { return components.a; }
  15507. forcedinline uint8 getRed() const throw() { return components.r; }
  15508. forcedinline uint8 getGreen() const throw() { return components.g; }
  15509. forcedinline uint8 getBlue() const throw() { return components.b; }
  15510. /** Blends another pixel onto this one.
  15511. This takes into account the opacity of the pixel being overlaid, and blends
  15512. it accordingly.
  15513. */
  15514. forcedinline void blend (const PixelARGB& src) throw()
  15515. {
  15516. uint32 sargb = src.getARGB();
  15517. const uint32 alpha = 0x100 - (sargb >> 24);
  15518. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15519. sargb += 0xff00ff00 & (getAG() * alpha);
  15520. argb = sargb;
  15521. }
  15522. /** Blends another pixel onto this one.
  15523. This takes into account the opacity of the pixel being overlaid, and blends
  15524. it accordingly.
  15525. */
  15526. forcedinline void blend (const PixelAlpha& src) throw();
  15527. /** Blends another pixel onto this one.
  15528. This takes into account the opacity of the pixel being overlaid, and blends
  15529. it accordingly.
  15530. */
  15531. forcedinline void blend (const PixelRGB& src) throw();
  15532. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15533. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15534. being used, so this can blend semi-transparently from a PixelRGB argument.
  15535. */
  15536. template <class Pixel>
  15537. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15538. {
  15539. ++extraAlpha;
  15540. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  15541. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  15542. const uint32 alpha = 0x100 - (sargb >> 24);
  15543. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15544. sargb += 0xff00ff00 & (getAG() * alpha);
  15545. argb = sargb;
  15546. }
  15547. /** Blends another pixel with this one, creating a colour that is somewhere
  15548. between the two, as specified by the amount.
  15549. */
  15550. template <class Pixel>
  15551. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15552. {
  15553. uint32 drb = getRB();
  15554. drb += (((src.getRB() - drb) * amount) >> 8);
  15555. drb &= 0x00ff00ff;
  15556. uint32 dag = getAG();
  15557. dag += (((src.getAG() - dag) * amount) >> 8);
  15558. dag &= 0x00ff00ff;
  15559. dag <<= 8;
  15560. dag |= drb;
  15561. argb = dag;
  15562. }
  15563. /** Copies another pixel colour over this one.
  15564. This doesn't blend it - this colour is simply replaced by the other one.
  15565. */
  15566. template <class Pixel>
  15567. forcedinline void set (const Pixel& src) throw()
  15568. {
  15569. argb = src.getARGB();
  15570. }
  15571. /** Replaces the colour's alpha value with another one. */
  15572. forcedinline void setAlpha (const uint8 newAlpha) throw()
  15573. {
  15574. components.a = newAlpha;
  15575. }
  15576. /** Multiplies the colour's alpha value with another one. */
  15577. forcedinline void multiplyAlpha (int multiplier) throw()
  15578. {
  15579. ++multiplier;
  15580. argb = ((multiplier * getAG()) & 0xff00ff00)
  15581. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  15582. }
  15583. forcedinline void multiplyAlpha (const float multiplier) throw()
  15584. {
  15585. multiplyAlpha ((int) (multiplier * 256.0f));
  15586. }
  15587. /** Sets the pixel's colour from individual components. */
  15588. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  15589. {
  15590. components.b = b;
  15591. components.g = g;
  15592. components.r = r;
  15593. components.a = a;
  15594. }
  15595. /** Premultiplies the pixel's RGB values by its alpha. */
  15596. forcedinline void premultiply() throw()
  15597. {
  15598. const uint32 alpha = components.a;
  15599. if (alpha < 0xff)
  15600. {
  15601. if (alpha == 0)
  15602. {
  15603. components.b = 0;
  15604. components.g = 0;
  15605. components.r = 0;
  15606. }
  15607. else
  15608. {
  15609. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  15610. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  15611. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  15612. }
  15613. }
  15614. }
  15615. /** Unpremultiplies the pixel's RGB values. */
  15616. forcedinline void unpremultiply() throw()
  15617. {
  15618. const uint32 alpha = components.a;
  15619. if (alpha < 0xff)
  15620. {
  15621. if (alpha == 0)
  15622. {
  15623. components.b = 0;
  15624. components.g = 0;
  15625. components.r = 0;
  15626. }
  15627. else
  15628. {
  15629. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  15630. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  15631. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  15632. }
  15633. }
  15634. }
  15635. forcedinline void desaturate() throw()
  15636. {
  15637. if (components.a < 0xff && components.a > 0)
  15638. {
  15639. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  15640. components.r = components.g = components.b
  15641. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  15642. }
  15643. else
  15644. {
  15645. components.r = components.g = components.b
  15646. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  15647. }
  15648. }
  15649. /** The indexes of the different components in the byte layout of this type of colour. */
  15650. #if JUCE_BIG_ENDIAN
  15651. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  15652. #else
  15653. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  15654. #endif
  15655. private:
  15656. union
  15657. {
  15658. uint32 argb;
  15659. struct
  15660. {
  15661. #if JUCE_BIG_ENDIAN
  15662. uint8 a : 8, r : 8, g : 8, b : 8;
  15663. #else
  15664. uint8 b, g, r, a;
  15665. #endif
  15666. } PACKED components;
  15667. };
  15668. } PACKED;
  15669. /**
  15670. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  15671. This is used internally by the imaging classes.
  15672. @see PixelARGB
  15673. */
  15674. class JUCE_API PixelRGB
  15675. {
  15676. public:
  15677. /** Creates a pixel without defining its colour. */
  15678. PixelRGB() throw() {}
  15679. ~PixelRGB() throw() {}
  15680. /** Creates a pixel from a 32-bit argb value.
  15681. (The argb format is that used by PixelARGB)
  15682. */
  15683. PixelRGB (const uint32 argb) throw()
  15684. {
  15685. r = (uint8) (argb >> 16);
  15686. g = (uint8) (argb >> 8);
  15687. b = (uint8) (argb);
  15688. }
  15689. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  15690. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  15691. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  15692. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  15693. forcedinline uint8 getRed() const throw() { return r; }
  15694. forcedinline uint8 getGreen() const throw() { return g; }
  15695. forcedinline uint8 getBlue() const throw() { return b; }
  15696. /** Blends another pixel onto this one.
  15697. This takes into account the opacity of the pixel being overlaid, and blends
  15698. it accordingly.
  15699. */
  15700. forcedinline void blend (const PixelARGB& src) throw()
  15701. {
  15702. uint32 sargb = src.getARGB();
  15703. const uint32 alpha = 0x100 - (sargb >> 24);
  15704. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15705. sargb += 0x0000ff00 & (g * alpha);
  15706. r = (uint8) (sargb >> 16);
  15707. g = (uint8) (sargb >> 8);
  15708. b = (uint8) sargb;
  15709. }
  15710. forcedinline void blend (const PixelRGB& src) throw()
  15711. {
  15712. set (src);
  15713. }
  15714. forcedinline void blend (const PixelAlpha& src) throw();
  15715. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15716. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15717. being used, so this can blend semi-transparently from a PixelRGB argument.
  15718. */
  15719. template <class Pixel>
  15720. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15721. {
  15722. ++extraAlpha;
  15723. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  15724. const uint32 sag = extraAlpha * src.getAG();
  15725. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  15726. const uint32 alpha = 0x100 - (sargb >> 24);
  15727. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15728. sargb += 0x0000ff00 & (g * alpha);
  15729. b = (uint8) sargb;
  15730. g = (uint8) (sargb >> 8);
  15731. r = (uint8) (sargb >> 16);
  15732. }
  15733. /** Blends another pixel with this one, creating a colour that is somewhere
  15734. between the two, as specified by the amount.
  15735. */
  15736. template <class Pixel>
  15737. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15738. {
  15739. uint32 drb = getRB();
  15740. drb += (((src.getRB() - drb) * amount) >> 8);
  15741. uint32 dag = getAG();
  15742. dag += (((src.getAG() - dag) * amount) >> 8);
  15743. b = (uint8) drb;
  15744. g = (uint8) dag;
  15745. r = (uint8) (drb >> 16);
  15746. }
  15747. /** Copies another pixel colour over this one.
  15748. This doesn't blend it - this colour is simply replaced by the other one.
  15749. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  15750. is thrown away.
  15751. */
  15752. template <class Pixel>
  15753. forcedinline void set (const Pixel& src) throw()
  15754. {
  15755. b = src.getBlue();
  15756. g = src.getGreen();
  15757. r = src.getRed();
  15758. }
  15759. /** This method is included for compatibility with the PixelARGB class. */
  15760. forcedinline void setAlpha (const uint8) throw() {}
  15761. /** Multiplies the colour's alpha value with another one. */
  15762. forcedinline void multiplyAlpha (int) throw() {}
  15763. /** Sets the pixel's colour from individual components. */
  15764. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  15765. {
  15766. r = r_;
  15767. g = g_;
  15768. b = b_;
  15769. }
  15770. /** Premultiplies the pixel's RGB values by its alpha. */
  15771. forcedinline void premultiply() throw() {}
  15772. /** Unpremultiplies the pixel's RGB values. */
  15773. forcedinline void unpremultiply() throw() {}
  15774. forcedinline void desaturate() throw()
  15775. {
  15776. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  15777. }
  15778. /** The indexes of the different components in the byte layout of this type of colour. */
  15779. #if JUCE_MAC
  15780. enum { indexR = 0, indexG = 1, indexB = 2 };
  15781. #else
  15782. enum { indexR = 2, indexG = 1, indexB = 0 };
  15783. #endif
  15784. private:
  15785. #if JUCE_MAC
  15786. uint8 r, g, b;
  15787. #else
  15788. uint8 b, g, r;
  15789. #endif
  15790. } PACKED;
  15791. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  15792. {
  15793. set (src);
  15794. }
  15795. /**
  15796. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  15797. This is used internally by the imaging classes.
  15798. @see PixelARGB, PixelRGB
  15799. */
  15800. class JUCE_API PixelAlpha
  15801. {
  15802. public:
  15803. /** Creates a pixel without defining its colour. */
  15804. PixelAlpha() throw() {}
  15805. ~PixelAlpha() throw() {}
  15806. /** Creates a pixel from a 32-bit argb value.
  15807. (The argb format is that used by PixelARGB)
  15808. */
  15809. PixelAlpha (const uint32 argb) throw()
  15810. {
  15811. a = (uint8) (argb >> 24);
  15812. }
  15813. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  15814. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  15815. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  15816. forcedinline uint8 getAlpha() const throw() { return a; }
  15817. forcedinline uint8 getRed() const throw() { return 0; }
  15818. forcedinline uint8 getGreen() const throw() { return 0; }
  15819. forcedinline uint8 getBlue() const throw() { return 0; }
  15820. /** Blends another pixel onto this one.
  15821. This takes into account the opacity of the pixel being overlaid, and blends
  15822. it accordingly.
  15823. */
  15824. template <class Pixel>
  15825. forcedinline void blend (const Pixel& src) throw()
  15826. {
  15827. const int srcA = src.getAlpha();
  15828. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  15829. }
  15830. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15831. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15832. being used, so this can blend semi-transparently from a PixelRGB argument.
  15833. */
  15834. template <class Pixel>
  15835. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15836. {
  15837. ++extraAlpha;
  15838. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  15839. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  15840. }
  15841. /** Blends another pixel with this one, creating a colour that is somewhere
  15842. between the two, as specified by the amount.
  15843. */
  15844. template <class Pixel>
  15845. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15846. {
  15847. a += ((src,getAlpha() - a) * amount) >> 8;
  15848. }
  15849. /** Copies another pixel colour over this one.
  15850. This doesn't blend it - this colour is simply replaced by the other one.
  15851. */
  15852. template <class Pixel>
  15853. forcedinline void set (const Pixel& src) throw()
  15854. {
  15855. a = src.getAlpha();
  15856. }
  15857. /** Replaces the colour's alpha value with another one. */
  15858. forcedinline void setAlpha (const uint8 newAlpha) throw()
  15859. {
  15860. a = newAlpha;
  15861. }
  15862. /** Multiplies the colour's alpha value with another one. */
  15863. forcedinline void multiplyAlpha (int multiplier) throw()
  15864. {
  15865. ++multiplier;
  15866. a = (uint8) ((a * multiplier) >> 8);
  15867. }
  15868. forcedinline void multiplyAlpha (const float multiplier) throw()
  15869. {
  15870. a = (uint8) (a * multiplier);
  15871. }
  15872. /** Sets the pixel's colour from individual components. */
  15873. forcedinline void setARGB (const uint8 a_, const uint8 r, const uint8 g, const uint8 b) throw()
  15874. {
  15875. a = a_;
  15876. }
  15877. /** Premultiplies the pixel's RGB values by its alpha. */
  15878. forcedinline void premultiply() throw()
  15879. {
  15880. }
  15881. /** Unpremultiplies the pixel's RGB values. */
  15882. forcedinline void unpremultiply() throw()
  15883. {
  15884. }
  15885. forcedinline void desaturate() throw()
  15886. {
  15887. }
  15888. private:
  15889. uint8 a : 8;
  15890. } PACKED;
  15891. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  15892. {
  15893. blend (PixelARGB (src.getARGB()));
  15894. }
  15895. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  15896. {
  15897. uint32 sargb = src.getARGB();
  15898. const uint32 alpha = 0x100 - (sargb >> 24);
  15899. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15900. sargb += 0xff00ff00 & (getAG() * alpha);
  15901. argb = sargb;
  15902. }
  15903. #if JUCE_MSVC
  15904. #pragma pack (pop)
  15905. #endif
  15906. #undef PACKED
  15907. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  15908. /********* End of inlined file: juce_PixelFormats.h *********/
  15909. /**
  15910. Represents a colour, also including a transparency value.
  15911. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  15912. */
  15913. class JUCE_API Colour
  15914. {
  15915. public:
  15916. /** Creates a transparent black colour. */
  15917. Colour() throw();
  15918. /** Creates a copy of another Colour object. */
  15919. Colour (const Colour& other) throw();
  15920. /** Creates a colour from a 32-bit ARGB value.
  15921. The format of this number is:
  15922. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  15923. All components in the range 0x00 to 0xff.
  15924. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15925. @see getPixelARGB
  15926. */
  15927. explicit Colour (const uint32 argb) throw();
  15928. /** Creates an opaque colour using 8-bit red, green and blue values */
  15929. Colour (const uint8 red,
  15930. const uint8 green,
  15931. const uint8 blue) throw();
  15932. /** Creates an opaque colour using 8-bit red, green and blue values */
  15933. static const Colour fromRGB (const uint8 red,
  15934. const uint8 green,
  15935. const uint8 blue) throw();
  15936. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  15937. Colour (const uint8 red,
  15938. const uint8 green,
  15939. const uint8 blue,
  15940. const uint8 alpha) throw();
  15941. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  15942. static const Colour fromRGBA (const uint8 red,
  15943. const uint8 green,
  15944. const uint8 blue,
  15945. const uint8 alpha) throw();
  15946. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  15947. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  15948. Values outside the valid range will be clipped.
  15949. */
  15950. Colour (const uint8 red,
  15951. const uint8 green,
  15952. const uint8 blue,
  15953. const float alpha) throw();
  15954. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  15955. static const Colour fromRGBAFloat (const uint8 red,
  15956. const uint8 green,
  15957. const uint8 blue,
  15958. const float alpha) throw();
  15959. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  15960. The floating point values must be between 0.0 and 1.0.
  15961. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15962. Values outside the valid range will be clipped.
  15963. */
  15964. Colour (const float hue,
  15965. const float saturation,
  15966. const float brightness,
  15967. const uint8 alpha) throw();
  15968. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  15969. All values must be between 0.0 and 1.0.
  15970. Numbers outside the valid range will be clipped.
  15971. */
  15972. Colour (const float hue,
  15973. const float saturation,
  15974. const float brightness,
  15975. const float alpha) throw();
  15976. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  15977. The floating point values must be between 0.0 and 1.0.
  15978. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15979. Values outside the valid range will be clipped.
  15980. */
  15981. static const Colour fromHSV (const float hue,
  15982. const float saturation,
  15983. const float brightness,
  15984. const float alpha) throw();
  15985. /** Destructor. */
  15986. ~Colour() throw();
  15987. /** Copies another Colour object. */
  15988. const Colour& operator= (const Colour& other) throw();
  15989. /** Compares two colours. */
  15990. bool operator== (const Colour& other) const throw();
  15991. /** Compares two colours. */
  15992. bool operator!= (const Colour& other) const throw();
  15993. /** Returns the red component of this colour.
  15994. @returns a value between 0x00 and 0xff.
  15995. */
  15996. uint8 getRed() const throw() { return argb.getRed(); }
  15997. /** Returns the green component of this colour.
  15998. @returns a value between 0x00 and 0xff.
  15999. */
  16000. uint8 getGreen() const throw() { return argb.getGreen(); }
  16001. /** Returns the blue component of this colour.
  16002. @returns a value between 0x00 and 0xff.
  16003. */
  16004. uint8 getBlue() const throw() { return argb.getBlue(); }
  16005. /** Returns the red component of this colour as a floating point value.
  16006. @returns a value between 0.0 and 1.0
  16007. */
  16008. float getFloatRed() const throw();
  16009. /** Returns the green component of this colour as a floating point value.
  16010. @returns a value between 0.0 and 1.0
  16011. */
  16012. float getFloatGreen() const throw();
  16013. /** Returns the blue component of this colour as a floating point value.
  16014. @returns a value between 0.0 and 1.0
  16015. */
  16016. float getFloatBlue() const throw();
  16017. /** Returns a premultiplied ARGB pixel object that represents this colour.
  16018. */
  16019. const PixelARGB getPixelARGB() const throw();
  16020. /** Returns a 32-bit integer that represents this colour.
  16021. The format of this number is:
  16022. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  16023. */
  16024. uint32 getARGB() const throw();
  16025. /** Returns the colour's alpha (opacity).
  16026. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  16027. */
  16028. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  16029. /** Returns the colour's alpha (opacity) as a floating point value.
  16030. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  16031. */
  16032. float getFloatAlpha() const throw();
  16033. /** Returns true if this colour is completely opaque.
  16034. Equivalent to (getAlpha() == 0xff).
  16035. */
  16036. bool isOpaque() const throw();
  16037. /** Returns true if this colour is completely transparent.
  16038. Equivalent to (getAlpha() == 0x00).
  16039. */
  16040. bool isTransparent() const throw();
  16041. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  16042. const Colour withAlpha (const uint8 newAlpha) const throw();
  16043. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  16044. const Colour withAlpha (const float newAlpha) const throw();
  16045. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  16046. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  16047. */
  16048. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  16049. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  16050. If the foreground colour is semi-transparent, it is blended onto this colour
  16051. accordingly.
  16052. */
  16053. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  16054. /** Returns a colour that lies somewhere between this one and another.
  16055. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  16056. is 1.0, the result is 100% of the other colour.
  16057. */
  16058. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  16059. /** Returns the colour's hue component.
  16060. The value returned is in the range 0.0 to 1.0
  16061. */
  16062. float getHue() const throw();
  16063. /** Returns the colour's saturation component.
  16064. The value returned is in the range 0.0 to 1.0
  16065. */
  16066. float getSaturation() const throw();
  16067. /** Returns the colour's brightness component.
  16068. The value returned is in the range 0.0 to 1.0
  16069. */
  16070. float getBrightness() const throw();
  16071. /** Returns the colour's hue, saturation and brightness components all at once.
  16072. The values returned are in the range 0.0 to 1.0
  16073. */
  16074. void getHSB (float& hue,
  16075. float& saturation,
  16076. float& brightness) const throw();
  16077. /** Returns a copy of this colour with a different hue. */
  16078. const Colour withHue (const float newHue) const throw();
  16079. /** Returns a copy of this colour with a different saturation. */
  16080. const Colour withSaturation (const float newSaturation) const throw();
  16081. /** Returns a copy of this colour with a different brightness.
  16082. @see brighter, darker, withMultipliedBrightness
  16083. */
  16084. const Colour withBrightness (const float newBrightness) const throw();
  16085. /** Returns a copy of this colour with it hue rotated.
  16086. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  16087. @see brighter, darker, withMultipliedBrightness
  16088. */
  16089. const Colour withRotatedHue (const float amountToRotate) const throw();
  16090. /** Returns a copy of this colour with its saturation multiplied by the given value.
  16091. The new colour's saturation is (this->getSaturation() * multiplier)
  16092. (the result is clipped to legal limits).
  16093. */
  16094. const Colour withMultipliedSaturation (const float multiplier) const throw();
  16095. /** Returns a copy of this colour with its brightness multiplied by the given value.
  16096. The new colour's saturation is (this->getBrightness() * multiplier)
  16097. (the result is clipped to legal limits).
  16098. */
  16099. const Colour withMultipliedBrightness (const float amount) const throw();
  16100. /** Returns a brighter version of this colour.
  16101. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  16102. unchanged, and higher values make it brighter
  16103. @see withMultipliedBrightness
  16104. */
  16105. const Colour brighter (float amountBrighter = 0.4f) const throw();
  16106. /** Returns a darker version of this colour.
  16107. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  16108. unchanged, and higher values make it darker
  16109. @see withMultipliedBrightness
  16110. */
  16111. const Colour darker (float amountDarker = 0.4f) const throw();
  16112. /** Returns a colour that will be clearly visible against this colour.
  16113. The amount parameter indicates how contrasting the new colour should
  16114. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  16115. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  16116. return white; Colours::white.contrasting (1.0f) will return black, etc.
  16117. */
  16118. const Colour contrasting (const float amount = 1.0f) const throw();
  16119. /** Returns a colour that contrasts against two colours.
  16120. Looks for a colour that contrasts with both of the colours passed-in.
  16121. Handy for things like choosing a highlight colour in text editors, etc.
  16122. */
  16123. static const Colour contrasting (const Colour& colour1,
  16124. const Colour& colour2) throw();
  16125. /** Returns an opaque shade of grey.
  16126. @param brightness the level of grey to return - 0 is black, 1.0 is white
  16127. */
  16128. static const Colour greyLevel (const float brightness) throw();
  16129. /** Returns a stringified version of this colour.
  16130. The string can be turned back into a colour using the fromString() method.
  16131. */
  16132. const String toString() const throw();
  16133. /** Reads the colour from a string that was created with toString().
  16134. */
  16135. static const Colour fromString (const String& encodedColourString);
  16136. juce_UseDebuggingNewOperator
  16137. private:
  16138. PixelARGB argb;
  16139. };
  16140. #endif // __JUCE_COLOUR_JUCEHEADER__
  16141. /********* End of inlined file: juce_Colour.h *********/
  16142. /**
  16143. Contains a set of predefined named colours (mostly standard HTML colours)
  16144. @see Colour, Colours::greyLevel
  16145. */
  16146. class Colours
  16147. {
  16148. public:
  16149. static JUCE_API const Colour
  16150. transparentBlack, /**< ARGB = 0x00000000 */
  16151. transparentWhite, /**< ARGB = 0x00ffffff */
  16152. black, /**< ARGB = 0xff000000 */
  16153. white, /**< ARGB = 0xffffffff */
  16154. blue, /**< ARGB = 0xff0000ff */
  16155. grey, /**< ARGB = 0xff808080 */
  16156. green, /**< ARGB = 0xff008000 */
  16157. red, /**< ARGB = 0xffff0000 */
  16158. yellow, /**< ARGB = 0xffffff00 */
  16159. aliceblue, antiquewhite, aqua, aquamarine,
  16160. azure, beige, bisque, blanchedalmond,
  16161. blueviolet, brown, burlywood, cadetblue,
  16162. chartreuse, chocolate, coral, cornflowerblue,
  16163. cornsilk, crimson, cyan, darkblue,
  16164. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  16165. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  16166. darkorchid, darkred, darksalmon, darkseagreen,
  16167. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  16168. deeppink, deepskyblue, dimgrey, dodgerblue,
  16169. firebrick, floralwhite, forestgreen, fuchsia,
  16170. gainsboro, gold, goldenrod, greenyellow,
  16171. honeydew, hotpink, indianred, indigo,
  16172. ivory, khaki, lavender, lavenderblush,
  16173. lemonchiffon, lightblue, lightcoral, lightcyan,
  16174. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  16175. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  16176. lightsteelblue, lightyellow, lime, limegreen,
  16177. linen, magenta, maroon, mediumaquamarine,
  16178. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  16179. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  16180. midnightblue, mintcream, mistyrose, navajowhite,
  16181. navy, oldlace, olive, olivedrab,
  16182. orange, orangered, orchid, palegoldenrod,
  16183. palegreen, paleturquoise, palevioletred, papayawhip,
  16184. peachpuff, peru, pink, plum,
  16185. powderblue, purple, rosybrown, royalblue,
  16186. saddlebrown, salmon, sandybrown, seagreen,
  16187. seashell, sienna, silver, skyblue,
  16188. slateblue, slategrey, snow, springgreen,
  16189. steelblue, tan, teal, thistle,
  16190. tomato, turquoise, violet, wheat,
  16191. whitesmoke, yellowgreen;
  16192. /** Attempts to look up a string in the list of known colour names, and return
  16193. the appropriate colour.
  16194. A non-case-sensitive search is made of the list of predefined colours, and
  16195. if a match is found, that colour is returned. If no match is found, the
  16196. colour passed in as the defaultColour parameter is returned.
  16197. */
  16198. static JUCE_API const Colour findColourForName (const String& colourName,
  16199. const Colour& defaultColour);
  16200. private:
  16201. // this isn't a class you should ever instantiate - it's just here for the
  16202. // static values in it.
  16203. Colours();
  16204. };
  16205. #endif // __JUCE_COLOURS_JUCEHEADER__
  16206. /********* End of inlined file: juce_Colours.h *********/
  16207. /********* Start of inlined file: juce_FillType.h *********/
  16208. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  16209. #define __JUCE_FILLTYPE_JUCEHEADER__
  16210. /********* Start of inlined file: juce_ColourGradient.h *********/
  16211. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  16212. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  16213. /**
  16214. Describes the layout and colours that should be used to paint a colour gradient.
  16215. @see Graphics::setGradientFill
  16216. */
  16217. class JUCE_API ColourGradient
  16218. {
  16219. public:
  16220. /** Creates a gradient object.
  16221. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  16222. colour2 should be. In between them there's a gradient.
  16223. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  16224. its centre.
  16225. The alpha transparencies of the colours are used, so note that
  16226. if you blend from transparent to a solid colour, the RGB of the transparent
  16227. colour will become visible in parts of the gradient. e.g. blending
  16228. from Colour::transparentBlack to Colours::white will produce a
  16229. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  16230. will be white all the way across.
  16231. @see ColourGradient
  16232. */
  16233. ColourGradient (const Colour& colour1,
  16234. const float x1,
  16235. const float y1,
  16236. const Colour& colour2,
  16237. const float x2,
  16238. const float y2,
  16239. const bool isRadial) throw();
  16240. /** Creates an uninitialised gradient.
  16241. If you use this constructor instead of the other one, be sure to set all the
  16242. object's public member variables before using it!
  16243. */
  16244. ColourGradient() throw();
  16245. /** Destructor */
  16246. ~ColourGradient() throw();
  16247. /** Removes any colours that have been added.
  16248. This will also remove any start and end colours, so the gradient won't work. You'll
  16249. need to add more colours with addColour().
  16250. */
  16251. void clearColours() throw();
  16252. /** Adds a colour at a point along the length of the gradient.
  16253. This allows the gradient to go through a spectrum of colours, instead of just a
  16254. start and end colour.
  16255. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  16256. of the distance along the line between the two points
  16257. at which the colour should occur.
  16258. @param colour the colour that should be used at this point
  16259. */
  16260. void addColour (const double proportionAlongGradient,
  16261. const Colour& colour) throw();
  16262. /** Multiplies the alpha value of all the colours by the given scale factor */
  16263. void multiplyOpacity (const float multiplier) throw();
  16264. /** Returns the number of colour-stops that have been added. */
  16265. int getNumColours() const throw();
  16266. /** Returns the position along the length of the gradient of the colour with this index.
  16267. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  16268. */
  16269. double getColourPosition (const int index) const throw();
  16270. /** Returns the colour that was added with a given index.
  16271. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  16272. */
  16273. const Colour getColour (const int index) const throw();
  16274. /** Returns the an interpolated colour at any position along the gradient.
  16275. @param position the position along the gradient, between 0 and 1
  16276. */
  16277. const Colour getColourAtPosition (const float position) const throw();
  16278. /** Creates a set of interpolated premultiplied ARGB values.
  16279. This will resize the HeapBlock, fill it with the colours, and will return the number of
  16280. colours that it added.
  16281. */
  16282. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const throw();
  16283. /** Returns true if all colours are opaque. */
  16284. bool isOpaque() const throw();
  16285. /** Returns true if all colours are completely transparent. */
  16286. bool isInvisible() const throw();
  16287. float x1;
  16288. float y1;
  16289. float x2;
  16290. float y2;
  16291. /** If true, the gradient should be filled circularly, centred around
  16292. (x1, y1), with (x2, y2) defining a point on the circumference.
  16293. If false, the gradient is linear between the two points.
  16294. */
  16295. bool isRadial;
  16296. juce_UseDebuggingNewOperator
  16297. private:
  16298. Array <uint32> colours;
  16299. };
  16300. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  16301. /********* End of inlined file: juce_ColourGradient.h *********/
  16302. class Image;
  16303. /**
  16304. Represents a colour or fill pattern to use for rendering paths.
  16305. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  16306. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  16307. @see Graphics::setFillType, DrawablePath::setFill
  16308. */
  16309. class JUCE_API FillType
  16310. {
  16311. public:
  16312. /** Creates a default fill type, of solid black. */
  16313. FillType() throw();
  16314. /** Creates a fill type of a solid colour.
  16315. @see setColour
  16316. */
  16317. FillType (const Colour& colour) throw();
  16318. /** Creates a gradient fill type.
  16319. @see setGradient
  16320. */
  16321. FillType (const ColourGradient& gradient) throw();
  16322. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  16323. and rotation of the pattern.
  16324. @see setTiledImage
  16325. */
  16326. FillType (const Image& image, const AffineTransform& transform) throw();
  16327. /** Creates a copy of another FillType. */
  16328. FillType (const FillType& other) throw();
  16329. /** Makes a copy of another FillType. */
  16330. const FillType& operator= (const FillType& other) throw();
  16331. /** Destructor. */
  16332. ~FillType() throw();
  16333. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  16334. bool isColour() const throw() { return gradient == 0 && image == 0; }
  16335. /** Returns true if this is a gradient fill. */
  16336. bool isGradient() const throw() { return gradient != 0; }
  16337. /** Returns true if this is a tiled image pattern fill. */
  16338. bool isTiledImage() const throw() { return image != 0; }
  16339. /** Turns this object into a solid colour fill.
  16340. If the object was an image or gradient, those fields will no longer be valid. */
  16341. void setColour (const Colour& newColour) throw();
  16342. /** Turns this object into a gradient fill. */
  16343. void setGradient (const ColourGradient& newGradient) throw();
  16344. /** Turns this object into a tiled image fill type. The transform allows you to set
  16345. the scaling, offset and rotation of the pattern.
  16346. */
  16347. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  16348. /** Changes the opacity that should be used.
  16349. If the fill is a solid colour, this just changes the opacity of that colour. For
  16350. gradients and image tiles, it changes the opacity that will be used for them.
  16351. */
  16352. void setOpacity (const float newOpacity) throw();
  16353. /** Returns the current opacity to be applied to the colour, gradient, or image.
  16354. @see setOpacity
  16355. */
  16356. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  16357. /** The solid colour being used.
  16358. If the fill type is not a solid colour, the alpha channel of this colour indicates
  16359. the opacity that should be used for the fill, and the RGB channels are ignored.
  16360. */
  16361. Colour colour;
  16362. /** Returns the gradient that should be used for filling.
  16363. This will be zero if the object is some other type of fill.
  16364. If a gradient is active, the overall opacity with which it should be applied
  16365. is indicated by the alpha channel of the colour variable.
  16366. */
  16367. ScopedPointer <ColourGradient> gradient;
  16368. /** Returns the image that should be used for tiling.
  16369. The FillType object just keeps a pointer to this image, it doesn't own it, so you have to
  16370. be careful to make sure the image doesn't get deleted while it's being used.
  16371. If an image fill is active, the overall opacity with which it should be applied
  16372. is indicated by the alpha channel of the colour variable.
  16373. */
  16374. const Image* image;
  16375. /** The transform that should be applied to the image or gradient that's being drawn.
  16376. */
  16377. AffineTransform transform;
  16378. juce_UseDebuggingNewOperator
  16379. };
  16380. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  16381. /********* End of inlined file: juce_FillType.h *********/
  16382. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  16383. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  16384. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  16385. /**
  16386. Defines the method used to postion some kind of rectangular object within
  16387. a rectangular viewport.
  16388. Although similar to Justification, this is more specific, and has some extra
  16389. options.
  16390. */
  16391. class JUCE_API RectanglePlacement
  16392. {
  16393. public:
  16394. /** Creates a RectanglePlacement object using a combination of flags. */
  16395. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  16396. /** Creates a copy of another Justification object. */
  16397. RectanglePlacement (const RectanglePlacement& other) throw();
  16398. /** Copies another Justification object. */
  16399. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  16400. /** Flag values that can be combined and used in the constructor. */
  16401. enum
  16402. {
  16403. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  16404. xLeft = 1,
  16405. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  16406. xRight = 2,
  16407. /** Indicates that the source should be placed in the centre between the left and right
  16408. sides of the available space. */
  16409. xMid = 4,
  16410. /** Indicates that the source's top edge should be aligned with the top edge of the
  16411. destination rectangle. */
  16412. yTop = 8,
  16413. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  16414. destination rectangle. */
  16415. yBottom = 16,
  16416. /** Indicates that the source should be placed in the centre between the top and bottom
  16417. sides of the available space. */
  16418. yMid = 32,
  16419. /** If this flag is set, then the source rectangle will be resized to completely fill
  16420. the destination rectangle, and all other flags are ignored.
  16421. */
  16422. stretchToFit = 64,
  16423. /** If this flag is set, then the source rectangle will be resized so that it is the
  16424. minimum size to completely fill the destination rectangle, without changing its
  16425. aspect ratio. This means that some of the source rectangle may fall outside
  16426. the destination.
  16427. If this flag is not set, the source will be given the maximum size at which none
  16428. of it falls outside the destination rectangle.
  16429. */
  16430. fillDestination = 128,
  16431. /** Indicates that the source rectangle can be reduced in size if required, but should
  16432. never be made larger than its original size.
  16433. */
  16434. onlyReduceInSize = 256,
  16435. /** Indicates that the source rectangle can be enlarged if required, but should
  16436. never be made smaller than its original size.
  16437. */
  16438. onlyIncreaseInSize = 512,
  16439. /** Indicates that the source rectangle's size should be left unchanged.
  16440. */
  16441. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  16442. /** A shorthand value that is equivalent to (xMid | yMid). */
  16443. centred = 4 + 32
  16444. };
  16445. /** Returns the raw flags that are set for this object. */
  16446. inline int getFlags() const throw() { return flags; }
  16447. /** Tests a set of flags for this object.
  16448. @returns true if any of the flags passed in are set on this object.
  16449. */
  16450. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  16451. /** Adjusts the position and size of a rectangle to fit it into a space.
  16452. The source rectangle co-ordinates will be adjusted so that they fit into
  16453. the destination rectangle based on this object's flags.
  16454. */
  16455. void applyTo (double& sourceX,
  16456. double& sourceY,
  16457. double& sourceW,
  16458. double& sourceH,
  16459. const double destinationX,
  16460. const double destinationY,
  16461. const double destinationW,
  16462. const double destinationH) const throw();
  16463. /** Returns the transform that should be applied to these source co-ordinates to fit them
  16464. into the destination rectangle using the current flags.
  16465. */
  16466. const AffineTransform getTransformToFit (float sourceX,
  16467. float sourceY,
  16468. float sourceW,
  16469. float sourceH,
  16470. const float destinationX,
  16471. const float destinationY,
  16472. const float destinationW,
  16473. const float destinationH) const throw();
  16474. private:
  16475. int flags;
  16476. };
  16477. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  16478. /********* End of inlined file: juce_RectanglePlacement.h *********/
  16479. class LowLevelGraphicsContext;
  16480. class Image;
  16481. class RectangleList;
  16482. /**
  16483. A graphics context, used for drawing a component or image.
  16484. When a Component needs painting, a Graphics context is passed to its
  16485. Component::paint() method, and this you then call methods within this
  16486. object to actually draw the component's content.
  16487. A Graphics can also be created from an image, to allow drawing directly onto
  16488. that image.
  16489. @see Component::paint
  16490. */
  16491. class JUCE_API Graphics
  16492. {
  16493. public:
  16494. /** Creates a Graphics object to draw directly onto the given image.
  16495. The graphics object that is created will be set up to draw onto the image,
  16496. with the context's clipping area being the entire size of the image, and its
  16497. origin being the image's origin. To draw into a subsection of an image, use the
  16498. reduceClipRegion() and setOrigin() methods.
  16499. Obviously you shouldn't delete the image before this context is deleted.
  16500. */
  16501. Graphics (Image& imageToDrawOnto) throw();
  16502. /** Destructor. */
  16503. ~Graphics() throw();
  16504. /** Changes the current drawing colour.
  16505. This sets the colour that will now be used for drawing operations - it also
  16506. sets the opacity to that of the colour passed-in.
  16507. If a brush is being used when this method is called, the brush will be deselected,
  16508. and any subsequent drawing will be done with a solid colour brush instead.
  16509. @see setOpacity
  16510. */
  16511. void setColour (const Colour& newColour) throw();
  16512. /** Changes the opacity to use with the current colour.
  16513. If a solid colour is being used for drawing, this changes its opacity
  16514. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  16515. If a gradient is being used, this will have no effect on it.
  16516. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  16517. */
  16518. void setOpacity (const float newOpacity) throw();
  16519. /** Sets the context to use a gradient for its fill pattern.
  16520. */
  16521. void setGradientFill (const ColourGradient& gradient) throw();
  16522. /** Sets the context to use a tiled image pattern for filling.
  16523. Make sure that you don't delete this image while it's still being used by
  16524. this context!
  16525. */
  16526. void setTiledImageFill (const Image& imageToUse,
  16527. const int anchorX,
  16528. const int anchorY,
  16529. const float opacity) throw();
  16530. /** Changes the current fill settings.
  16531. @see setColour, setGradientFill, setTiledImageFill
  16532. */
  16533. void setFillType (const FillType& newFill) throw();
  16534. /** Changes the font to use for subsequent text-drawing functions.
  16535. Note there's also a setFont (float, int) method to quickly change the size and
  16536. style of the current font.
  16537. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  16538. */
  16539. void setFont (const Font& newFont) throw();
  16540. /** Changes the size and style of the currently-selected font.
  16541. This is a convenient shortcut that changes the context's current font to a
  16542. different size or style. The typeface won't be changed.
  16543. @see Font
  16544. */
  16545. void setFont (const float newFontHeight,
  16546. const int fontStyleFlags = Font::plain) throw();
  16547. /** Draws a one-line text string.
  16548. This will use the current colour (or brush) to fill the text. The font is the last
  16549. one specified by setFont().
  16550. @param text the string to draw
  16551. @param startX the position to draw the left-hand edge of the text
  16552. @param baselineY the position of the text's baseline
  16553. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  16554. */
  16555. void drawSingleLineText (const String& text,
  16556. const int startX,
  16557. const int baselineY) const throw();
  16558. /** Draws text across multiple lines.
  16559. This will break the text onto a new line where there's a new-line or
  16560. carriage-return character, or at a word-boundary when the text becomes wider
  16561. than the size specified by the maximumLineWidth parameter.
  16562. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  16563. */
  16564. void drawMultiLineText (const String& text,
  16565. const int startX,
  16566. const int baselineY,
  16567. const int maximumLineWidth) const throw();
  16568. /** Renders a string of text as a vector path.
  16569. This allows a string to be transformed with an arbitrary AffineTransform and
  16570. rendered using the current colour/brush. It's much slower than the normal text methods
  16571. but more accurate.
  16572. @see setFont
  16573. */
  16574. void drawTextAsPath (const String& text,
  16575. const AffineTransform& transform) const throw();
  16576. /** Draws a line of text within a specified rectangle.
  16577. The text will be positioned within the rectangle based on the justification
  16578. flags passed-in. If the string is too long to fit inside the rectangle, it will
  16579. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  16580. flag is true).
  16581. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  16582. */
  16583. void drawText (const String& text,
  16584. const int x,
  16585. const int y,
  16586. const int width,
  16587. const int height,
  16588. const Justification& justificationType,
  16589. const bool useEllipsesIfTooBig) const throw();
  16590. /** Tries to draw a text string inside a given space.
  16591. This does its best to make the given text readable within the specified rectangle,
  16592. so it useful for labelling things.
  16593. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  16594. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  16595. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  16596. it's been truncated.
  16597. A Justification parameter lets you specify how the text is laid out within the rectangle,
  16598. both horizontally and vertically.
  16599. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  16600. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  16601. can set this value to 1.0f.
  16602. @see GlyphArrangement::addFittedText
  16603. */
  16604. void drawFittedText (const String& text,
  16605. const int x,
  16606. const int y,
  16607. const int width,
  16608. const int height,
  16609. const Justification& justificationFlags,
  16610. const int maximumNumberOfLines,
  16611. const float minimumHorizontalScale = 0.7f) const throw();
  16612. /** Fills the context's entire clip region with the current colour or brush.
  16613. (See also the fillAll (const Colour&) method which is a quick way of filling
  16614. it with a given colour).
  16615. */
  16616. void fillAll() const throw();
  16617. /** Fills the context's entire clip region with a given colour.
  16618. This leaves the context's current colour and brush unchanged, it just
  16619. uses the specified colour temporarily.
  16620. */
  16621. void fillAll (const Colour& colourToUse) const throw();
  16622. /** Fills a rectangle with the current colour or brush.
  16623. @see drawRect, fillRoundedRectangle
  16624. */
  16625. void fillRect (int x,
  16626. int y,
  16627. int width,
  16628. int height) const throw();
  16629. /** Fills a rectangle with the current colour or brush. */
  16630. void fillRect (const Rectangle& rectangle) const throw();
  16631. /** Fills a rectangle with the current colour or brush.
  16632. This uses sub-pixel positioning so is slower than the fillRect method which
  16633. takes integer co-ordinates.
  16634. */
  16635. void fillRect (const float x,
  16636. const float y,
  16637. const float width,
  16638. const float height) const throw();
  16639. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  16640. @see drawRoundedRectangle, Path::addRoundedRectangle
  16641. */
  16642. void fillRoundedRectangle (const float x,
  16643. const float y,
  16644. const float width,
  16645. const float height,
  16646. const float cornerSize) const throw();
  16647. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  16648. @see drawRoundedRectangle, Path::addRoundedRectangle
  16649. */
  16650. void fillRoundedRectangle (const Rectangle& rectangle,
  16651. const float cornerSize) const throw();
  16652. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  16653. */
  16654. void fillCheckerBoard (int x, int y,
  16655. int width, int height,
  16656. const int checkWidth,
  16657. const int checkHeight,
  16658. const Colour& colour1,
  16659. const Colour& colour2) const throw();
  16660. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16661. The lines are drawn inside the given rectangle, and greater line thicknesses
  16662. extend inwards.
  16663. @see fillRect
  16664. */
  16665. void drawRect (const int x,
  16666. const int y,
  16667. const int width,
  16668. const int height,
  16669. const int lineThickness = 1) const throw();
  16670. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16671. The lines are drawn inside the given rectangle, and greater line thicknesses
  16672. extend inwards.
  16673. @see fillRect
  16674. */
  16675. void drawRect (const float x,
  16676. const float y,
  16677. const float width,
  16678. const float height,
  16679. const float lineThickness = 1.0f) const throw();
  16680. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16681. The lines are drawn inside the given rectangle, and greater line thicknesses
  16682. extend inwards.
  16683. @see fillRect
  16684. */
  16685. void drawRect (const Rectangle& rectangle,
  16686. const int lineThickness = 1) const throw();
  16687. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  16688. @see fillRoundedRectangle, Path::addRoundedRectangle
  16689. */
  16690. void drawRoundedRectangle (const float x,
  16691. const float y,
  16692. const float width,
  16693. const float height,
  16694. const float cornerSize,
  16695. const float lineThickness) const throw();
  16696. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  16697. @see fillRoundedRectangle, Path::addRoundedRectangle
  16698. */
  16699. void drawRoundedRectangle (const Rectangle& rectangle,
  16700. const float cornerSize,
  16701. const float lineThickness) const throw();
  16702. /** Draws a 3D raised (or indented) bevel using two colours.
  16703. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  16704. extend inwards.
  16705. The top-left colour is used for the top- and left-hand edges of the
  16706. bevel; the bottom-right colour is used for the bottom- and right-hand
  16707. edges.
  16708. If useGradient is true, then the bevel fades out to make it look more curved
  16709. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  16710. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  16711. the centre edges are sharp and it fades towards the outside.
  16712. */
  16713. void drawBevel (const int x,
  16714. const int y,
  16715. const int width,
  16716. const int height,
  16717. const int bevelThickness,
  16718. const Colour& topLeftColour = Colours::white,
  16719. const Colour& bottomRightColour = Colours::black,
  16720. const bool useGradient = true,
  16721. const bool sharpEdgeOnOutside = true) const throw();
  16722. /** Draws a pixel using the current colour or brush.
  16723. */
  16724. void setPixel (int x, int y) const throw();
  16725. /** Fills an ellipse with the current colour or brush.
  16726. The ellipse is drawn to fit inside the given rectangle.
  16727. @see drawEllipse, Path::addEllipse
  16728. */
  16729. void fillEllipse (const float x,
  16730. const float y,
  16731. const float width,
  16732. const float height) const throw();
  16733. /** Draws an elliptical stroke using the current colour or brush.
  16734. @see fillEllipse, Path::addEllipse
  16735. */
  16736. void drawEllipse (const float x,
  16737. const float y,
  16738. const float width,
  16739. const float height,
  16740. const float lineThickness) const throw();
  16741. /** Draws a line between two points.
  16742. The line is 1 pixel wide and drawn with the current colour or brush.
  16743. */
  16744. void drawLine (float startX,
  16745. float startY,
  16746. float endX,
  16747. float endY) const throw();
  16748. /** Draws a line between two points with a given thickness.
  16749. @see Path::addLineSegment
  16750. */
  16751. void drawLine (const float startX,
  16752. const float startY,
  16753. const float endX,
  16754. const float endY,
  16755. const float lineThickness) const throw();
  16756. /** Draws a line between two points.
  16757. The line is 1 pixel wide and drawn with the current colour or brush.
  16758. */
  16759. void drawLine (const Line& line) const throw();
  16760. /** Draws a line between two points with a given thickness.
  16761. @see Path::addLineSegment
  16762. */
  16763. void drawLine (const Line& line,
  16764. const float lineThickness) const throw();
  16765. /** Draws a dashed line using a custom set of dash-lengths.
  16766. @param startX the line's start x co-ordinate
  16767. @param startY the line's start y co-ordinate
  16768. @param endX the line's end x co-ordinate
  16769. @param endY the line's end y co-ordinate
  16770. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  16771. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  16772. draw 6 pixels, skip 7 pixels, and then repeat.
  16773. @param numDashLengths the number of elements in the array (this must be an even number).
  16774. @param lineThickness the thickness of the line to draw
  16775. @see PathStrokeType::createDashedStroke
  16776. */
  16777. void drawDashedLine (const float startX,
  16778. const float startY,
  16779. const float endX,
  16780. const float endY,
  16781. const float* const dashLengths,
  16782. const int numDashLengths,
  16783. const float lineThickness = 1.0f) const throw();
  16784. /** Draws a vertical line of pixels at a given x position.
  16785. The x position is an integer, but the top and bottom of the line can be sub-pixel
  16786. positions, and these will be anti-aliased if necessary.
  16787. */
  16788. void drawVerticalLine (const int x, float top, float bottom) const throw();
  16789. /** Draws a horizontal line of pixels at a given y position.
  16790. The y position is an integer, but the left and right ends of the line can be sub-pixel
  16791. positions, and these will be anti-aliased if necessary.
  16792. */
  16793. void drawHorizontalLine (const int y, float left, float right) const throw();
  16794. /** Fills a path using the currently selected colour or brush.
  16795. */
  16796. void fillPath (const Path& path,
  16797. const AffineTransform& transform = AffineTransform::identity) const throw();
  16798. /** Draws a path's outline using the currently selected colour or brush.
  16799. */
  16800. void strokePath (const Path& path,
  16801. const PathStrokeType& strokeType,
  16802. const AffineTransform& transform = AffineTransform::identity) const throw();
  16803. /** Draws a line with an arrowhead.
  16804. @param startX the line's start x co-ordinate
  16805. @param startY the line's start y co-ordinate
  16806. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  16807. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  16808. @param lineThickness the thickness of the line
  16809. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  16810. @param arrowheadLength the length of the arrow head (along the length of the line)
  16811. */
  16812. void drawArrow (const float startX,
  16813. const float startY,
  16814. const float endX,
  16815. const float endY,
  16816. const float lineThickness,
  16817. const float arrowheadWidth,
  16818. const float arrowheadLength) const throw();
  16819. /** Types of rendering quality that can be specified when drawing images.
  16820. @see blendImage, Graphics::setImageResamplingQuality
  16821. */
  16822. enum ResamplingQuality
  16823. {
  16824. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  16825. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  16826. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  16827. };
  16828. /** Changes the quality that will be used when resampling images.
  16829. By default a Graphics object will be set to mediumRenderingQuality.
  16830. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  16831. */
  16832. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  16833. /** Draws an image.
  16834. This will draw the whole of an image, positioning its top-left corner at the
  16835. given co-ordinates, and keeping its size the same. This is the simplest image
  16836. drawing method - the others give more control over the scaling and clipping
  16837. of the images.
  16838. Images are composited using the context's current opacity, so if you
  16839. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16840. (or setColour() with an opaque colour) before drawing images.
  16841. */
  16842. void drawImageAt (const Image* const imageToDraw,
  16843. const int topLeftX,
  16844. const int topLeftY,
  16845. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16846. /** Draws part of an image, rescaling it to fit in a given target region.
  16847. The specified area of the source image is rescaled and drawn to fill the
  16848. specifed destination rectangle.
  16849. Images are composited using the context's current opacity, so if you
  16850. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16851. (or setColour() with an opaque colour) before drawing images.
  16852. @param imageToDraw the image to overlay
  16853. @param destX the left of the destination rectangle
  16854. @param destY the top of the destination rectangle
  16855. @param destWidth the width of the destination rectangle
  16856. @param destHeight the height of the destination rectangle
  16857. @param sourceX the left of the rectangle to copy from the source image
  16858. @param sourceY the top of the rectangle to copy from the source image
  16859. @param sourceWidth the width of the rectangle to copy from the source image
  16860. @param sourceHeight the height of the rectangle to copy from the source image
  16861. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  16862. the source image's alpha channel is used as a mask with
  16863. which to fill the destination using the current colour
  16864. or brush. (If the source is has no alpha channel, then
  16865. it will just fill the target with a solid rectangle)
  16866. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  16867. */
  16868. void drawImage (const Image* const imageToDraw,
  16869. int destX,
  16870. int destY,
  16871. int destWidth,
  16872. int destHeight,
  16873. int sourceX,
  16874. int sourceY,
  16875. int sourceWidth,
  16876. int sourceHeight,
  16877. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16878. /** Draws part of an image, having applied an affine transform to it.
  16879. This lets you throw the image around in some wacky ways, rotate it, shear,
  16880. scale it, etc.
  16881. A subregion is specified within the source image, and all transformations
  16882. will be treated as relative to the origin of this sub-region. So, for example if
  16883. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  16884. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  16885. your image. If you want to use the whole image, then Image::getBounds() returns a
  16886. suitable rectangle to use as the imageSubRegion parameter.
  16887. Images are composited using the context's current opacity, so if you
  16888. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16889. (or setColour() with an opaque colour) before drawing images.
  16890. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  16891. are ignored and it is filled with the current brush, masked by its alpha channel.
  16892. @see setImageResamplingQuality, drawImage
  16893. */
  16894. void drawImageTransformed (const Image* const imageToDraw,
  16895. const Rectangle& imageSubRegion,
  16896. const AffineTransform& transform,
  16897. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16898. /** Draws an image to fit within a designated rectangle.
  16899. If the image is too big or too small for the space, it will be rescaled
  16900. to fit as nicely as it can do without affecting its aspect ratio. It will
  16901. then be placed within the target rectangle according to the justification flags
  16902. specified.
  16903. @param imageToDraw the source image to draw
  16904. @param destX top-left of the target rectangle to fit it into
  16905. @param destY top-left of the target rectangle to fit it into
  16906. @param destWidth size of the target rectangle to fit the image into
  16907. @param destHeight size of the target rectangle to fit the image into
  16908. @param placementWithinTarget this specifies how the image should be positioned
  16909. within the target rectangle - see the RectanglePlacement
  16910. class for more details about this.
  16911. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  16912. alpha channel will be used as a mask with which to
  16913. draw with the current brush or colour. This is
  16914. similar to fillAlphaMap(), and see also drawImage()
  16915. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  16916. */
  16917. void drawImageWithin (const Image* const imageToDraw,
  16918. const int destX,
  16919. const int destY,
  16920. const int destWidth,
  16921. const int destHeight,
  16922. const RectanglePlacement& placementWithinTarget,
  16923. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16924. /** Returns the position of the bounding box for the current clipping region.
  16925. @see getClipRegion, clipRegionIntersects
  16926. */
  16927. const Rectangle getClipBounds() const throw();
  16928. /** Checks whether a rectangle overlaps the context's clipping region.
  16929. If this returns false, no part of the given area can be drawn onto, so this
  16930. method can be used to optimise a component's paint() method, by letting it
  16931. avoid drawing complex objects that aren't within the region being repainted.
  16932. */
  16933. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  16934. /** Intersects the current clipping region with another region.
  16935. @returns true if the resulting clipping region is non-zero in size
  16936. @see setOrigin, clipRegionIntersects
  16937. */
  16938. bool reduceClipRegion (const int x, const int y,
  16939. const int width, const int height) throw();
  16940. /** Intersects the current clipping region with a rectangle list region.
  16941. @returns true if the resulting clipping region is non-zero in size
  16942. @see setOrigin, clipRegionIntersects
  16943. */
  16944. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  16945. /** Intersects the current clipping region with a path.
  16946. @returns true if the resulting clipping region is non-zero in size
  16947. @see reduceClipRegion
  16948. */
  16949. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity) throw();
  16950. /** Intersects the current clipping region with an image's alpha-channel.
  16951. The current clipping path is intersected with the area covered by this image's
  16952. alpha-channel, after the image has been transformed by the specified matrix.
  16953. @param image the image whose alpha-channel should be used. If the image doesn't
  16954. have an alpha-channel, it is treated as entirely opaque.
  16955. @param sourceClipRegion a subsection of the image that should be used. To use the
  16956. entire image, just pass a rectangle of bounds
  16957. (0, 0, image.getWidth(), image.getHeight()).
  16958. @param transform a matrix to apply to the image
  16959. @returns true if the resulting clipping region is non-zero in size
  16960. @see reduceClipRegion
  16961. */
  16962. bool reduceClipRegion (const Image& image, const Rectangle& sourceClipRegion,
  16963. const AffineTransform& transform) throw();
  16964. /** Excludes a rectangle to stop it being drawn into. */
  16965. void excludeClipRegion (const int x, const int y,
  16966. const int width, const int height) throw();
  16967. /** Returns true if no drawing can be done because the clip region is zero. */
  16968. bool isClipEmpty() const throw();
  16969. /** Saves the current graphics state on an internal stack.
  16970. To restore the state, use restoreState().
  16971. */
  16972. void saveState() throw();
  16973. /** Restores a graphics state that was previously saved with saveState().
  16974. */
  16975. void restoreState() throw();
  16976. /** Moves the position of the context's origin.
  16977. This changes the position that the context considers to be (0, 0) to
  16978. the specified position.
  16979. So if you call setOrigin (100, 100), then the position that was previously
  16980. referred to as (100, 100) will subsequently be considered to be (0, 0).
  16981. @see reduceClipRegion
  16982. */
  16983. void setOrigin (const int newOriginX,
  16984. const int newOriginY) throw();
  16985. /** Resets the current colour, brush, and font to default settings. */
  16986. void resetToDefaultState() throw();
  16987. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  16988. bool isVectorDevice() const throw();
  16989. juce_UseDebuggingNewOperator
  16990. /** Create a graphics that uses a given low-level renderer.
  16991. For internal use only.
  16992. NB. The context will NOT be deleted by this object when it is deleted.
  16993. */
  16994. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  16995. /** @internal */
  16996. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  16997. private:
  16998. LowLevelGraphicsContext* const context;
  16999. const bool ownsContext;
  17000. bool saveStatePending;
  17001. void saveStateIfPending() throw();
  17002. const Graphics& operator= (const Graphics& other);
  17003. Graphics (const Graphics&);
  17004. };
  17005. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  17006. /********* End of inlined file: juce_Graphics.h *********/
  17007. /**
  17008. A graphical effect filter that can be applied to components.
  17009. An ImageEffectFilter can be applied to the image that a component
  17010. paints before it hits the screen.
  17011. This is used for adding effects like shadows, blurs, etc.
  17012. @see Component::setComponentEffect
  17013. */
  17014. class JUCE_API ImageEffectFilter
  17015. {
  17016. public:
  17017. /** Overridden to render the effect.
  17018. The implementation of this method must use the image that is passed in
  17019. as its source, and should render its output to the graphics context passed in.
  17020. @param sourceImage the image that the source component has just rendered with
  17021. its paint() method. The image may or may not have an alpha
  17022. channel, depending on whether the component is opaque.
  17023. @param destContext the graphics context to use to draw the resultant image.
  17024. */
  17025. virtual void applyEffect (Image& sourceImage,
  17026. Graphics& destContext) = 0;
  17027. /** Destructor. */
  17028. virtual ~ImageEffectFilter() {}
  17029. };
  17030. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  17031. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  17032. /********* Start of inlined file: juce_RectangleList.h *********/
  17033. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  17034. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  17035. /**
  17036. Maintains a set of rectangles as a complex region.
  17037. This class allows a set of rectangles to be treated as a solid shape, and can
  17038. add and remove rectangular sections of it, and simplify overlapping or
  17039. adjacent rectangles.
  17040. @see Rectangle
  17041. */
  17042. class JUCE_API RectangleList
  17043. {
  17044. public:
  17045. /** Creates an empty RectangleList */
  17046. RectangleList() throw();
  17047. /** Creates a copy of another list */
  17048. RectangleList (const RectangleList& other) throw();
  17049. /** Creates a list containing just one rectangle. */
  17050. RectangleList (const Rectangle& rect) throw();
  17051. /** Copies this list from another one. */
  17052. const RectangleList& operator= (const RectangleList& other) throw();
  17053. /** Destructor. */
  17054. ~RectangleList() throw();
  17055. /** Returns true if the region is empty. */
  17056. bool isEmpty() const throw();
  17057. /** Returns the number of rectangles in the list. */
  17058. int getNumRectangles() const throw() { return rects.size(); }
  17059. /** Returns one of the rectangles at a particular index.
  17060. @returns the rectangle at the index, or an empty rectangle if the
  17061. index is out-of-range.
  17062. */
  17063. const Rectangle getRectangle (const int index) const throw();
  17064. /** Removes all rectangles to leave an empty region. */
  17065. void clear() throw();
  17066. /** Merges a new rectangle into the list.
  17067. The rectangle being added will first be clipped to remove any parts of it
  17068. that overlap existing rectangles in the list.
  17069. */
  17070. void add (const int x, const int y,
  17071. const int w, const int h) throw();
  17072. /** Merges a new rectangle into the list.
  17073. The rectangle being added will first be clipped to remove any parts of it
  17074. that overlap existing rectangles in the list, and adjacent rectangles will be
  17075. merged into it.
  17076. */
  17077. void add (const Rectangle& rect) throw();
  17078. /** Dumbly adds a rectangle to the list without checking for overlaps.
  17079. This simply adds the rectangle to the end, it doesn't merge it or remove
  17080. any overlapping bits.
  17081. */
  17082. void addWithoutMerging (const Rectangle& rect) throw();
  17083. /** Merges another rectangle list into this one.
  17084. Any overlaps between the two lists will be clipped, so that the result is
  17085. the union of both lists.
  17086. */
  17087. void add (const RectangleList& other) throw();
  17088. /** Removes a rectangular region from the list.
  17089. Any rectangles in the list which overlap this will be clipped and subdivided
  17090. if necessary.
  17091. */
  17092. void subtract (const Rectangle& rect) throw();
  17093. /** Removes all areas in another RectangleList from this one.
  17094. Any rectangles in the list which overlap this will be clipped and subdivided
  17095. if necessary.
  17096. */
  17097. void subtract (const RectangleList& otherList) throw();
  17098. /** Removes any areas of the region that lie outside a given rectangle.
  17099. Any rectangles in the list which overlap this will be clipped and subdivided
  17100. if necessary.
  17101. Returns true if the resulting region is not empty, false if it is empty.
  17102. @see getIntersectionWith
  17103. */
  17104. bool clipTo (const Rectangle& rect) throw();
  17105. /** Removes any areas of the region that lie outside a given rectangle list.
  17106. Any rectangles in this object which overlap the specified list will be clipped
  17107. and subdivided if necessary.
  17108. Returns true if the resulting region is not empty, false if it is empty.
  17109. @see getIntersectionWith
  17110. */
  17111. bool clipTo (const RectangleList& other) throw();
  17112. /** Creates a region which is the result of clipping this one to a given rectangle.
  17113. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  17114. resulting region into the list whose reference is passed-in.
  17115. Returns true if the resulting region is not empty, false if it is empty.
  17116. @see clipTo
  17117. */
  17118. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  17119. /** Swaps the contents of this and another list.
  17120. This swaps their internal pointers, so is hugely faster than using copy-by-value
  17121. to swap them.
  17122. */
  17123. void swapWith (RectangleList& otherList) throw();
  17124. /** Checks whether the region contains a given point.
  17125. @returns true if the point lies within one of the rectangles in the list
  17126. */
  17127. bool containsPoint (const int x, const int y) const throw();
  17128. /** Checks whether the region contains the whole of a given rectangle.
  17129. @returns true all parts of the rectangle passed in lie within the region
  17130. defined by this object
  17131. @see intersectsRectangle, containsPoint
  17132. */
  17133. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  17134. /** Checks whether the region contains any part of a given rectangle.
  17135. @returns true if any part of the rectangle passed in lies within the region
  17136. defined by this object
  17137. @see containsRectangle
  17138. */
  17139. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  17140. /** Checks whether this region intersects any part of another one.
  17141. @see intersectsRectangle
  17142. */
  17143. bool intersects (const RectangleList& other) const throw();
  17144. /** Returns the smallest rectangle that can enclose the whole of this region. */
  17145. const Rectangle getBounds() const throw();
  17146. /** Optimises the list into a minimum number of constituent rectangles.
  17147. This will try to combine any adjacent rectangles into larger ones where
  17148. possible, to simplify lists that might have been fragmented by repeated
  17149. add/subtract calls.
  17150. */
  17151. void consolidate() throw();
  17152. /** Adds an x and y value to all the co-ordinates. */
  17153. void offsetAll (const int dx, const int dy) throw();
  17154. /** Creates a Path object to represent this region. */
  17155. const Path toPath() const throw();
  17156. /** An iterator for accessing all the rectangles in a RectangleList. */
  17157. class Iterator
  17158. {
  17159. public:
  17160. Iterator (const RectangleList& list) throw();
  17161. ~Iterator() throw();
  17162. /** Advances to the next rectangle, and returns true if it's not finished.
  17163. Call this before using getRectangle() to find the rectangle that was returned.
  17164. */
  17165. bool next() throw();
  17166. /** Returns the current rectangle. */
  17167. const Rectangle* getRectangle() const throw() { return current; }
  17168. juce_UseDebuggingNewOperator
  17169. private:
  17170. const Rectangle* current;
  17171. const RectangleList& owner;
  17172. int index;
  17173. Iterator (const Iterator&);
  17174. const Iterator& operator= (const Iterator&);
  17175. };
  17176. juce_UseDebuggingNewOperator
  17177. private:
  17178. friend class Iterator;
  17179. Array <Rectangle> rects;
  17180. };
  17181. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  17182. /********* End of inlined file: juce_RectangleList.h *********/
  17183. /********* Start of inlined file: juce_BorderSize.h *********/
  17184. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  17185. #define __JUCE_BORDERSIZE_JUCEHEADER__
  17186. /**
  17187. Specifies a set of gaps to be left around the sides of a rectangle.
  17188. This is basically the size of the spaces at the top, bottom, left and right of
  17189. a rectangle. It's used by various component classes to specify borders.
  17190. @see Rectangle
  17191. */
  17192. class JUCE_API BorderSize
  17193. {
  17194. public:
  17195. /** Creates a null border.
  17196. All sizes are left as 0.
  17197. */
  17198. BorderSize() throw();
  17199. /** Creates a copy of another border. */
  17200. BorderSize (const BorderSize& other) throw();
  17201. /** Creates a border with the given gaps. */
  17202. BorderSize (const int topGap,
  17203. const int leftGap,
  17204. const int bottomGap,
  17205. const int rightGap) throw();
  17206. /** Creates a border with the given gap on all sides. */
  17207. BorderSize (const int allGaps) throw();
  17208. /** Destructor. */
  17209. ~BorderSize() throw();
  17210. /** Returns the gap that should be left at the top of the region. */
  17211. int getTop() const throw() { return top; }
  17212. /** Returns the gap that should be left at the top of the region. */
  17213. int getLeft() const throw() { return left; }
  17214. /** Returns the gap that should be left at the top of the region. */
  17215. int getBottom() const throw() { return bottom; }
  17216. /** Returns the gap that should be left at the top of the region. */
  17217. int getRight() const throw() { return right; }
  17218. /** Returns the sum of the top and bottom gaps. */
  17219. int getTopAndBottom() const throw() { return top + bottom; }
  17220. /** Returns the sum of the left and right gaps. */
  17221. int getLeftAndRight() const throw() { return left + right; }
  17222. /** Changes the top gap. */
  17223. void setTop (const int newTopGap) throw();
  17224. /** Changes the left gap. */
  17225. void setLeft (const int newLeftGap) throw();
  17226. /** Changes the bottom gap. */
  17227. void setBottom (const int newBottomGap) throw();
  17228. /** Changes the right gap. */
  17229. void setRight (const int newRightGap) throw();
  17230. /** Returns a rectangle with these borders removed from it. */
  17231. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  17232. /** Removes this border from a given rectangle. */
  17233. void subtractFrom (Rectangle& rectangle) const throw();
  17234. /** Returns a rectangle with these borders added around it. */
  17235. const Rectangle addedTo (const Rectangle& original) const throw();
  17236. /** Adds this border around a given rectangle. */
  17237. void addTo (Rectangle& original) const throw();
  17238. bool operator== (const BorderSize& other) const throw();
  17239. bool operator!= (const BorderSize& other) const throw();
  17240. juce_UseDebuggingNewOperator
  17241. private:
  17242. int top, left, bottom, right;
  17243. };
  17244. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  17245. /********* End of inlined file: juce_BorderSize.h *********/
  17246. /********* Start of inlined file: juce_ComponentPeer.h *********/
  17247. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  17248. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  17249. class Component;
  17250. class Graphics;
  17251. class ComponentBoundsConstrainer;
  17252. class ComponentDeletionWatcher;
  17253. /**
  17254. The base class for window objects that wrap a component as a real operating
  17255. system object.
  17256. This is an abstract base class - the platform specific code contains default
  17257. implementations of it that create and manage windows.
  17258. @see Component::createNewPeer
  17259. */
  17260. class JUCE_API ComponentPeer : public MessageListener
  17261. {
  17262. public:
  17263. /** A combination of these flags is passed to the ComponentPeer constructor. */
  17264. enum StyleFlags
  17265. {
  17266. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  17267. entry on the taskbar (ignored on MacOSX) */
  17268. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  17269. tooltip, etc. */
  17270. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  17271. through it (may not be possible on some platforms). */
  17272. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  17273. title bar and frame\. if not specified, the window will be
  17274. borderless. */
  17275. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  17276. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  17277. minimise button on it. */
  17278. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  17279. maximise button on it. */
  17280. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  17281. close button on it. */
  17282. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  17283. not be possible on all platforms). */
  17284. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  17285. do its own repainting, but only to repaint when the
  17286. performAnyPendingRepaintsNow() method is called. */
  17287. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  17288. be used for things like plugin windows, to stop them interfering
  17289. with the host's shortcut keys */
  17290. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  17291. };
  17292. /** Creates a peer.
  17293. The component is the one that we intend to represent, and the style flags are
  17294. a combination of the values in the StyleFlags enum
  17295. */
  17296. ComponentPeer (Component* const component,
  17297. const int styleFlags) throw();
  17298. /** Destructor. */
  17299. virtual ~ComponentPeer();
  17300. /** Returns the component being represented by this peer. */
  17301. Component* getComponent() const throw() { return component; }
  17302. /** Returns the set of style flags that were set when the window was created.
  17303. @see Component::addToDesktop
  17304. */
  17305. int getStyleFlags() const throw() { return styleFlags; }
  17306. /** Returns the raw handle to whatever kind of window is being used.
  17307. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  17308. but rememeber there's no guarantees what you'll get back.
  17309. */
  17310. virtual void* getNativeHandle() const = 0;
  17311. /** Shows or hides the window. */
  17312. virtual void setVisible (bool shouldBeVisible) = 0;
  17313. /** Changes the title of the window. */
  17314. virtual void setTitle (const String& title) = 0;
  17315. /** Moves the window without changing its size.
  17316. If the native window is contained in another window, then the co-ordinates are
  17317. relative to the parent window's origin, not the screen origin.
  17318. This should result in a callback to handleMovedOrResized().
  17319. */
  17320. virtual void setPosition (int x, int y) = 0;
  17321. /** Resizes the window without changing its position.
  17322. This should result in a callback to handleMovedOrResized().
  17323. */
  17324. virtual void setSize (int w, int h) = 0;
  17325. /** Moves and resizes the window.
  17326. If the native window is contained in another window, then the co-ordinates are
  17327. relative to the parent window's origin, not the screen origin.
  17328. This should result in a callback to handleMovedOrResized().
  17329. */
  17330. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  17331. /** Returns the current position and size of the window.
  17332. If the native window is contained in another window, then the co-ordinates are
  17333. relative to the parent window's origin, not the screen origin.
  17334. */
  17335. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  17336. /** Returns the x-position of this window, relative to the screen's origin. */
  17337. virtual int getScreenX() const = 0;
  17338. /** Returns the y-position of this window, relative to the screen's origin. */
  17339. virtual int getScreenY() const = 0;
  17340. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  17341. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  17342. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  17343. virtual void globalPositionToRelative (int& x, int& y) = 0;
  17344. /** Minimises the window. */
  17345. virtual void setMinimised (bool shouldBeMinimised) = 0;
  17346. /** True if the window is currently minimised. */
  17347. virtual bool isMinimised() const = 0;
  17348. /** Enable/disable fullscreen mode for the window. */
  17349. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  17350. /** True if the window is currently full-screen. */
  17351. virtual bool isFullScreen() const = 0;
  17352. /** Sets the size to restore to if fullscreen mode is turned off. */
  17353. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  17354. /** Returns the size to restore to if fullscreen mode is turned off. */
  17355. const Rectangle& getNonFullScreenBounds() const throw();
  17356. /** Attempts to change the icon associated with this window.
  17357. */
  17358. virtual void setIcon (const Image& newIcon) = 0;
  17359. /** Sets a constrainer to use if the peer can resize itself.
  17360. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  17361. */
  17362. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  17363. /** Returns the current constrainer, if one has been set. */
  17364. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  17365. /** Checks if a point is in the window.
  17366. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  17367. is false, then this returns false if the point is actually inside a child of this
  17368. window.
  17369. */
  17370. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  17371. /** Returns the size of the window frame that's around this window.
  17372. Whether or not the window has a normal window frame depends on the flags
  17373. that were set when the window was created by Component::addToDesktop()
  17374. */
  17375. virtual const BorderSize getFrameSize() const = 0;
  17376. /** This is called when the window's bounds change.
  17377. A peer implementation must call this when the window is moved and resized, so that
  17378. this method can pass the message on to the component.
  17379. */
  17380. void handleMovedOrResized();
  17381. /** This is called if the screen resolution changes.
  17382. A peer implementation must call this if the monitor arrangement changes or the available
  17383. screen size changes.
  17384. */
  17385. void handleScreenSizeChange();
  17386. /** This is called to repaint the component into the given context. */
  17387. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  17388. /** Sets this window to either be always-on-top or normal.
  17389. Some kinds of window might not be able to do this, so should return false.
  17390. */
  17391. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  17392. /** Brings the window to the top, optionally also giving it focus. */
  17393. virtual void toFront (bool makeActive) = 0;
  17394. /** Moves the window to be just behind another one. */
  17395. virtual void toBehind (ComponentPeer* other) = 0;
  17396. /** Called when the window is brought to the front, either by the OS or by a call
  17397. to toFront().
  17398. */
  17399. void handleBroughtToFront();
  17400. /** True if the window has the keyboard focus. */
  17401. virtual bool isFocused() const = 0;
  17402. /** Tries to give the window keyboard focus. */
  17403. virtual void grabFocus() = 0;
  17404. /** Tells the window that text input may be required at the given position.
  17405. This may cause things like a virtual on-screen keyboard to appear, depending
  17406. on the OS.
  17407. */
  17408. virtual void textInputRequired (int x, int y) = 0;
  17409. /** Called when the window gains keyboard focus. */
  17410. void handleFocusGain();
  17411. /** Called when the window loses keyboard focus. */
  17412. void handleFocusLoss();
  17413. Component* getLastFocusedSubcomponent() const throw();
  17414. /** Called when a key is pressed.
  17415. For keycode info, see the KeyPress class.
  17416. Returns true if the keystroke was used.
  17417. */
  17418. bool handleKeyPress (const int keyCode,
  17419. const juce_wchar textCharacter);
  17420. /** Called whenever a key is pressed or released.
  17421. Returns true if the keystroke was used.
  17422. */
  17423. bool handleKeyUpOrDown (const bool isKeyDown);
  17424. /** Called whenever a modifier key is pressed or released. */
  17425. void handleModifierKeysChange();
  17426. /** Invalidates a region of the window to be repainted asynchronously. */
  17427. virtual void repaint (int x, int y, int w, int h) = 0;
  17428. /** This can be called (from the message thread) to cause the immediate redrawing
  17429. of any areas of this window that need repainting.
  17430. You shouldn't ever really need to use this, it's mainly for special purposes
  17431. like supporting audio plugins where the host's event loop is out of our control.
  17432. */
  17433. virtual void performAnyPendingRepaintsNow() = 0;
  17434. void handleMouseEnter (int x, int y, const int64 time);
  17435. void handleMouseMove (int x, int y, const int64 time);
  17436. void handleMouseDown (int x, int y, const int64 time);
  17437. void handleMouseDrag (int x, int y, const int64 time);
  17438. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  17439. void handleMouseExit (int x, int y, const int64 time);
  17440. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  17441. /** Causes a mouse-move callback to be made asynchronously. */
  17442. void sendFakeMouseMove() throw();
  17443. void handleUserClosingWindow();
  17444. void handleFileDragMove (const StringArray& files, int x, int y);
  17445. void handleFileDragExit (const StringArray& files);
  17446. void handleFileDragDrop (const StringArray& files, int x, int y);
  17447. /** Resets the masking region.
  17448. The subclass should call this every time it's about to call the handlePaint
  17449. method.
  17450. @see addMaskedRegion
  17451. */
  17452. void clearMaskedRegion() throw();
  17453. /** Adds a rectangle to the set of areas not to paint over.
  17454. A component can call this on its peer during its paint() method, to signal
  17455. that the painting code should ignore a given region. The reason
  17456. for this is to stop embedded windows (such as OpenGL) getting painted over.
  17457. The masked region is cleared each time before a paint happens, so a component
  17458. will have to make sure it calls this every time it's painted.
  17459. */
  17460. void addMaskedRegion (int x, int y, int w, int h) throw();
  17461. /** Returns the number of currently-active peers.
  17462. @see getPeer
  17463. */
  17464. static int getNumPeers() throw();
  17465. /** Returns one of the currently-active peers.
  17466. @see getNumPeers
  17467. */
  17468. static ComponentPeer* getPeer (const int index) throw();
  17469. /** Checks if this peer object is valid.
  17470. @see getNumPeers
  17471. */
  17472. static bool isValidPeer (const ComponentPeer* const peer) throw();
  17473. static void bringModalComponentToFront();
  17474. virtual const StringArray getAvailableRenderingEngines() throw();
  17475. virtual int getCurrentRenderingEngine() throw();
  17476. virtual void setCurrentRenderingEngine (int index) throw();
  17477. juce_UseDebuggingNewOperator
  17478. protected:
  17479. Component* const component;
  17480. const int styleFlags;
  17481. RectangleList maskedRegion;
  17482. Rectangle lastNonFullscreenBounds;
  17483. uint32 lastPaintTime;
  17484. ComponentBoundsConstrainer* constrainer;
  17485. static void updateCurrentModifiers() throw();
  17486. /** @internal */
  17487. void handleMessage (const Message& message);
  17488. private:
  17489. Component* lastFocusedComponent;
  17490. ScopedPointer <ComponentDeletionWatcher> dragAndDropTargetComponent;
  17491. Component* lastDragAndDropCompUnderMouse;
  17492. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  17493. friend class Component;
  17494. static ComponentPeer* getPeerFor (const Component* const component) throw();
  17495. void setLastDragDropTarget (Component* comp);
  17496. ComponentPeer (const ComponentPeer&);
  17497. const ComponentPeer& operator= (const ComponentPeer&);
  17498. };
  17499. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  17500. /********* End of inlined file: juce_ComponentPeer.h *********/
  17501. class LookAndFeel;
  17502. /**
  17503. The base class for all JUCE user-interface objects.
  17504. */
  17505. class JUCE_API Component : public MouseListener,
  17506. protected MessageListener
  17507. {
  17508. public:
  17509. /** Creates a component.
  17510. To get it to actually appear, you'll also need to:
  17511. - Either add it to a parent component or use the addToDesktop() method to
  17512. make it a desktop window
  17513. - Set its size and position to something sensible
  17514. - Use setVisible() to make it visible
  17515. And for it to serve any useful purpose, you'll need to write a
  17516. subclass of Component or use one of the other types of component from
  17517. the library.
  17518. */
  17519. Component() throw();
  17520. /** Destructor.
  17521. Note that when a component is deleted, any child components it might
  17522. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  17523. */
  17524. virtual ~Component();
  17525. /** Creates a component, setting its name at the same time.
  17526. @see getName, setName
  17527. */
  17528. Component (const String& componentName) throw();
  17529. /** Returns the name of this component.
  17530. @see setName
  17531. */
  17532. const String& getName() const throw() { return componentName_; }
  17533. /** Sets the name of this component.
  17534. When the name changes, all registered ComponentListeners will receive a
  17535. ComponentListener::componentNameChanged() callback.
  17536. @see getName
  17537. */
  17538. virtual void setName (const String& newName);
  17539. /** Checks whether this Component object has been deleted.
  17540. This will check whether this object is still a valid component, or whether
  17541. it's been deleted.
  17542. It's safe to call this on null or dangling pointers, but note that there is a
  17543. small risk if another new (but different) component has been created at the
  17544. same memory address which this one occupied, this methods can return a
  17545. false positive.
  17546. */
  17547. bool isValidComponent() const throw();
  17548. /** Makes the component visible or invisible.
  17549. This method will show or hide the component.
  17550. Note that components default to being non-visible when first created.
  17551. Also note that visible components won't be seen unless all their parent components
  17552. are also visible.
  17553. This method will call visibilityChanged() and also componentVisibilityChanged()
  17554. for any component listeners that are interested in this component.
  17555. @param shouldBeVisible whether to show or hide the component
  17556. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  17557. */
  17558. virtual void setVisible (bool shouldBeVisible);
  17559. /** Tests whether the component is visible or not.
  17560. this doesn't necessarily tell you whether this comp is actually on the screen
  17561. because this depends on whether all the parent components are also visible - use
  17562. isShowing() to find this out.
  17563. @see isShowing, setVisible
  17564. */
  17565. bool isVisible() const throw() { return flags.visibleFlag; }
  17566. /** Called when this component's visiblility changes.
  17567. @see setVisible, isVisible
  17568. */
  17569. virtual void visibilityChanged();
  17570. /** Tests whether this component and all its parents are visible.
  17571. @returns true only if this component and all its parents are visible.
  17572. @see isVisible
  17573. */
  17574. bool isShowing() const throw();
  17575. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  17576. To do this, this function will cunningly:
  17577. - take a snapshot of the component as it currently looks
  17578. - call setVisible(false) on the component
  17579. - replace it with a special component that will continue drawing the
  17580. snapshot, animating it and gradually making it more transparent
  17581. - when it's gone, the special component will also be deleted
  17582. As soon as this method returns, the component can be safely removed and deleted
  17583. leaving the proxy to do the fade-out, so it's even ok to call this in a
  17584. component's destructor.
  17585. Passing non-zero x and y values will cause the ghostly component image to
  17586. also whizz off by this distance while fading out. If the scale factor is
  17587. not 1.0, it will also zoom from the component's current size to this new size.
  17588. One thing to be careful about is that the parent component must be able to cope
  17589. with this unknown component type being added to it.
  17590. */
  17591. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  17592. const int deltaXToMove = 0,
  17593. const int deltaYToMove = 0,
  17594. const float scaleFactorAtEnd = 1.0f);
  17595. /** Makes this component appear as a window on the desktop.
  17596. Note that before calling this, you should make sure that the component's opacity is
  17597. set correctly using setOpaque(). If the component is non-opaque, the windowing
  17598. system will try to create a special transparent window for it, which will generally take
  17599. a lot more CPU to operate (and might not even be possible on some platforms).
  17600. If the component is inside a parent component at the time this method is called, it
  17601. will be first be removed from that parent. Likewise if a component on the desktop
  17602. is subsequently added to another component, it'll be removed from the desktop.
  17603. @param windowStyleFlags a combination of the flags specified in the
  17604. ComponentPeer::StyleFlags enum, which define the
  17605. window's characteristics.
  17606. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  17607. in which the juce component should place itself. On Windows,
  17608. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  17609. supported on all platforms, and best left as 0 unless you know
  17610. what you're doing
  17611. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  17612. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  17613. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  17614. */
  17615. virtual void addToDesktop (int windowStyleFlags,
  17616. void* nativeWindowToAttachTo = 0);
  17617. /** If the component is currently showing on the desktop, this will hide it.
  17618. You can also use setVisible() to hide a desktop window temporarily, but
  17619. removeFromDesktop() will free any system resources that are being used up.
  17620. @see addToDesktop, isOnDesktop
  17621. */
  17622. void removeFromDesktop();
  17623. /** Returns true if this component is currently showing on the desktop.
  17624. @see addToDesktop, removeFromDesktop
  17625. */
  17626. bool isOnDesktop() const throw();
  17627. /** Returns the heavyweight window that contains this component.
  17628. If this component is itself on the desktop, this will return the window
  17629. object that it is using. Otherwise, it will return the window of
  17630. its top-level parent component.
  17631. This may return 0 if there isn't a desktop component.
  17632. @see addToDesktop, isOnDesktop
  17633. */
  17634. ComponentPeer* getPeer() const throw();
  17635. /** For components on the desktop, this is called if the system wants to close the window.
  17636. This is a signal that either the user or the system wants the window to close. The
  17637. default implementation of this method will trigger an assertion to warn you that your
  17638. component should do something about it, but you can override this to ignore the event
  17639. if you want.
  17640. */
  17641. virtual void userTriedToCloseWindow();
  17642. /** Called for a desktop component which has just been minimised or un-minimised.
  17643. This will only be called for components on the desktop.
  17644. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  17645. */
  17646. virtual void minimisationStateChanged (bool isNowMinimised);
  17647. /** Brings the component to the front of its siblings.
  17648. If some of the component's siblings have had their 'always-on-top' flag set,
  17649. then they will still be kept in front of this one (unless of course this
  17650. one is also 'always-on-top').
  17651. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  17652. to the component (see grabKeyboardFocus() for more details)
  17653. @see toBack, toBehind, setAlwaysOnTop
  17654. */
  17655. void toFront (const bool shouldAlsoGainFocus);
  17656. /** Changes this component's z-order to be at the back of all its siblings.
  17657. If the component is set to be 'always-on-top', it will only be moved to the
  17658. back of the other other 'always-on-top' components.
  17659. @see toFront, toBehind, setAlwaysOnTop
  17660. */
  17661. void toBack();
  17662. /** Changes this component's z-order so that it's just behind another component.
  17663. @see toFront, toBack
  17664. */
  17665. void toBehind (Component* const other);
  17666. /** Sets whether the component should always be kept at the front of its siblings.
  17667. @see isAlwaysOnTop
  17668. */
  17669. void setAlwaysOnTop (const bool shouldStayOnTop);
  17670. /** Returns true if this component is set to always stay in front of its siblings.
  17671. @see setAlwaysOnTop
  17672. */
  17673. bool isAlwaysOnTop() const throw();
  17674. /** Returns the x co-ordinate of the component's left edge.
  17675. This is a distance in pixels from the left edge of the component's parent.
  17676. @see getScreenX
  17677. */
  17678. inline int getX() const throw() { return bounds_.getX(); }
  17679. /** Returns the y co-ordinate of the top of this component.
  17680. This is a distance in pixels from the top edge of the component's parent.
  17681. @see getScreenY
  17682. */
  17683. inline int getY() const throw() { return bounds_.getY(); }
  17684. /** Returns the component's width in pixels. */
  17685. inline int getWidth() const throw() { return bounds_.getWidth(); }
  17686. /** Returns the component's height in pixels. */
  17687. inline int getHeight() const throw() { return bounds_.getHeight(); }
  17688. /** Returns the x co-ordinate of the component's right-hand edge.
  17689. This is a distance in pixels from the left edge of the component's parent.
  17690. */
  17691. int getRight() const throw() { return bounds_.getRight(); }
  17692. /** Returns the y co-ordinate of the bottom edge of this component.
  17693. This is a distance in pixels from the top edge of the component's parent.
  17694. */
  17695. int getBottom() const throw() { return bounds_.getBottom(); }
  17696. /** Returns this component's bounding box.
  17697. The rectangle returned is relative to the top-left of the component's parent.
  17698. */
  17699. const Rectangle& getBounds() const throw() { return bounds_; }
  17700. /** Returns the region of this component that's not obscured by other, opaque components.
  17701. The RectangleList that is returned represents the area of this component
  17702. which isn't covered by opaque child components.
  17703. If includeSiblings is true, it will also take into account any siblings
  17704. that may be overlapping the component.
  17705. */
  17706. void getVisibleArea (RectangleList& result,
  17707. const bool includeSiblings) const;
  17708. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  17709. @see getX, relativePositionToGlobal
  17710. */
  17711. int getScreenX() const throw();
  17712. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  17713. @see getY, relativePositionToGlobal
  17714. */
  17715. int getScreenY() const throw();
  17716. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  17717. @see globalPositionToRelative, relativePositionToOtherComponent
  17718. */
  17719. void relativePositionToGlobal (int& x, int& y) const throw();
  17720. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  17721. @see relativePositionToGlobal, relativePositionToOtherComponent
  17722. */
  17723. void globalPositionToRelative (int& x, int& y) const throw();
  17724. /** Converts a position relative to this component's top-left into a position
  17725. relative to another component's top-left.
  17726. @see relativePositionToGlobal, globalPositionToRelative
  17727. */
  17728. void relativePositionToOtherComponent (const Component* const targetComponent,
  17729. int& x, int& y) const throw();
  17730. /** Moves the component to a new position.
  17731. Changes the component's top-left position (without changing its size).
  17732. The position is relative to the top-left of the component's parent.
  17733. If the component actually moves, this method will make a synchronous call to moved().
  17734. @see setBounds, ComponentListener::componentMovedOrResized
  17735. */
  17736. void setTopLeftPosition (const int x, const int y);
  17737. /** Moves the component to a new position.
  17738. Changes the position of the component's top-right corner (keeping it the same size).
  17739. The position is relative to the top-left of the component's parent.
  17740. If the component actually moves, this method will make a synchronous call to moved().
  17741. */
  17742. void setTopRightPosition (const int x, const int y);
  17743. /** Changes the size of the component.
  17744. A synchronous call to resized() will be occur if the size actually changes.
  17745. */
  17746. void setSize (const int newWidth, const int newHeight);
  17747. /** Changes the component's position and size.
  17748. The co-ordinates are relative to the top-left of the component's parent, or relative
  17749. to the origin of the screen is the component is on the desktop.
  17750. If this method changes the component's top-left position, it will make a synchronous
  17751. call to moved(). If it changes the size, it will also make a call to resized().
  17752. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  17753. */
  17754. void setBounds (int x, int y, int width, int height);
  17755. /** Changes the component's position and size.
  17756. @see setBounds
  17757. */
  17758. void setBounds (const Rectangle& newBounds);
  17759. /** Changes the component's position and size in terms of fractions of its parent's size.
  17760. The values are factors of the parent's size, so for example
  17761. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  17762. width and height of the parent, with its top-left position 20% of
  17763. the way across and down the parent.
  17764. */
  17765. void setBoundsRelative (const float proportionalX, const float proportionalY,
  17766. const float proportionalWidth, const float proportionalHeight);
  17767. /** Changes the component's position and size based on the amount of space to leave around it.
  17768. This will position the component within its parent, leaving the specified number of
  17769. pixels around each edge.
  17770. */
  17771. void setBoundsInset (const BorderSize& borders);
  17772. /** Positions the component within a given rectangle, keeping its proportions
  17773. unchanged.
  17774. If onlyReduceInSize is false, the component will be resized to fill as much of the
  17775. rectangle as possible without changing its aspect ratio (the component's
  17776. current size is used to determine its aspect ratio, so a zero-size component
  17777. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  17778. too big to fit inside the rectangle.
  17779. It will then be positioned within the rectangle according to the justification flags
  17780. specified.
  17781. */
  17782. void setBoundsToFit (int x, int y, int width, int height,
  17783. const Justification& justification,
  17784. const bool onlyReduceInSize);
  17785. /** Changes the position of the component's centre.
  17786. Leaves the component's size unchanged, but sets the position of its centre
  17787. relative to its parent's top-left.
  17788. */
  17789. void setCentrePosition (const int x, const int y);
  17790. /** Changes the position of the component's centre.
  17791. Leaves the position unchanged, but positions its centre relative to its
  17792. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  17793. its parent.
  17794. */
  17795. void setCentreRelative (const float x, const float y);
  17796. /** Changes the component's size and centres it within its parent.
  17797. After changing the size, the component will be moved so that it's
  17798. centred within its parent.
  17799. */
  17800. void centreWithSize (const int width, const int height);
  17801. /** Returns a proportion of the component's width.
  17802. This is a handy equivalent of (getWidth() * proportion).
  17803. */
  17804. int proportionOfWidth (const float proportion) const throw();
  17805. /** Returns a proportion of the component's height.
  17806. This is a handy equivalent of (getHeight() * proportion).
  17807. */
  17808. int proportionOfHeight (const float proportion) const throw();
  17809. /** Returns the width of the component's parent.
  17810. If the component has no parent (i.e. if it's on the desktop), this will return
  17811. the width of the screen.
  17812. */
  17813. int getParentWidth() const throw();
  17814. /** Returns the height of the component's parent.
  17815. If the component has no parent (i.e. if it's on the desktop), this will return
  17816. the height of the screen.
  17817. */
  17818. int getParentHeight() const throw();
  17819. /** Returns the screen co-ordinates of the monitor that contains this component.
  17820. If there's only one monitor, this will return its size - if there are multiple
  17821. monitors, it will return the area of the monitor that contains the component's
  17822. centre.
  17823. */
  17824. const Rectangle getParentMonitorArea() const throw();
  17825. /** Returns the number of child components that this component contains.
  17826. @see getChildComponent, getIndexOfChildComponent
  17827. */
  17828. int getNumChildComponents() const throw();
  17829. /** Returns one of this component's child components, by it index.
  17830. The component with index 0 is at the back of the z-order, the one at the
  17831. front will have index (getNumChildComponents() - 1).
  17832. If the index is out-of-range, this will return a null pointer.
  17833. @see getNumChildComponents, getIndexOfChildComponent
  17834. */
  17835. Component* getChildComponent (const int index) const throw();
  17836. /** Returns the index of this component in the list of child components.
  17837. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  17838. values are further towards the front.
  17839. Returns -1 if the component passed-in is not a child of this component.
  17840. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  17841. */
  17842. int getIndexOfChildComponent (const Component* const child) const throw();
  17843. /** Adds a child component to this one.
  17844. @param child the new component to add. If the component passed-in is already
  17845. the child of another component, it'll first be removed from that.
  17846. @param zOrder The index in the child-list at which this component should be inserted.
  17847. A value of -1 will insert it in front of the others, 0 is the back.
  17848. @see removeChildComponent, addAndMakeVisible, getChild,
  17849. ComponentListener::componentChildrenChanged
  17850. */
  17851. void addChildComponent (Component* const child,
  17852. int zOrder = -1);
  17853. /** Adds a child component to this one, and also makes the child visible if it isn't.
  17854. Quite a useful function, this is just the same as calling addChildComponent()
  17855. followed by setVisible (true) on the child.
  17856. */
  17857. void addAndMakeVisible (Component* const child,
  17858. int zOrder = -1);
  17859. /** Removes one of this component's child-components.
  17860. If the child passed-in isn't actually a child of this component (either because
  17861. it's invalid or is the child of a different parent), then nothing is done.
  17862. Note that removing a child will not delete it!
  17863. @see addChildComponent, ComponentListener::componentChildrenChanged
  17864. */
  17865. void removeChildComponent (Component* const childToRemove);
  17866. /** Removes one of this component's child-components by index.
  17867. This will return a pointer to the component that was removed, or null if
  17868. the index was out-of-range.
  17869. Note that removing a child will not delete it!
  17870. @see addChildComponent, ComponentListener::componentChildrenChanged
  17871. */
  17872. Component* removeChildComponent (const int childIndexToRemove);
  17873. /** Removes all this component's children.
  17874. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  17875. */
  17876. void removeAllChildren();
  17877. /** Removes all this component's children, and deletes them.
  17878. @see removeAllChildren
  17879. */
  17880. void deleteAllChildren();
  17881. /** Returns the component which this component is inside.
  17882. If this is the highest-level component or hasn't yet been added to
  17883. a parent, this will return null.
  17884. */
  17885. Component* getParentComponent() const throw() { return parentComponent_; }
  17886. /** Searches the parent components for a component of a specified class.
  17887. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  17888. component that can be dynamically cast to a MyComp, or will return 0 if none
  17889. of the parents are suitable.
  17890. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  17891. */
  17892. template <class TargetClass>
  17893. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  17894. {
  17895. (void) dummyParameter;
  17896. Component* p = parentComponent_;
  17897. while (p != 0)
  17898. {
  17899. TargetClass* target = dynamic_cast <TargetClass*> (p);
  17900. if (target != 0)
  17901. return target;
  17902. p = p->parentComponent_;
  17903. }
  17904. return 0;
  17905. }
  17906. /** Returns the highest-level component which contains this one or its parents.
  17907. This will search upwards in the parent-hierarchy from this component, until it
  17908. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  17909. not yet added to a parent), and will return that.
  17910. */
  17911. Component* getTopLevelComponent() const throw();
  17912. /** Checks whether a component is anywhere inside this component or its children.
  17913. This will recursively check through this components children to see if the
  17914. given component is anywhere inside.
  17915. */
  17916. bool isParentOf (const Component* possibleChild) const throw();
  17917. /** Called to indicate that the component's parents have changed.
  17918. When a component is added or removed from its parent, this method will
  17919. be called on all of its children (recursively - so all children of its
  17920. children will also be called as well).
  17921. Subclasses can override this if they need to react to this in some way.
  17922. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  17923. */
  17924. virtual void parentHierarchyChanged();
  17925. /** Subclasses can use this callback to be told when children are added or removed.
  17926. @see parentHierarchyChanged
  17927. */
  17928. virtual void childrenChanged();
  17929. /** Tests whether a given point inside the component.
  17930. Overriding this method allows you to create components which only intercept
  17931. mouse-clicks within a user-defined area.
  17932. This is called to find out whether a particular x, y co-ordinate is
  17933. considered to be inside the component or not, and is used by methods such
  17934. as contains() and getComponentAt() to work out which component
  17935. the mouse is clicked on.
  17936. Components with custom shapes will probably want to override it to perform
  17937. some more complex hit-testing.
  17938. The default implementation of this method returns either true or false,
  17939. depending on the value that was set by calling setInterceptsMouseClicks() (true
  17940. is the default return value).
  17941. Note that the hit-test region is not related to the opacity with which
  17942. areas of a component are painted.
  17943. Applications should never call hitTest() directly - instead use the
  17944. contains() method, because this will also test for occlusion by the
  17945. component's parent.
  17946. Note that for components on the desktop, this method will be ignored, because it's
  17947. not always possible to implement this behaviour on all platforms.
  17948. @param x the x co-ordinate to test, relative to the left hand edge of this
  17949. component. This value is guaranteed to be greater than or equal to
  17950. zero, and less than the component's width
  17951. @param y the y co-ordinate to test, relative to the top edge of this
  17952. component. This value is guaranteed to be greater than or equal to
  17953. zero, and less than the component's height
  17954. @returns true if the click is considered to be inside the component
  17955. @see setInterceptsMouseClicks, contains
  17956. */
  17957. virtual bool hitTest (int x, int y);
  17958. /** Changes the default return value for the hitTest() method.
  17959. Setting this to false is an easy way to make a component pass its mouse-clicks
  17960. through to the components behind it.
  17961. When a component is created, the default setting for this is true.
  17962. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  17963. return false (or true for child components if allowClicksOnChildComponents
  17964. is true)
  17965. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  17966. components can be clicked on as normal but clicks on this component pass
  17967. straight through; if this is false and allowClicksOnThisComponent
  17968. is false, then neither this component nor any child components can
  17969. be clicked on
  17970. @see hitTest, getInterceptsMouseClicks
  17971. */
  17972. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  17973. const bool allowClicksOnChildComponents) throw();
  17974. /** Retrieves the current state of the mouse-click interception flags.
  17975. On return, the two parameters are set to the state used in the last call to
  17976. setInterceptsMouseClicks().
  17977. @see setInterceptsMouseClicks
  17978. */
  17979. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  17980. bool& allowsClicksOnChildComponents) const throw();
  17981. /** Returns true if a given point lies within this component or one of its children.
  17982. Never override this method! Use hitTest to create custom hit regions.
  17983. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17984. @param y the y co-ordinate to test, relative to this component's top edge.
  17985. @returns true if the point is within the component's hit-test area, but only if
  17986. that part of the component isn't clipped by its parent component. Note
  17987. that this won't take into account any overlapping sibling components
  17988. which might be in the way - for that, see reallyContains()
  17989. @see hitTest, reallyContains, getComponentAt
  17990. */
  17991. virtual bool contains (int x, int y);
  17992. /** Returns true if a given point lies in this component, taking any overlapping
  17993. siblings into account.
  17994. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17995. @param y the y co-ordinate to test, relative to this component's top edge.
  17996. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  17997. component, this determines the value that will
  17998. be returned.
  17999. @see contains, getComponentAt
  18000. */
  18001. bool reallyContains (int x, int y,
  18002. const bool returnTrueIfWithinAChild);
  18003. /** Returns the component at a certain point within this one.
  18004. @param x the x co-ordinate to test, relative to this component's left hand edge.
  18005. @param y the y co-ordinate to test, relative to this component's top edge.
  18006. @returns the component that is at this position - which may be 0, this component,
  18007. or one of its children. Note that overlapping siblings that might actually
  18008. be in the way are not taken into account by this method - to account for these,
  18009. instead call getComponentAt on the top-level parent of this component.
  18010. @see hitTest, contains, reallyContains
  18011. */
  18012. Component* getComponentAt (const int x, const int y);
  18013. /** Marks the whole component as needing to be redrawn.
  18014. Calling this will not do any repainting immediately, but will mark the component
  18015. as 'dirty'. At some point in the near future the operating system will send a paint
  18016. message, which will redraw all the dirty regions of all components.
  18017. There's no guarantee about how soon after calling repaint() the redraw will actually
  18018. happen, and other queued events may be delivered before a redraw is done.
  18019. If the setBufferedToImage() method has been used to cause this component
  18020. to use a buffer, the repaint() call will invalidate the component's buffer.
  18021. To redraw just a subsection of the component rather than the whole thing,
  18022. use the repaint (int, int, int, int) method.
  18023. @see paint
  18024. */
  18025. void repaint() throw();
  18026. /** Marks a subsection of this component as needing to be redrawn.
  18027. Calling this will not do any repainting immediately, but will mark the given region
  18028. of the component as 'dirty'. At some point in the near future the operating system
  18029. will send a paint message, which will redraw all the dirty regions of all components.
  18030. There's no guarantee about how soon after calling repaint() the redraw will actually
  18031. happen, and other queued events may be delivered before a redraw is done.
  18032. The region that is passed in will be clipped to keep it within the bounds of this
  18033. component.
  18034. @see repaint()
  18035. */
  18036. void repaint (const int x, const int y,
  18037. const int width, const int height) throw();
  18038. /** Makes the component use an internal buffer to optimise its redrawing.
  18039. Setting this flag to true will cause the component to allocate an
  18040. internal buffer into which it paints itself, so that when asked to
  18041. redraw itself, it can use this buffer rather than actually calling the
  18042. paint() method.
  18043. The buffer is kept until the repaint() method is called directly on
  18044. this component (or until it is resized), when the image is invalidated
  18045. and then redrawn the next time the component is painted.
  18046. Note that only the drawing that happens within the component's paint()
  18047. method is drawn into the buffer, it's child components are not buffered, and
  18048. nor is the paintOverChildren() method.
  18049. @see repaint, paint, createComponentSnapshot
  18050. */
  18051. void setBufferedToImage (const bool shouldBeBuffered) throw();
  18052. /** Generates a snapshot of part of this component.
  18053. This will return a new Image, the size of the rectangle specified,
  18054. containing a snapshot of the specified area of the component and all
  18055. its children.
  18056. The image may or may not have an alpha-channel, depending on whether the
  18057. image is opaque or not.
  18058. If the clipImageToComponentBounds parameter is true and the area is greater than
  18059. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  18060. then parts of the component beyond its bounds can be drawn.
  18061. The caller is responsible for deleting the image that is returned.
  18062. @see paintEntireComponent
  18063. */
  18064. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  18065. const bool clipImageToComponentBounds = true);
  18066. /** Draws this component and all its subcomponents onto the specified graphics
  18067. context.
  18068. You should very rarely have to use this method, it's simply there in case you need
  18069. to draw a component with a custom graphics context for some reason, e.g. for
  18070. creating a snapshot of the component.
  18071. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  18072. on its children in order to render the entire tree.
  18073. The graphics context may be left in an undefined state after this method returns,
  18074. so you may need to reset it if you're going to use it again.
  18075. */
  18076. void paintEntireComponent (Graphics& context);
  18077. /** Adds an effect filter to alter the component's appearance.
  18078. When a component has an effect filter set, then this is applied to the
  18079. results of its paint() method. There are a few preset effects, such as
  18080. a drop-shadow or glow, but they can be user-defined as well.
  18081. The effect that is passed in will not be deleted by the component - the
  18082. caller must take care of deleting it.
  18083. To remove an effect from a component, pass a null pointer in as the parameter.
  18084. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  18085. */
  18086. void setComponentEffect (ImageEffectFilter* const newEffect);
  18087. /** Returns the current component effect.
  18088. @see setComponentEffect
  18089. */
  18090. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  18091. /** Finds the appropriate look-and-feel to use for this component.
  18092. If the component hasn't had a look-and-feel explicitly set, this will
  18093. return the parent's look-and-feel, or just the default one if there's no
  18094. parent.
  18095. @see setLookAndFeel, lookAndFeelChanged
  18096. */
  18097. LookAndFeel& getLookAndFeel() const throw();
  18098. /** Sets the look and feel to use for this component.
  18099. This will also change the look and feel for any child components that haven't
  18100. had their look set explicitly.
  18101. The object passed in will not be deleted by the component, so it's the caller's
  18102. responsibility to manage it. It may be used at any time until this component
  18103. has been deleted.
  18104. Calling this method will also invoke the sendLookAndFeelChange() method.
  18105. @see getLookAndFeel, lookAndFeelChanged
  18106. */
  18107. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  18108. /** Called to let the component react to a change in the look-and-feel setting.
  18109. When the look-and-feel is changed for a component, this will be called in
  18110. all its child components, recursively.
  18111. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  18112. an application uses a LookAndFeel class that might have changed internally.
  18113. @see sendLookAndFeelChange, getLookAndFeel
  18114. */
  18115. virtual void lookAndFeelChanged();
  18116. /** Calls the lookAndFeelChanged() method in this component and all its children.
  18117. This will recurse through the children and their children, calling lookAndFeelChanged()
  18118. on them all.
  18119. @see lookAndFeelChanged
  18120. */
  18121. void sendLookAndFeelChange();
  18122. /** Indicates whether any parts of the component might be transparent.
  18123. Components that always paint all of their contents with solid colour and
  18124. thus completely cover any components behind them should use this method
  18125. to tell the repaint system that they are opaque.
  18126. This information is used to optimise drawing, because it means that
  18127. objects underneath opaque windows don't need to be painted.
  18128. By default, components are considered transparent, unless this is used to
  18129. make it otherwise.
  18130. @see isOpaque, getVisibleArea
  18131. */
  18132. void setOpaque (const bool shouldBeOpaque) throw();
  18133. /** Returns true if no parts of this component are transparent.
  18134. @returns the value that was set by setOpaque, (the default being false)
  18135. @see setOpaque
  18136. */
  18137. bool isOpaque() const throw();
  18138. /** Indicates whether the component should be brought to the front when clicked.
  18139. Setting this flag to true will cause the component to be brought to the front
  18140. when the mouse is clicked somewhere inside it or its child components.
  18141. Note that a top-level desktop window might still be brought to the front by the
  18142. operating system when it's clicked, depending on how the OS works.
  18143. By default this is set to false.
  18144. @see setMouseClickGrabsKeyboardFocus
  18145. */
  18146. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  18147. /** Indicates whether the component should be brought to the front when clicked-on.
  18148. @see setBroughtToFrontOnMouseClick
  18149. */
  18150. bool isBroughtToFrontOnMouseClick() const throw();
  18151. // Keyboard focus methods
  18152. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  18153. By default components aren't actually interested in gaining the
  18154. focus, but this method can be used to turn this on.
  18155. See the grabKeyboardFocus() method for details about the way a component
  18156. is chosen to receive the focus.
  18157. @see grabKeyboardFocus, getWantsKeyboardFocus
  18158. */
  18159. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  18160. /** Returns true if the component is interested in getting keyboard focus.
  18161. This returns the flag set by setWantsKeyboardFocus(). The default
  18162. setting is false.
  18163. @see setWantsKeyboardFocus
  18164. */
  18165. bool getWantsKeyboardFocus() const throw();
  18166. /** Chooses whether a click on this component automatically grabs the focus.
  18167. By default this is set to true, but you might want a component which can
  18168. be focused, but where you don't want the user to be able to affect it directly
  18169. by clicking.
  18170. */
  18171. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  18172. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  18173. See setMouseClickGrabsKeyboardFocus() for more info.
  18174. */
  18175. bool getMouseClickGrabsKeyboardFocus() const throw();
  18176. /** Tries to give keyboard focus to this component.
  18177. When the user clicks on a component or its grabKeyboardFocus()
  18178. method is called, the following procedure is used to work out which
  18179. component should get it:
  18180. - if the component that was clicked on actually wants focus (as indicated
  18181. by calling getWantsKeyboardFocus), it gets it.
  18182. - if the component itself doesn't want focus, it will try to pass it
  18183. on to whichever of its children is the default component, as determined by
  18184. KeyboardFocusTraverser::getDefaultComponent()
  18185. - if none of its children want focus at all, it will pass it up to its
  18186. parent instead, unless it's a top-level component without a parent,
  18187. in which case it just takes the focus itself.
  18188. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  18189. getCurrentlyFocusedComponent, focusGained, focusLost,
  18190. keyPressed, keyStateChanged
  18191. */
  18192. void grabKeyboardFocus();
  18193. /** Returns true if this component currently has the keyboard focus.
  18194. @param trueIfChildIsFocused if this is true, then the method returns true if
  18195. either this component or any of its children (recursively)
  18196. have the focus. If false, the method only returns true if
  18197. this component has the focus.
  18198. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  18199. focusGained, focusLost
  18200. */
  18201. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  18202. /** Returns the component that currently has the keyboard focus.
  18203. @returns the focused component, or null if nothing is focused.
  18204. */
  18205. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  18206. /** Tries to move the keyboard focus to one of this component's siblings.
  18207. This will try to move focus to either the next or previous component. (This
  18208. is the method that is used when shifting focus by pressing the tab key).
  18209. Components for which getWantsKeyboardFocus() returns false are not looked at.
  18210. @param moveToNext if true, the focus will move forwards; if false, it will
  18211. move backwards
  18212. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  18213. */
  18214. void moveKeyboardFocusToSibling (const bool moveToNext);
  18215. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  18216. which focus should be passed from this component.
  18217. The default implementation of this method will return a default
  18218. KeyboardFocusTraverser if this component is a focus container (as determined
  18219. by the setFocusContainer() method). If the component isn't a focus
  18220. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  18221. If you overrride this to return a custom KeyboardFocusTraverser, then
  18222. this component and all its sub-components will use the new object to
  18223. make their focusing decisions.
  18224. The method should return a new object, which the caller is required to
  18225. delete when no longer needed.
  18226. */
  18227. virtual KeyboardFocusTraverser* createFocusTraverser();
  18228. /** Returns the focus order of this component, if one has been specified.
  18229. By default components don't have a focus order - in that case, this
  18230. will return 0. Lower numbers indicate that the component will be
  18231. earlier in the focus traversal order.
  18232. To change the order, call setExplicitFocusOrder().
  18233. The focus order may be used by the KeyboardFocusTraverser class as part of
  18234. its algorithm for deciding the order in which components should be traversed.
  18235. See the KeyboardFocusTraverser class for more details on this.
  18236. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  18237. */
  18238. int getExplicitFocusOrder() const throw();
  18239. /** Sets the index used in determining the order in which focusable components
  18240. should be traversed.
  18241. A value of 0 or less is taken to mean that no explicit order is wanted, and
  18242. that traversal should use other factors, like the component's position.
  18243. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  18244. */
  18245. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  18246. /** Indicates whether this component is a parent for components that can have
  18247. their focus traversed.
  18248. This flag is used by the default implementation of the createFocusTraverser()
  18249. method, which uses the flag to find the first parent component (of the currently
  18250. focused one) which wants to be a focus container.
  18251. So using this method to set the flag to 'true' causes this component to
  18252. act as the top level within which focus is passed around.
  18253. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  18254. */
  18255. void setFocusContainer (const bool shouldBeFocusContainer) throw();
  18256. /** Returns true if this component has been marked as a focus container.
  18257. See setFocusContainer() for more details.
  18258. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  18259. */
  18260. bool isFocusContainer() const throw();
  18261. /** Returns true if the component (and all its parents) are enabled.
  18262. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  18263. what difference this makes to the component depends on the type. E.g. buttons
  18264. and sliders will choose to draw themselves differently, etc.
  18265. Note that if one of this component's parents is disabled, this will always
  18266. return false, even if this component itself is enabled.
  18267. @see setEnabled, enablementChanged
  18268. */
  18269. bool isEnabled() const throw();
  18270. /** Enables or disables this component.
  18271. Disabling a component will also cause all of its child components to become
  18272. disabled.
  18273. Similarly, enabling a component which is inside a disabled parent
  18274. component won't make any difference until the parent is re-enabled.
  18275. @see isEnabled, enablementChanged
  18276. */
  18277. void setEnabled (const bool shouldBeEnabled);
  18278. /** Callback to indicate that this component has been enabled or disabled.
  18279. This can be triggered by one of the component's parent components
  18280. being enabled or disabled, as well as changes to the component itself.
  18281. The default implementation of this method does nothing; your class may
  18282. wish to repaint itself or something when this happens.
  18283. @see setEnabled, isEnabled
  18284. */
  18285. virtual void enablementChanged();
  18286. /** Changes the mouse cursor shape to use when the mouse is over this component.
  18287. Note that the cursor set by this method can be overridden by the getMouseCursor
  18288. method.
  18289. @see MouseCursor
  18290. */
  18291. void setMouseCursor (const MouseCursor& cursorType) throw();
  18292. /** Returns the mouse cursor shape to use when the mouse is over this component.
  18293. The default implementation will return the cursor that was set by setCursor()
  18294. but can be overridden for more specialised purposes, e.g. returning different
  18295. cursors depending on the mouse position.
  18296. @see MouseCursor
  18297. */
  18298. virtual const MouseCursor getMouseCursor();
  18299. /** Forces the current mouse cursor to be updated.
  18300. If you're overriding the getMouseCursor() method to control which cursor is
  18301. displayed, then this will only be checked each time the user moves the mouse. So
  18302. if you want to force the system to check that the cursor being displayed is
  18303. up-to-date (even if the mouse is just sitting there), call this method.
  18304. This isn't needed if you're only using setMouseCursor().
  18305. */
  18306. void updateMouseCursor() const throw();
  18307. /** Components can override this method to draw their content.
  18308. The paint() method gets called when a region of a component needs redrawing,
  18309. either because the component's repaint() method has been called, or because
  18310. something has happened on the screen that means a section of a window needs
  18311. to be redrawn.
  18312. Any child components will draw themselves over whatever this method draws. If
  18313. you need to paint over the top of your child components, you can also implement
  18314. the paintOverChildren() method to do this.
  18315. If you want to cause a component to redraw itself, this is done asynchronously -
  18316. calling the repaint() method marks a region of the component as "dirty", and the
  18317. paint() method will automatically be called sometime later, by the message thread,
  18318. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  18319. you never redraw something synchronously.
  18320. You should never need to call this method directly - to take a snapshot of the
  18321. component you could use createComponentSnapshot() or paintEntireComponent().
  18322. @param g the graphics context that must be used to do the drawing operations.
  18323. @see repaint, paintOverChildren, Graphics
  18324. */
  18325. virtual void paint (Graphics& g);
  18326. /** Components can override this method to draw over the top of their children.
  18327. For most drawing operations, it's better to use the normal paint() method,
  18328. but if you need to overlay something on top of the children, this can be
  18329. used.
  18330. @see paint, Graphics
  18331. */
  18332. virtual void paintOverChildren (Graphics& g);
  18333. /** Called when the mouse moves inside this component.
  18334. If the mouse button isn't pressed and the mouse moves over a component,
  18335. this will be called to let the component react to this.
  18336. A component will always get a mouseEnter callback before a mouseMove.
  18337. @param e details about the position and status of the mouse event
  18338. @see mouseEnter, mouseExit, mouseDrag, contains
  18339. */
  18340. virtual void mouseMove (const MouseEvent& e);
  18341. /** Called when the mouse first enters this component.
  18342. If the mouse button isn't pressed and the mouse moves into a component,
  18343. this will be called to let the component react to this.
  18344. When the mouse button is pressed and held down while being moved in
  18345. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  18346. mouseDrag messages are sent to the component that the mouse was originally
  18347. clicked on, until the button is released.
  18348. If you're writing a component that needs to repaint itself when the mouse
  18349. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  18350. method.
  18351. @param e details about the position and status of the mouse event
  18352. @see mouseExit, mouseDrag, mouseMove, contains
  18353. */
  18354. virtual void mouseEnter (const MouseEvent& e);
  18355. /** Called when the mouse moves out of this component.
  18356. This will be called when the mouse moves off the edge of this
  18357. component.
  18358. If the mouse button was pressed, and it was then dragged off the
  18359. edge of the component and released, then this callback will happen
  18360. when the button is released, after the mouseUp callback.
  18361. If you're writing a component that needs to repaint itself when the mouse
  18362. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  18363. method.
  18364. @param e details about the position and status of the mouse event
  18365. @see mouseEnter, mouseDrag, mouseMove, contains
  18366. */
  18367. virtual void mouseExit (const MouseEvent& e);
  18368. /** Called when a mouse button is pressed while it's over this component.
  18369. The MouseEvent object passed in contains lots of methods for finding out
  18370. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18371. were held down at the time.
  18372. Once a button is held down, the mouseDrag method will be called when the
  18373. mouse moves, until the button is released.
  18374. @param e details about the position and status of the mouse event
  18375. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18376. */
  18377. virtual void mouseDown (const MouseEvent& e);
  18378. /** Called when the mouse is moved while a button is held down.
  18379. When a mouse button is pressed inside a component, that component
  18380. receives mouseDrag callbacks each time the mouse moves, even if the
  18381. mouse strays outside the component's bounds.
  18382. If you want to be able to drag things off the edge of a component
  18383. and have the component scroll when you get to the edges, the
  18384. beginDragAutoRepeat() method might be useful.
  18385. @param e details about the position and status of the mouse event
  18386. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  18387. */
  18388. virtual void mouseDrag (const MouseEvent& e);
  18389. /** Called when a mouse button is released.
  18390. A mouseUp callback is sent to the component in which a button was pressed
  18391. even if the mouse is actually over a different component when the
  18392. button is released.
  18393. The MouseEvent object passed in contains lots of methods for finding out
  18394. which buttons were down just before they were released.
  18395. @param e details about the position and status of the mouse event
  18396. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18397. */
  18398. virtual void mouseUp (const MouseEvent& e);
  18399. /** Called when a mouse button has been double-clicked in this component.
  18400. The MouseEvent object passed in contains lots of methods for finding out
  18401. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18402. were held down at the time.
  18403. For altering the time limit used to detect double-clicks,
  18404. see MouseEvent::setDoubleClickTimeout.
  18405. @param e details about the position and status of the mouse event
  18406. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  18407. MouseEvent::getDoubleClickTimeout
  18408. */
  18409. virtual void mouseDoubleClick (const MouseEvent& e);
  18410. /** Called when the mouse-wheel is moved.
  18411. This callback is sent to the component that the mouse is over when the
  18412. wheel is moved.
  18413. If not overridden, the component will forward this message to its parent, so
  18414. that parent components can collect mouse-wheel messages that happen to
  18415. child components which aren't interested in them.
  18416. @param e details about the position and status of the mouse event
  18417. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18418. value means the wheel has been pushed to the right, negative means it
  18419. was pushed to the left
  18420. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18421. value means the wheel has been pushed upwards, negative means it
  18422. was pushed downwards
  18423. */
  18424. virtual void mouseWheelMove (const MouseEvent& e,
  18425. float wheelIncrementX,
  18426. float wheelIncrementY);
  18427. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  18428. next mouse-drag operation.
  18429. This allows you to make sure that mouseDrag() events sent continuously, even
  18430. when the mouse isn't moving. This can be useful for things like auto-scrolling
  18431. components when the mouse is near an edge.
  18432. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  18433. minimum interval between consecutive mouse drag callbacks. The callbacks
  18434. will continue until the mouse is released, and then the interval will be reset,
  18435. so you need to make sure it's called every time you begin a drag event. If it
  18436. is called when the mouse isn't actually being pressed, it will apply to the next
  18437. mouse-drag operation that happens.
  18438. Passing an interval of 0 or less will cancel the auto-repeat.
  18439. @see mouseDrag
  18440. */
  18441. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  18442. /** Causes automatic repaints when the mouse enters or exits this component.
  18443. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  18444. on the component, it will trigger a repaint.
  18445. This is handy for things like buttons that need to draw themselves differently when
  18446. the mouse moves over them, and it avoids having to override all the different mouse
  18447. callbacks and call repaint().
  18448. @see mouseEnter, mouseExit, mouseDown, mouseUp
  18449. */
  18450. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  18451. /** Registers a listener to be told when mouse events occur in this component.
  18452. If you need to get informed about mouse events in a component but can't or
  18453. don't want to override its methods, you can attach any number of listeners
  18454. to the component, and these will get told about the events in addition to
  18455. the component's own callbacks being called.
  18456. Note that a MouseListener can also be attached to more than one component.
  18457. @param newListener the listener to register
  18458. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  18459. for events that happen to any child component
  18460. within this component, including deeply-nested
  18461. child components. If false, it will only be
  18462. told about events that this component handles.
  18463. @see MouseListener, removeMouseListener
  18464. */
  18465. void addMouseListener (MouseListener* const newListener,
  18466. const bool wantsEventsForAllNestedChildComponents) throw();
  18467. /** Deregisters a mouse listener.
  18468. @see addMouseListener, MouseListener
  18469. */
  18470. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  18471. /** Adds a listener that wants to hear about keypresses that this component receives.
  18472. The listeners that are registered with a component are called by its keyPressed() or
  18473. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  18474. If you add an object as a key listener, be careful to remove it when the object
  18475. is deleted, or the component will be left with a dangling pointer.
  18476. @see keyPressed, keyStateChanged, removeKeyListener
  18477. */
  18478. void addKeyListener (KeyListener* const newListener) throw();
  18479. /** Removes a previously-registered key listener.
  18480. @see addKeyListener
  18481. */
  18482. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  18483. /** Called when a key is pressed.
  18484. When a key is pressed, the component that has the keyboard focus will have this
  18485. method called. Remember that a component will only be given the focus if its
  18486. setWantsKeyboardFocus() method has been used to enable this.
  18487. If your implementation returns true, the event will be consumed and not passed
  18488. on to any other listeners. If it returns false, the key will be passed to any
  18489. KeyListeners that have been registered with this component. As soon as one of these
  18490. returns true, the process will stop, but if they all return false, the event will
  18491. be passed upwards to this component's parent, and so on.
  18492. The default implementation of this method does nothing and returns false.
  18493. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  18494. */
  18495. virtual bool keyPressed (const KeyPress& key);
  18496. /** Called when a key is pressed or released.
  18497. Whenever a key on the keyboard is pressed or released (including modifier keys
  18498. like shift and ctrl), this method will be called on the component that currently
  18499. has the keyboard focus. Remember that a component will only be given the focus if
  18500. its setWantsKeyboardFocus() method has been used to enable this.
  18501. If your implementation returns true, the event will be consumed and not passed
  18502. on to any other listeners. If it returns false, then any KeyListeners that have
  18503. been registered with this component will have their keyStateChanged methods called.
  18504. As soon as one of these returns true, the process will stop, but if they all return
  18505. false, the event will be passed upwards to this component's parent, and so on.
  18506. The default implementation of this method does nothing and returns false.
  18507. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  18508. method.
  18509. @param isKeyDown true if a key has been pressed; false if it has been released
  18510. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  18511. */
  18512. virtual bool keyStateChanged (const bool isKeyDown);
  18513. /** Called when a modifier key is pressed or released.
  18514. Whenever the shift, control, alt or command keys are pressed or released,
  18515. this method will be called on the component that currently has the keyboard focus.
  18516. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  18517. method has been used to enable this.
  18518. The default implementation of this method actually calls its parent's modifierKeysChanged
  18519. method, so that focused components which aren't interested in this will give their
  18520. parents a chance to act on the event instead.
  18521. @see keyStateChanged, ModifierKeys
  18522. */
  18523. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  18524. /** Enumeration used by the focusChanged() and focusLost() methods. */
  18525. enum FocusChangeType
  18526. {
  18527. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  18528. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  18529. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  18530. };
  18531. /** Called to indicate that this component has just acquired the keyboard focus.
  18532. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  18533. */
  18534. virtual void focusGained (FocusChangeType cause);
  18535. /** Called to indicate that this component has just lost the keyboard focus.
  18536. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  18537. */
  18538. virtual void focusLost (FocusChangeType cause);
  18539. /** Called to indicate that one of this component's children has been focused or unfocused.
  18540. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  18541. changed. It happens when focus moves from one of this component's children (at any depth)
  18542. to a component that isn't contained in this one, (or vice-versa).
  18543. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  18544. */
  18545. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  18546. /** Returns true if the mouse is currently over this component.
  18547. If the mouse isn't over the component, this will return false, even if the
  18548. mouse is currently being dragged - so you can use this in your mouseDrag
  18549. method to find out whether it's really over the component or not.
  18550. Note that when the mouse button is being held down, then the only component
  18551. for which this method will return true is the one that was originally
  18552. clicked on.
  18553. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  18554. */
  18555. bool isMouseOver() const throw();
  18556. /** Returns true if the mouse button is currently held down in this component.
  18557. Note that this is a test to see whether the mouse is being pressed in this
  18558. component, so it'll return false if called on component A when the mouse
  18559. is actually being dragged in component B.
  18560. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  18561. */
  18562. bool isMouseButtonDown() const throw();
  18563. /** True if the mouse is over this component, or if it's being dragged in this component.
  18564. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  18565. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  18566. */
  18567. bool isMouseOverOrDragging() const throw();
  18568. /** Returns true if a mouse button is currently down.
  18569. Unlike isMouseButtonDown, this will test the current state of the
  18570. buttons without regard to which component (if any) it has been
  18571. pressed in.
  18572. @see isMouseButtonDown, ModifierKeys
  18573. */
  18574. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  18575. /** Returns the mouse's current position, relative to this component.
  18576. The co-ordinates are relative to the component's top-left corner.
  18577. */
  18578. void getMouseXYRelative (int& x, int& y) const throw();
  18579. /** Returns the component that's currently underneath the mouse.
  18580. @returns the component or 0 if there isn't one.
  18581. @see contains, getComponentAt
  18582. */
  18583. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  18584. /** Allows the mouse to move beyond the edges of the screen.
  18585. Calling this method when the mouse button is currently pressed inside this component
  18586. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  18587. the edges of the screen.
  18588. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  18589. can be used for things like custom slider controls or dragging objects around, where
  18590. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  18591. The unbounded mode is automatically turned off when the mouse button is released, or
  18592. it can be turned off explicitly by calling this method again.
  18593. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  18594. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  18595. hidden; if true, it will only be hidden when it
  18596. is moved beyond the edge of the screen
  18597. */
  18598. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  18599. bool keepCursorVisibleUntilOffscreen = false) throw();
  18600. /** Called when this component's size has been changed.
  18601. A component can implement this method to do things such as laying out its
  18602. child components when its width or height changes.
  18603. The method is called synchronously as a result of the setBounds or setSize
  18604. methods, so repeatedly changing a components size will repeatedly call its
  18605. resized method (unlike things like repainting, where multiple calls to repaint
  18606. are coalesced together).
  18607. If the component is a top-level window on the desktop, its size could also
  18608. be changed by operating-system factors beyond the application's control.
  18609. @see moved, setSize
  18610. */
  18611. virtual void resized();
  18612. /** Called when this component's position has been changed.
  18613. This is called when the position relative to its parent changes, not when
  18614. its absolute position on the screen changes (so it won't be called for
  18615. all child components when a parent component is moved).
  18616. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  18617. or any of the other repositioning methods, and like resized(), it will be
  18618. called each time those methods are called.
  18619. If the component is a top-level window on the desktop, its position could also
  18620. be changed by operating-system factors beyond the application's control.
  18621. @see resized, setBounds
  18622. */
  18623. virtual void moved();
  18624. /** Called when one of this component's children is moved or resized.
  18625. If the parent wants to know about changes to its immediate children (not
  18626. to children of its children), this is the method to override.
  18627. @see moved, resized, parentSizeChanged
  18628. */
  18629. virtual void childBoundsChanged (Component* child);
  18630. /** Called when this component's immediate parent has been resized.
  18631. If the component is a top-level window, this indicates that the screen size
  18632. has changed.
  18633. @see childBoundsChanged, moved, resized
  18634. */
  18635. virtual void parentSizeChanged();
  18636. /** Called when this component has been moved to the front of its siblings.
  18637. The component may have been brought to the front by the toFront() method, or
  18638. by the operating system if it's a top-level window.
  18639. @see toFront
  18640. */
  18641. virtual void broughtToFront();
  18642. /** Adds a listener to be told about changes to the component hierarchy or position.
  18643. Component listeners get called when this component's size, position or children
  18644. change - see the ComponentListener class for more details.
  18645. @param newListener the listener to register - if this is already registered, it
  18646. will be ignored.
  18647. @see ComponentListener, removeComponentListener
  18648. */
  18649. void addComponentListener (ComponentListener* const newListener) throw();
  18650. /** Removes a component listener.
  18651. @see addComponentListener
  18652. */
  18653. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  18654. /** Dispatches a numbered message to this component.
  18655. This is a quick and cheap way of allowing simple asynchronous messages to
  18656. be sent to components. It's also safe, because if the component that you
  18657. send the message to is a null or dangling pointer, this won't cause an error.
  18658. The command ID is later delivered to the component's handleCommandMessage() method by
  18659. the application's message queue.
  18660. @see handleCommandMessage
  18661. */
  18662. void postCommandMessage (const int commandId) throw();
  18663. /** Called to handle a command that was sent by postCommandMessage().
  18664. This is called by the message thread when a command message arrives, and
  18665. the component can override this method to process it in any way it needs to.
  18666. @see postCommandMessage
  18667. */
  18668. virtual void handleCommandMessage (int commandId);
  18669. /** Runs a component modally, waiting until the loop terminates.
  18670. This method first makes the component visible, brings it to the front and
  18671. gives it the keyboard focus.
  18672. It then runs a loop, dispatching messages from the system message queue, but
  18673. blocking all mouse or keyboard messages from reaching any components other
  18674. than this one and its children.
  18675. This loop continues until the component's exitModalState() method is called (or
  18676. the component is deleted), and then this method returns, returning the value
  18677. passed into exitModalState().
  18678. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  18679. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  18680. */
  18681. int runModalLoop();
  18682. /** Puts the component into a modal state.
  18683. This makes the component modal, so that messages are blocked from reaching
  18684. any components other than this one and its children, but unlike runModalLoop(),
  18685. this method returns immediately.
  18686. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  18687. get the focus, which is usually what you'll want it to do. If not, it will leave
  18688. the focus unchanged.
  18689. @see exitModalState, runModalLoop
  18690. */
  18691. void enterModalState (const bool takeKeyboardFocus = true);
  18692. /** Ends a component's modal state.
  18693. If this component is currently modal, this will turn of its modalness, and return
  18694. a value to the runModalLoop() method that might have be running its modal loop.
  18695. @see runModalLoop, enterModalState, isCurrentlyModal
  18696. */
  18697. void exitModalState (const int returnValue);
  18698. /** Returns true if this component is the modal one.
  18699. It's possible to have nested modal components, e.g. a pop-up dialog box
  18700. that launches another pop-up, but this will only return true for
  18701. the one at the top of the stack.
  18702. @see getCurrentlyModalComponent
  18703. */
  18704. bool isCurrentlyModal() const throw();
  18705. /** Returns the number of components that are currently in a modal state.
  18706. @see getCurrentlyModalComponent
  18707. */
  18708. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  18709. /** Returns one of the components that are currently modal.
  18710. The index specifies which of the possible modal components to return. The order
  18711. of the components in this list is the reverse of the order in which they became
  18712. modal - so the component at index 0 is always the active component, and the others
  18713. are progressively earlier ones that are themselves now blocked by later ones.
  18714. @returns the modal component, or null if no components are modal (or if the
  18715. index is out of range)
  18716. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  18717. */
  18718. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  18719. /** Checks whether there's a modal component somewhere that's stopping this one
  18720. from receiving messages.
  18721. If there is a modal component, its canModalEventBeSentToComponent() method
  18722. will be called to see if it will still allow this component to receive events.
  18723. @see runModalLoop, getCurrentlyModalComponent
  18724. */
  18725. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  18726. /** When a component is modal, this callback allows it to choose which other
  18727. components can still receive events.
  18728. When a modal component is active and the user clicks on a non-modal component,
  18729. this method is called on the modal component, and if it returns true, the
  18730. event is allowed to reach its target. If it returns false, the event is blocked
  18731. and the inputAttemptWhenModal() callback is made.
  18732. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  18733. implementation just returns false in all cases.
  18734. */
  18735. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  18736. /** Called when the user tries to click on a component that is blocked by another
  18737. modal component.
  18738. When a component is modal and the user clicks on one of the other components,
  18739. the modal component will receive this callback.
  18740. The default implementation of this method will play a beep, and bring the currently
  18741. modal component to the front, but it can be overridden to do other tasks.
  18742. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  18743. */
  18744. virtual void inputAttemptWhenModal();
  18745. /** Returns one of the component's properties as a string.
  18746. @param keyName the name of the property to retrieve
  18747. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18748. properties, then it will check whether the parent component has
  18749. the key.
  18750. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18751. */
  18752. const String getComponentProperty (const String& keyName,
  18753. const bool useParentComponentIfNotFound,
  18754. const String& defaultReturnValue = String::empty) const throw();
  18755. /** Returns one of the properties as an integer.
  18756. @param keyName the name of the property to retrieve
  18757. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18758. properties, then it will check whether the parent component has
  18759. the key.
  18760. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18761. */
  18762. int getComponentPropertyInt (const String& keyName,
  18763. const bool useParentComponentIfNotFound,
  18764. const int defaultReturnValue = 0) const throw();
  18765. /** Returns one of the properties as an double.
  18766. @param keyName the name of the property to retrieve
  18767. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18768. properties, then it will check whether the parent component has
  18769. the key.
  18770. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18771. */
  18772. double getComponentPropertyDouble (const String& keyName,
  18773. const bool useParentComponentIfNotFound,
  18774. const double defaultReturnValue = 0.0) const throw();
  18775. /** Returns one of the properties as an boolean.
  18776. The result will be true if the string found for this key name can be parsed as a non-zero
  18777. integer.
  18778. @param keyName the name of the property to retrieve
  18779. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18780. properties, then it will check whether the parent component has
  18781. the key.
  18782. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18783. */
  18784. bool getComponentPropertyBool (const String& keyName,
  18785. const bool useParentComponentIfNotFound,
  18786. const bool defaultReturnValue = false) const throw();
  18787. /** Returns one of the properties as an colour.
  18788. @param keyName the name of the property to retrieve
  18789. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18790. properties, then it will check whether the parent component has
  18791. the key.
  18792. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  18793. */
  18794. const Colour getComponentPropertyColour (const String& keyName,
  18795. const bool useParentComponentIfNotFound,
  18796. const Colour& defaultReturnValue = Colours::black) const throw();
  18797. /** Sets a named property as a string.
  18798. @param keyName the name of the property to set. (This mustn't be an empty string)
  18799. @param value the new value to set it to
  18800. @see removeComponentProperty
  18801. */
  18802. void setComponentProperty (const String& keyName, const String& value) throw();
  18803. /** Sets a named property to an integer.
  18804. @param keyName the name of the property to set. (This mustn't be an empty string)
  18805. @param value the new value to set it to
  18806. @see removeComponentProperty
  18807. */
  18808. void setComponentProperty (const String& keyName, const int value) throw();
  18809. /** Sets a named property to a double.
  18810. @param keyName the name of the property to set. (This mustn't be an empty string)
  18811. @param value the new value to set it to
  18812. @see removeComponentProperty
  18813. */
  18814. void setComponentProperty (const String& keyName, const double value) throw();
  18815. /** Sets a named property to a boolean.
  18816. @param keyName the name of the property to set. (This mustn't be an empty string)
  18817. @param value the new value to set it to
  18818. @see removeComponentProperty
  18819. */
  18820. void setComponentProperty (const String& keyName, const bool value) throw();
  18821. /** Sets a named property to a colour.
  18822. @param keyName the name of the property to set. (This mustn't be an empty string)
  18823. @param newColour the new colour to set it to
  18824. @see removeComponentProperty
  18825. */
  18826. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  18827. /** Deletes a named component property.
  18828. @param keyName the name of the property to delete. (This mustn't be an empty string)
  18829. @see setComponentProperty, getComponentProperty
  18830. */
  18831. void removeComponentProperty (const String& keyName) throw();
  18832. /** Returns the complete set of properties that have been set for this component.
  18833. If no properties have been set, this will return a null pointer.
  18834. @see getComponentProperty, setComponentProperty
  18835. */
  18836. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  18837. /** Looks for a colour that has been registered with the given colour ID number.
  18838. If a colour has been set for this ID number using setColour(), then it is
  18839. returned. If none has been set, the method will try calling the component's
  18840. LookAndFeel class's findColour() method. If none has been registered with the
  18841. look-and-feel either, it will just return black.
  18842. The colour IDs for various purposes are stored as enums in the components that
  18843. they are relevent to - for an example, see Slider::ColourIds,
  18844. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  18845. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  18846. */
  18847. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  18848. /** Registers a colour to be used for a particular purpose.
  18849. Changing a colour will cause a synchronous callback to the colourChanged()
  18850. method, which your component can override if it needs to do something when
  18851. colours are altered.
  18852. For more details about colour IDs, see the comments for findColour().
  18853. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  18854. */
  18855. void setColour (const int colourId, const Colour& colour);
  18856. /** If a colour has been set with setColour(), this will remove it.
  18857. This allows you to make a colour revert to its default state.
  18858. */
  18859. void removeColour (const int colourId);
  18860. /** Returns true if the specified colour ID has been explicitly set for this
  18861. component using the setColour() method.
  18862. */
  18863. bool isColourSpecified (const int colourId) const throw();
  18864. /** This looks for any colours that have been specified for this component,
  18865. and copies them to the specified target component.
  18866. */
  18867. void copyAllExplicitColoursTo (Component& target) const throw();
  18868. /** This method is called when a colour is changed by the setColour() method.
  18869. @see setColour, findColour
  18870. */
  18871. virtual void colourChanged();
  18872. /** Returns the underlying native window handle for this component.
  18873. This is platform-dependent and strictly for power-users only!
  18874. */
  18875. void* getWindowHandle() const throw();
  18876. /** When created, each component is given a number to uniquely identify it.
  18877. The number is incremented each time a new component is created, so it's a more
  18878. unique way of identifying a component than using its memory location (which
  18879. may be reused after the component is deleted, of course).
  18880. */
  18881. uint32 getComponentUID() const throw() { return componentUID; }
  18882. juce_UseDebuggingNewOperator
  18883. private:
  18884. friend class ComponentPeer;
  18885. friend class InternalDragRepeater;
  18886. static Component* currentlyFocusedComponent;
  18887. static Component* componentUnderMouse;
  18888. String componentName_;
  18889. Component* parentComponent_;
  18890. uint32 componentUID;
  18891. Rectangle bounds_;
  18892. unsigned short numDeepMouseListeners;
  18893. Array <Component*> childComponentList_;
  18894. LookAndFeel* lookAndFeel_;
  18895. MouseCursor cursor_;
  18896. ImageEffectFilter* effect_;
  18897. Image* bufferedImage_;
  18898. VoidArray* mouseListeners_;
  18899. VoidArray* keyListeners_;
  18900. VoidArray* componentListeners_;
  18901. PropertySet* propertySet_;
  18902. struct ComponentFlags
  18903. {
  18904. bool hasHeavyweightPeerFlag : 1;
  18905. bool visibleFlag : 1;
  18906. bool opaqueFlag : 1;
  18907. bool ignoresMouseClicksFlag : 1;
  18908. bool allowChildMouseClicksFlag : 1;
  18909. bool wantsFocusFlag : 1;
  18910. bool isFocusContainerFlag : 1;
  18911. bool dontFocusOnMouseClickFlag : 1;
  18912. bool alwaysOnTopFlag : 1;
  18913. bool bufferToImageFlag : 1;
  18914. bool bringToFrontOnClickFlag : 1;
  18915. bool repaintOnMouseActivityFlag : 1;
  18916. bool draggingFlag : 1;
  18917. bool mouseOverFlag : 1;
  18918. bool mouseInsideFlag : 1;
  18919. bool currentlyModalFlag : 1;
  18920. bool isDisabledFlag : 1;
  18921. bool childCompFocusedFlag : 1;
  18922. #ifdef JUCE_DEBUG
  18923. bool isInsidePaintCall : 1;
  18924. #endif
  18925. };
  18926. union
  18927. {
  18928. uint32 componentFlags_;
  18929. ComponentFlags flags;
  18930. };
  18931. void internalMouseEnter (int x, int y, const int64 time);
  18932. void internalMouseExit (int x, int y, const int64 time);
  18933. void internalMouseDown (int x, int y);
  18934. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  18935. void internalMouseDrag (int x, int y, const int64 time);
  18936. void internalMouseMove (int x, int y, const int64 time);
  18937. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  18938. void internalBroughtToFront();
  18939. void internalFocusGain (const FocusChangeType cause);
  18940. void internalFocusLoss (const FocusChangeType cause);
  18941. void internalChildFocusChange (FocusChangeType cause);
  18942. void internalModalInputAttempt();
  18943. void internalModifierKeysChanged();
  18944. void internalChildrenChanged();
  18945. void internalHierarchyChanged();
  18946. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  18947. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  18948. void repaintParent() throw();
  18949. void sendFakeMouseMove() const;
  18950. void takeKeyboardFocus (const FocusChangeType cause);
  18951. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  18952. static void giveAwayFocus();
  18953. void sendEnablementChangeMessage();
  18954. static void* runModalLoopCallback (void*);
  18955. static void bringModalComponentToFront();
  18956. void subtractObscuredRegions (RectangleList& result,
  18957. const int deltaX, const int deltaY,
  18958. const Rectangle& clipRect,
  18959. const Component* const compToAvoid) const throw();
  18960. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  18961. const int deltaX, const int deltaY) const throw();
  18962. // how much of the component is not off the edges of its parents
  18963. const Rectangle getUnclippedArea() const;
  18964. void sendVisibilityChangeMessage();
  18965. // This is included here just to cause a compile error if your code is still handling
  18966. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  18967. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  18968. // implement its methods instead of this Component method).
  18969. virtual void filesDropped (const StringArray&, int, int) {}
  18970. // components aren't allowed to have copy constructors, as this would mess up parent
  18971. // hierarchies. You might need to give your subclasses a private dummy constructor like
  18972. // this one to avoid compiler warnings.
  18973. Component (const Component&);
  18974. const Component& operator= (const Component&);
  18975. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  18976. // subclass to use the new parameters to keyStateChanged)
  18977. virtual void keyStateChanged() {};
  18978. protected:
  18979. /** @internal */
  18980. virtual void internalRepaint (int x, int y, int w, int h);
  18981. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  18982. /** Overridden from the MessageListener parent class.
  18983. You can override this if you really need to, but be sure to pass your unwanted messages up
  18984. to this base class implementation, as the Component class needs to send itself messages
  18985. to work properly.
  18986. */
  18987. void handleMessage (const Message&);
  18988. };
  18989. #endif // __JUCE_COMPONENT_JUCEHEADER__
  18990. /********* End of inlined file: juce_Component.h *********/
  18991. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  18992. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18993. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18994. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  18995. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18996. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18997. /** A type used to hold the unique ID for an application command.
  18998. This is a numeric type, so it can be stored as an integer.
  18999. @see ApplicationCommandInfo, ApplicationCommandManager,
  19000. ApplicationCommandTarget, KeyPressMappingSet
  19001. */
  19002. typedef int CommandID;
  19003. /** A set of general-purpose application command IDs.
  19004. Because these commands are likely to be used in most apps, they're defined
  19005. here to help different apps to use the same numeric values for them.
  19006. Of course you don't have to use these, but some of them are used internally by
  19007. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  19008. @see ApplicationCommandInfo, ApplicationCommandManager,
  19009. ApplicationCommandTarget, KeyPressMappingSet
  19010. */
  19011. namespace StandardApplicationCommandIDs
  19012. {
  19013. /** This command ID should be used to send a "Quit the App" command.
  19014. This command is recognised by the JUCEApplication class, so if it is invoked
  19015. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  19016. object will catch it and call JUCEApplication::systemRequestedQuit().
  19017. */
  19018. static const CommandID quit = 0x1001;
  19019. /** The command ID that should be used to send a "Delete" command. */
  19020. static const CommandID del = 0x1002;
  19021. /** The command ID that should be used to send a "Cut" command. */
  19022. static const CommandID cut = 0x1003;
  19023. /** The command ID that should be used to send a "Copy to clipboard" command. */
  19024. static const CommandID copy = 0x1004;
  19025. /** The command ID that should be used to send a "Paste from clipboard" command. */
  19026. static const CommandID paste = 0x1005;
  19027. /** The command ID that should be used to send a "Select all" command. */
  19028. static const CommandID selectAll = 0x1006;
  19029. /** The command ID that should be used to send a "Deselect all" command. */
  19030. static const CommandID deselectAll = 0x1007;
  19031. }
  19032. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  19033. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  19034. /**
  19035. Holds information describing an application command.
  19036. This object is used to pass information about a particular command, such as its
  19037. name, description and other usage flags.
  19038. When an ApplicationCommandTarget is asked to provide information about the commands
  19039. it can perform, this is the structure gets filled-in to describe each one.
  19040. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  19041. ApplicationCommandManager
  19042. */
  19043. struct JUCE_API ApplicationCommandInfo
  19044. {
  19045. ApplicationCommandInfo (const CommandID commandID) throw();
  19046. /** Sets a number of the structures values at once.
  19047. The meanings of each of the parameters is described below, in the appropriate
  19048. member variable's description.
  19049. */
  19050. void setInfo (const String& shortName,
  19051. const String& description,
  19052. const String& categoryName,
  19053. const int flags) throw();
  19054. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  19055. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  19056. is false, the bit is set.
  19057. */
  19058. void setActive (const bool isActive) throw();
  19059. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  19060. */
  19061. void setTicked (const bool isTicked) throw();
  19062. /** Handy method for adding a keypress to the defaultKeypresses array.
  19063. This is just so you can write things like:
  19064. @code
  19065. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  19066. @endcode
  19067. instead of
  19068. @code
  19069. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  19070. @endcode
  19071. */
  19072. void addDefaultKeypress (const int keyCode,
  19073. const ModifierKeys& modifiers) throw();
  19074. /** The command's unique ID number.
  19075. */
  19076. CommandID commandID;
  19077. /** A short name to describe the command.
  19078. This should be suitable for use in menus, on buttons that trigger the command, etc.
  19079. You can use the setInfo() method to quickly set this and some of the command's
  19080. other properties.
  19081. */
  19082. String shortName;
  19083. /** A longer description of the command.
  19084. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  19085. pop-up tooltip describing what the command does.
  19086. You can use the setInfo() method to quickly set this and some of the command's
  19087. other properties.
  19088. */
  19089. String description;
  19090. /** A named category that the command fits into.
  19091. You can give your commands any category you like, and these will be displayed in
  19092. contexts such as the KeyMappingEditorComponent, where the category is used to group
  19093. commands together.
  19094. You can use the setInfo() method to quickly set this and some of the command's
  19095. other properties.
  19096. */
  19097. String categoryName;
  19098. /** A list of zero or more keypresses that should be used as the default keys for
  19099. this command.
  19100. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  19101. this list to initialise the default set of key-to-command mappings.
  19102. @see addDefaultKeypress
  19103. */
  19104. Array <KeyPress> defaultKeypresses;
  19105. /** Flags describing the ways in which this command should be used.
  19106. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  19107. variable.
  19108. */
  19109. enum CommandFlags
  19110. {
  19111. /** Indicates that the command can't currently be performed.
  19112. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  19113. not currently permissable to perform the command. If the flag is set, then
  19114. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  19115. command or show themselves as not being enabled.
  19116. @see ApplicationCommandInfo::setActive
  19117. */
  19118. isDisabled = 1 << 0,
  19119. /** Indicates that the command should have a tick next to it on a menu.
  19120. If your command is shown on a menu and this is set, it'll show a tick next to
  19121. it. Other components such as buttons may also use this flag to indicate that it
  19122. is a value that can be toggled, and is currently in the 'on' state.
  19123. @see ApplicationCommandInfo::setTicked
  19124. */
  19125. isTicked = 1 << 1,
  19126. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  19127. it will call the command twice, once on key-down and again on key-up.
  19128. @see ApplicationCommandTarget::InvocationInfo
  19129. */
  19130. wantsKeyUpDownCallbacks = 1 << 2,
  19131. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  19132. command in its list.
  19133. */
  19134. hiddenFromKeyEditor = 1 << 3,
  19135. /** If this flag is present, then a KeyMappingEditorComponent will display the
  19136. command in its list, but won't allow the assigned keypress to be changed.
  19137. */
  19138. readOnlyInKeyEditor = 1 << 4,
  19139. /** If this flag is present and the command is invoked from a keypress, then any
  19140. buttons or menus that are also connected to the command will not flash to
  19141. indicate that they've been triggered.
  19142. */
  19143. dontTriggerVisualFeedback = 1 << 5
  19144. };
  19145. /** A bitwise-OR of the values specified in the CommandFlags enum.
  19146. You can use the setInfo() method to quickly set this and some of the command's
  19147. other properties.
  19148. */
  19149. int flags;
  19150. };
  19151. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  19152. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  19153. /**
  19154. A command target publishes a list of command IDs that it can perform.
  19155. An ApplicationCommandManager despatches commands to targets, which must be
  19156. able to provide information about what commands they can handle.
  19157. To create a target, you'll need to inherit from this class, implementing all of
  19158. its pure virtual methods.
  19159. For info about how a target is chosen to receive a command, see
  19160. ApplicationCommandManager::getFirstCommandTarget().
  19161. @see ApplicationCommandManager, ApplicationCommandInfo
  19162. */
  19163. class JUCE_API ApplicationCommandTarget
  19164. {
  19165. public:
  19166. /** Creates a command target. */
  19167. ApplicationCommandTarget();
  19168. /** Destructor. */
  19169. virtual ~ApplicationCommandTarget();
  19170. /**
  19171. */
  19172. struct JUCE_API InvocationInfo
  19173. {
  19174. InvocationInfo (const CommandID commandID) throw();
  19175. /** The UID of the command that should be performed. */
  19176. CommandID commandID;
  19177. /** The command's flags.
  19178. See ApplicationCommandInfo for a description of these flag values.
  19179. */
  19180. int commandFlags;
  19181. /** The types of context in which the command might be called. */
  19182. enum InvocationMethod
  19183. {
  19184. direct = 0, /**< The command is being invoked directly by a piece of code. */
  19185. fromKeyPress, /**< The command is being invoked by a key-press. */
  19186. fromMenu, /**< The command is being invoked by a menu selection. */
  19187. fromButton /**< The command is being invoked by a button click. */
  19188. };
  19189. /** The type of event that triggered this command. */
  19190. InvocationMethod invocationMethod;
  19191. /** If triggered by a keypress or menu, this will be the component that had the
  19192. keyboard focus at the time.
  19193. If triggered by a button, it may be set to that component, or it may be null.
  19194. */
  19195. Component* originatingComponent;
  19196. /** The keypress that was used to invoke it.
  19197. Note that this will be an invalid keypress if the command was invoked
  19198. by some other means than a keyboard shortcut.
  19199. */
  19200. KeyPress keyPress;
  19201. /** True if the callback is being invoked when the key is pressed,
  19202. false if the key is being released.
  19203. @see KeyPressMappingSet::addCommand()
  19204. */
  19205. bool isKeyDown;
  19206. /** If the key is being released, this indicates how long it had been held
  19207. down for.
  19208. (Only relevant if isKeyDown is false.)
  19209. */
  19210. int millisecsSinceKeyPressed;
  19211. };
  19212. /** This must return the next target to try after this one.
  19213. When a command is being sent, and the first target can't handle
  19214. that command, this method is used to determine the next target that should
  19215. be tried.
  19216. It may return 0 if it doesn't know of another target.
  19217. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  19218. method to return a parent component that might want to handle it.
  19219. @see invoke
  19220. */
  19221. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  19222. /** This must return a complete list of commands that this target can handle.
  19223. Your target should add all the command IDs that it handles to the array that is
  19224. passed-in.
  19225. */
  19226. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  19227. /** This must provide details about one of the commands that this target can perform.
  19228. This will be called with one of the command IDs that the target provided in its
  19229. getAllCommands() methods.
  19230. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  19231. suitable information about the command. (The commandID field will already have been filled-in
  19232. by the caller).
  19233. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  19234. set all the fields at once.
  19235. If the command is currently inactive for some reason, this method must use
  19236. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  19237. bit of the ApplicationCommandInfo::flags field).
  19238. Any default key-presses for the command should be appended to the
  19239. ApplicationCommandInfo::defaultKeypresses field.
  19240. Note that if you change something that affects the status of the commands
  19241. that would be returned by this method (e.g. something that makes some commands
  19242. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  19243. to cause the manager to refresh its status.
  19244. */
  19245. virtual void getCommandInfo (const CommandID commandID,
  19246. ApplicationCommandInfo& result) = 0;
  19247. /** This must actually perform the specified command.
  19248. If this target is able to perform the command specified by the commandID field of the
  19249. InvocationInfo structure, then it should do so, and must return true.
  19250. If it can't handle this command, it should return false, which tells the caller to pass
  19251. the command on to the next target in line.
  19252. @see invoke, ApplicationCommandManager::invoke
  19253. */
  19254. virtual bool perform (const InvocationInfo& info) = 0;
  19255. /** Makes this target invoke a command.
  19256. Your code can call this method to invoke a command on this target, but normally
  19257. you'd call it indirectly via ApplicationCommandManager::invoke() or
  19258. ApplicationCommandManager::invokeDirectly().
  19259. If this target can perform the given command, it will call its perform() method to
  19260. do so. If not, then getNextCommandTarget() will be used to determine the next target
  19261. to try, and the command will be passed along to it.
  19262. @param invocationInfo this must be correctly filled-in, describing the context for
  19263. the invocation.
  19264. @param asynchronously if false, the command will be performed before this method returns.
  19265. If true, a message will be posted so that the command will be performed
  19266. later on the message thread, and this method will return immediately.
  19267. @see perform, ApplicationCommandManager::invoke
  19268. */
  19269. bool invoke (const InvocationInfo& invocationInfo,
  19270. const bool asynchronously);
  19271. /** Invokes a given command directly on this target.
  19272. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  19273. structure.
  19274. */
  19275. bool invokeDirectly (const CommandID commandID,
  19276. const bool asynchronously);
  19277. /** Searches this target and all subsequent ones for the first one that can handle
  19278. the specified command.
  19279. This will use getNextCommandTarget() to determine the chain of targets to try
  19280. after this one.
  19281. */
  19282. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  19283. /** Checks whether this command can currently be performed by this target.
  19284. This will return true only if a call to getCommandInfo() doesn't set the
  19285. isDisabled flag to indicate that the command is inactive.
  19286. */
  19287. bool isCommandActive (const CommandID commandID);
  19288. /** If this object is a Component, this method will seach upwards in its current
  19289. UI hierarchy for the next parent component that implements the
  19290. ApplicationCommandTarget class.
  19291. If your target is a Component, this is a very handy method to use in your
  19292. getNextCommandTarget() implementation.
  19293. */
  19294. ApplicationCommandTarget* findFirstTargetParentComponent();
  19295. juce_UseDebuggingNewOperator
  19296. private:
  19297. // (for async invocation of commands)
  19298. class CommandTargetMessageInvoker : public MessageListener
  19299. {
  19300. public:
  19301. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  19302. ~CommandTargetMessageInvoker();
  19303. void handleMessage (const Message& message);
  19304. private:
  19305. ApplicationCommandTarget* const owner;
  19306. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  19307. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  19308. };
  19309. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  19310. friend class CommandTargetMessageInvoker;
  19311. bool tryToInvoke (const InvocationInfo& info, const bool async);
  19312. ApplicationCommandTarget (const ApplicationCommandTarget&);
  19313. const ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  19314. };
  19315. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  19316. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  19317. /********* Start of inlined file: juce_ActionListener.h *********/
  19318. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  19319. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  19320. /**
  19321. Receives callbacks to indicate that some kind of event has occurred.
  19322. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  19323. about something that's happened.
  19324. @see ActionListenerList, ActionBroadcaster, ChangeListener
  19325. */
  19326. class JUCE_API ActionListener
  19327. {
  19328. public:
  19329. /** Destructor. */
  19330. virtual ~ActionListener() {}
  19331. /** Overridden by your subclass to receive the callback.
  19332. @param message the string that was specified when the event was triggered
  19333. by a call to ActionListenerList::sendActionMessage()
  19334. */
  19335. virtual void actionListenerCallback (const String& message) = 0;
  19336. };
  19337. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  19338. /********* End of inlined file: juce_ActionListener.h *********/
  19339. /**
  19340. An instance of this class is used to specify initialisation and shutdown
  19341. code for the application.
  19342. An application that wants to run in the JUCE framework needs to declare a
  19343. subclass of JUCEApplication and implement its various pure virtual methods.
  19344. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  19345. to declare an instance of this class and generate a suitable platform-specific
  19346. main() function.
  19347. e.g. @code
  19348. class MyJUCEApp : public JUCEApplication
  19349. {
  19350. // NEVER put objects inside a JUCEApplication class - only use pointers to
  19351. // objects, which you must create in the initialise() method.
  19352. MyApplicationWindow* myMainWindow;
  19353. public:
  19354. MyJUCEApp()
  19355. : myMainWindow (0)
  19356. {
  19357. // never create any Juce objects in the constructor - do all your initialisation
  19358. // in the initialise() method.
  19359. }
  19360. ~MyJUCEApp()
  19361. {
  19362. // all your shutdown code must have already been done in the shutdown() method -
  19363. // nothing should happen in this destructor.
  19364. }
  19365. void initialise (const String& commandLine)
  19366. {
  19367. myMainWindow = new MyApplicationWindow();
  19368. myMainWindow->setBounds (100, 100, 400, 500);
  19369. myMainWindow->setVisible (true);
  19370. }
  19371. void shutdown()
  19372. {
  19373. delete myMainWindow;
  19374. }
  19375. const String getApplicationName()
  19376. {
  19377. return T("Super JUCE-o-matic");
  19378. }
  19379. const String getApplicationVersion()
  19380. {
  19381. return T("1.0");
  19382. }
  19383. };
  19384. // this creates wrapper code to actually launch the app properly.
  19385. START_JUCE_APPLICATION (MyJUCEApp)
  19386. @endcode
  19387. Because this object will be created before Juce has properly initialised, you must
  19388. NEVER add any member variable objects that will be automatically constructed. Likewise
  19389. don't put ANY code in the constructor that could call Juce functions. Any objects that
  19390. you want to add to the class must be pointers, which you should instantiate during the
  19391. initialise() method, and delete in the shutdown() method.
  19392. @see MessageManager, DeletedAtShutdown
  19393. */
  19394. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  19395. private ActionListener
  19396. {
  19397. protected:
  19398. /** Constructs a JUCE app object.
  19399. If subclasses implement a constructor or destructor, they shouldn't call any
  19400. JUCE code in there - put your startup/shutdown code in initialise() and
  19401. shutdown() instead.
  19402. */
  19403. JUCEApplication();
  19404. public:
  19405. /** Destructor.
  19406. If subclasses implement a constructor or destructor, they shouldn't call any
  19407. JUCE code in there - put your startup/shutdown code in initialise() and
  19408. shutdown() instead.
  19409. */
  19410. virtual ~JUCEApplication();
  19411. /** Returns the global instance of the application object being run. */
  19412. static JUCEApplication* getInstance() throw();
  19413. /** Called when the application starts.
  19414. This will be called once to let the application do whatever initialisation
  19415. it needs, create its windows, etc.
  19416. After the method returns, the normal event-dispatch loop will be run,
  19417. until the quit() method is called, at which point the shutdown()
  19418. method will be called to let the application clear up anything it needs
  19419. to delete.
  19420. If during the initialise() method, the application decides not to start-up
  19421. after all, it can just call the quit() method and the event loop won't be run.
  19422. @param commandLineParameters the line passed in does not include the
  19423. name of the executable, just the parameter list.
  19424. @see shutdown, quit
  19425. */
  19426. virtual void initialise (const String& commandLineParameters) = 0;
  19427. /** Returns true if the application hasn't yet completed its initialise() method
  19428. and entered the main event loop.
  19429. This is handy for things like splash screens to know when the app's up-and-running
  19430. properly.
  19431. */
  19432. bool isInitialising() const throw();
  19433. /* Called to allow the application to clear up before exiting.
  19434. After JUCEApplication::quit() has been called, the event-dispatch loop will
  19435. terminate, and this method will get called to allow the app to sort itself
  19436. out.
  19437. Be careful that nothing happens in this method that might rely on messages
  19438. being sent, or any kind of window activity, because the message loop is no
  19439. longer running at this point.
  19440. @see DeletedAtShutdown
  19441. */
  19442. virtual void shutdown() = 0;
  19443. /** Returns the application's name.
  19444. An application must implement this to name itself.
  19445. */
  19446. virtual const String getApplicationName() = 0;
  19447. /** Returns the application's version number.
  19448. An application can implement this to give itself a version.
  19449. (The default implementation of this just returns an empty string).
  19450. */
  19451. virtual const String getApplicationVersion();
  19452. /** Checks whether multiple instances of the app are allowed.
  19453. If you application class returns true for this, more than one instance is
  19454. permitted to run (except on the Mac where this isn't possible).
  19455. If it's false, the second instance won't start, but it you will still get a
  19456. callback to anotherInstanceStarted() to tell you about this - which
  19457. gives you a chance to react to what the user was trying to do.
  19458. */
  19459. virtual bool moreThanOneInstanceAllowed();
  19460. /** Indicates that the user has tried to start up another instance of the app.
  19461. This will get called even if moreThanOneInstanceAllowed() is false.
  19462. */
  19463. virtual void anotherInstanceStarted (const String& commandLine);
  19464. /** Called when the operating system is trying to close the application.
  19465. The default implementation of this method is to call quit(), but it may
  19466. be overloaded to ignore the request or do some other special behaviour
  19467. instead. For example, you might want to offer the user the chance to save
  19468. their changes before quitting, and give them the chance to cancel.
  19469. If you want to send a quit signal to your app, this is the correct method
  19470. to call, because it means that requests that come from the system get handled
  19471. in the same way as those from your own application code. So e.g. you'd
  19472. call this method from a "quit" item on a menu bar.
  19473. */
  19474. virtual void systemRequestedQuit();
  19475. /** If any unhandled exceptions make it through to the message dispatch loop, this
  19476. callback will be triggered, in case you want to log them or do some other
  19477. type of error-handling.
  19478. If the type of exception is derived from the std::exception class, the pointer
  19479. passed-in will be valid. If the exception is of unknown type, this pointer
  19480. will be null.
  19481. */
  19482. virtual void unhandledException (const std::exception* e,
  19483. const String& sourceFilename,
  19484. const int lineNumber);
  19485. /** Signals that the main message loop should stop and the application should terminate.
  19486. This isn't synchronous, it just posts a quit message to the main queue, and
  19487. when this message arrives, the message loop will stop, the shutdown() method
  19488. will be called, and the app will exit.
  19489. Note that this will cause an unconditional quit to happen, so if you need an
  19490. extra level before this, e.g. to give the user the chance to save their work
  19491. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  19492. method - see that method's help for more info.
  19493. @see MessageManager, DeletedAtShutdown
  19494. */
  19495. static void quit();
  19496. /** Sets the value that should be returned as the application's exit code when the
  19497. app quits.
  19498. This is the value that's returned by the main() function. Normally you'd leave this
  19499. as 0 unless you want to indicate an error code.
  19500. @see getApplicationReturnValue
  19501. */
  19502. void setApplicationReturnValue (const int newReturnValue) throw();
  19503. /** Returns the value that has been set as the application's exit code.
  19504. @see setApplicationReturnValue
  19505. */
  19506. int getApplicationReturnValue() const throw() { return appReturnValue; }
  19507. /** Returns the application's command line params.
  19508. */
  19509. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  19510. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  19511. /** @internal */
  19512. static int main (String& commandLine, JUCEApplication* const newApp);
  19513. /** @internal */
  19514. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  19515. /** @internal */
  19516. static void sendUnhandledException (const std::exception* const e,
  19517. const char* const sourceFile,
  19518. const int lineNumber);
  19519. /** @internal */
  19520. ApplicationCommandTarget* getNextCommandTarget();
  19521. /** @internal */
  19522. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  19523. /** @internal */
  19524. void getAllCommands (Array <CommandID>& commands);
  19525. /** @internal */
  19526. bool perform (const InvocationInfo& info);
  19527. /** @internal */
  19528. void actionListenerCallback (const String& message);
  19529. private:
  19530. String commandLineParameters;
  19531. int appReturnValue;
  19532. bool stillInitialising;
  19533. InterProcessLock* appLock;
  19534. JUCEApplication (const JUCEApplication&);
  19535. const JUCEApplication& operator= (const JUCEApplication&);
  19536. public:
  19537. /** @internal */
  19538. bool initialiseApp (String& commandLine);
  19539. /** @internal */
  19540. static int shutdownAppAndClearUp();
  19541. };
  19542. #endif // __JUCE_APPLICATION_JUCEHEADER__
  19543. /********* End of inlined file: juce_Application.h *********/
  19544. #endif
  19545. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  19546. #endif
  19547. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  19548. #endif
  19549. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19550. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  19551. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19552. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19553. /********* Start of inlined file: juce_Desktop.h *********/
  19554. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  19555. #define __JUCE_DESKTOP_JUCEHEADER__
  19556. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  19557. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19558. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19559. /**
  19560. Classes derived from this will be automatically deleted when the application exits.
  19561. After JUCEApplication::shutdown() has been called, any objects derived from
  19562. DeletedAtShutdown which are still in existence will be deleted in the reverse
  19563. order to that in which they were created.
  19564. So if you've got a singleton and don't want to have to explicitly delete it, just
  19565. inherit from this and it'll be taken care of.
  19566. */
  19567. class JUCE_API DeletedAtShutdown
  19568. {
  19569. protected:
  19570. /** Creates a DeletedAtShutdown object. */
  19571. DeletedAtShutdown();
  19572. /** Destructor.
  19573. It's ok to delete these objects explicitly - it's only the ones left
  19574. dangling at the end that will be deleted automatically.
  19575. */
  19576. virtual ~DeletedAtShutdown();
  19577. public:
  19578. /** Deletes all extant objects.
  19579. This shouldn't be used by applications, as it's called automatically
  19580. in the shutdown code of the JUCEApplication class.
  19581. */
  19582. static void deleteAll();
  19583. private:
  19584. DeletedAtShutdown (const DeletedAtShutdown&);
  19585. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  19586. };
  19587. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19588. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  19589. /********* Start of inlined file: juce_Timer.h *********/
  19590. #ifndef __JUCE_TIMER_JUCEHEADER__
  19591. #define __JUCE_TIMER_JUCEHEADER__
  19592. class InternalTimerThread;
  19593. /**
  19594. Repeatedly calls a user-defined method at a specified time interval.
  19595. A Timer's timerCallback() method will be repeatedly called at a given
  19596. interval. Initially when a Timer object is created, they will do nothing
  19597. until the startTimer() method is called, then the message thread will
  19598. start calling it back until stopTimer() is called.
  19599. The time interval isn't guaranteed to be precise to any more than maybe
  19600. 10-20ms, and the intervals may end up being much longer than requested if the
  19601. system is busy. Because it's the message thread that is doing the callbacks,
  19602. any messages that take a significant amount of time to process will block
  19603. all the timers for that period.
  19604. If you need to have a single callback that is shared by multiple timers with
  19605. different frequencies, then the MultiTimer class allows you to do that - its
  19606. structure is very similar to the Timer class, but contains multiple timers
  19607. internally, each one identified by an ID number.
  19608. @see MultiTimer
  19609. */
  19610. class JUCE_API Timer
  19611. {
  19612. protected:
  19613. /** Creates a Timer.
  19614. When created, the timer is stopped, so use startTimer() to get it going.
  19615. */
  19616. Timer() throw();
  19617. /** Creates a copy of another timer.
  19618. Note that this timer won't be started, even if the one you're copying
  19619. is running.
  19620. */
  19621. Timer (const Timer& other) throw();
  19622. public:
  19623. /** Destructor. */
  19624. virtual ~Timer();
  19625. /** The user-defined callback routine that actually gets called periodically.
  19626. It's perfectly ok to call startTimer() or stopTimer() from within this
  19627. callback to change the subsequent intervals.
  19628. */
  19629. virtual void timerCallback() = 0;
  19630. /** Starts the timer and sets the length of interval required.
  19631. If the timer is already started, this will reset it, so the
  19632. time between calling this method and the next timer callback
  19633. will not be less than the interval length passed in.
  19634. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  19635. rounded up to 1)
  19636. */
  19637. void startTimer (const int intervalInMilliseconds) throw();
  19638. /** Stops the timer.
  19639. No more callbacks will be made after this method returns.
  19640. If this is called from a different thread, any callbacks that may
  19641. be currently executing may be allowed to finish before the method
  19642. returns.
  19643. */
  19644. void stopTimer() throw();
  19645. /** Checks if the timer has been started.
  19646. @returns true if the timer is running.
  19647. */
  19648. bool isTimerRunning() const throw() { return periodMs > 0; }
  19649. /** Returns the timer's interval.
  19650. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  19651. */
  19652. int getTimerInterval() const throw() { return periodMs; }
  19653. private:
  19654. friend class InternalTimerThread;
  19655. int countdownMs, periodMs;
  19656. Timer* previous;
  19657. Timer* next;
  19658. const Timer& operator= (const Timer&);
  19659. };
  19660. #endif // __JUCE_TIMER_JUCEHEADER__
  19661. /********* End of inlined file: juce_Timer.h *********/
  19662. /**
  19663. Classes can implement this interface and register themselves with the Desktop class
  19664. to receive callbacks when the currently focused component changes.
  19665. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  19666. */
  19667. class JUCE_API FocusChangeListener
  19668. {
  19669. public:
  19670. /** Destructor. */
  19671. virtual ~FocusChangeListener() {}
  19672. /** Callback to indicate that the currently focused component has changed. */
  19673. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  19674. };
  19675. /**
  19676. Describes and controls aspects of the computer's desktop.
  19677. */
  19678. class JUCE_API Desktop : private DeletedAtShutdown,
  19679. private Timer,
  19680. private AsyncUpdater
  19681. {
  19682. public:
  19683. /** There's only one dektop object, and this method will return it.
  19684. */
  19685. static Desktop& JUCE_CALLTYPE getInstance() throw();
  19686. /** Returns a list of the positions of all the monitors available.
  19687. The first rectangle in the list will be the main monitor area.
  19688. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19689. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19690. */
  19691. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  19692. /** Returns the position and size of the main monitor.
  19693. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19694. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19695. */
  19696. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  19697. /** Returns the position and size of the monitor which contains this co-ordinate.
  19698. If none of the monitors contains the point, this will just return the
  19699. main monitor.
  19700. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19701. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19702. */
  19703. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  19704. /** Returns the mouse position.
  19705. The co-ordinates are relative to the top-left of the main monitor.
  19706. */
  19707. static void getMousePosition (int& x, int& y) throw();
  19708. /** Makes the mouse pointer jump to a given location.
  19709. The co-ordinates are relative to the top-left of the main monitor.
  19710. */
  19711. static void setMousePosition (int x, int y) throw();
  19712. /** Returns the last position at which a mouse button was pressed.
  19713. */
  19714. static void getLastMouseDownPosition (int& x, int& y) throw();
  19715. /** Returns the number of times the mouse button has been clicked since the
  19716. app started.
  19717. Each mouse-down event increments this number by 1.
  19718. */
  19719. static int getMouseButtonClickCounter() throw();
  19720. /** This lets you prevent the screensaver from becoming active.
  19721. Handy if you're running some sort of presentation app where having a screensaver
  19722. appear would be annoying.
  19723. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  19724. won't enable a screensaver unless the user has actually set one up).
  19725. The disablement will only happen while the Juce application is the foreground
  19726. process - if another task is running in front of it, then the screensaver will
  19727. be unaffected.
  19728. @see isScreenSaverEnabled
  19729. */
  19730. static void setScreenSaverEnabled (const bool isEnabled) throw();
  19731. /** Returns true if the screensaver has not been turned off.
  19732. This will return the last value passed into setScreenSaverEnabled(). Note that
  19733. it won't tell you whether the user is actually using a screen saver, just
  19734. whether this app is deliberately preventing one from running.
  19735. @see setScreenSaverEnabled
  19736. */
  19737. static bool isScreenSaverEnabled() throw();
  19738. /** Registers a MouseListener that will receive all mouse events that occur on
  19739. any component.
  19740. @see removeGlobalMouseListener
  19741. */
  19742. void addGlobalMouseListener (MouseListener* const listener) throw();
  19743. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  19744. method.
  19745. @see addGlobalMouseListener
  19746. */
  19747. void removeGlobalMouseListener (MouseListener* const listener) throw();
  19748. /** Registers a MouseListener that will receive a callback whenever the focused
  19749. component changes.
  19750. */
  19751. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  19752. /** Unregisters a listener that was added with addFocusChangeListener(). */
  19753. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  19754. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  19755. The component must already be on the desktop for this method to work. It will
  19756. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  19757. etc will be hidden.
  19758. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  19759. the component that's currently being used will be resized back to the size
  19760. and position it was in before being put into this mode.
  19761. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  19762. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  19763. to hide as much on-screen paraphenalia as possible.
  19764. */
  19765. void setKioskModeComponent (Component* componentToUse,
  19766. const bool allowMenusAndBars = true);
  19767. /** Returns the component that is currently being used in kiosk-mode.
  19768. This is the component that was last set by setKioskModeComponent(). If none
  19769. has been set, this returns 0.
  19770. */
  19771. Component* getKioskModeComponent() const { return kioskModeComponent; }
  19772. /** Returns the number of components that are currently active as top-level
  19773. desktop windows.
  19774. @see getComponent, Component::addToDesktop
  19775. */
  19776. int getNumComponents() const throw();
  19777. /** Returns one of the top-level desktop window components.
  19778. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  19779. index is out-of-range.
  19780. @see getNumComponents, Component::addToDesktop
  19781. */
  19782. Component* getComponent (const int index) const throw();
  19783. /** Finds the component at a given screen location.
  19784. This will drill down into top-level windows to find the child component at
  19785. the given position.
  19786. Returns 0 if the co-ordinates are inside a non-Juce window.
  19787. */
  19788. Component* findComponentAt (const int screenX,
  19789. const int screenY) const;
  19790. juce_UseDebuggingNewOperator
  19791. /** Tells this object to refresh its idea of what the screen resolution is.
  19792. (Called internally by the native code).
  19793. */
  19794. void refreshMonitorSizes() throw();
  19795. /** True if the OS supports semitransparent windows */
  19796. static bool canUseSemiTransparentWindows() throw();
  19797. private:
  19798. friend class Component;
  19799. friend class ComponentPeer;
  19800. SortedSet <void*> mouseListeners, focusListeners;
  19801. VoidArray desktopComponents;
  19802. friend class DeletedAtShutdown;
  19803. friend class TopLevelWindowManager;
  19804. Desktop() throw();
  19805. ~Desktop() throw();
  19806. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  19807. int lastMouseX, lastMouseY;
  19808. Component* kioskModeComponent;
  19809. Rectangle kioskComponentOriginalBounds;
  19810. void timerCallback();
  19811. void sendMouseMove();
  19812. void resetTimer() throw();
  19813. int getNumDisplayMonitors() const throw();
  19814. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  19815. void addDesktopComponent (Component* const c) throw();
  19816. void removeDesktopComponent (Component* const c) throw();
  19817. void componentBroughtToFront (Component* const c) throw();
  19818. void triggerFocusCallback() throw();
  19819. void handleAsyncUpdate();
  19820. Desktop (const Desktop&);
  19821. const Desktop& operator= (const Desktop&);
  19822. };
  19823. #endif // __JUCE_DESKTOP_JUCEHEADER__
  19824. /********* End of inlined file: juce_Desktop.h *********/
  19825. class KeyPressMappingSet;
  19826. class ApplicationCommandManagerListener;
  19827. /**
  19828. One of these objects holds a list of all the commands your app can perform,
  19829. and despatches these commands when needed.
  19830. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  19831. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  19832. to invoke automatically, which means you don't have to handle the result of a menu
  19833. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  19834. which can choose which events they want to handle.
  19835. This architecture also allows for nested ApplicationCommandTargets, so that for example
  19836. you could have two different objects, one inside the other, both of which can respond to
  19837. a "delete" command. Depending on which one has focus, the command will be sent to the
  19838. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  19839. method.
  19840. To set up your app to use commands, you'll need to do the following:
  19841. - Create a global ApplicationCommandManager to hold the list of all possible
  19842. commands. (This will also manage a set of key-mappings for them).
  19843. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  19844. This allows the object to provide a list of commands that it can perform, and
  19845. to handle them.
  19846. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  19847. or ApplicationCommandManager::registerCommand().
  19848. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  19849. method to access the key-mapper object, which you will need to register as a key-listener
  19850. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  19851. about setting this up.
  19852. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  19853. cause these commands to be invoked automatically.
  19854. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  19855. When a command is invoked, the ApplicationCommandManager will try to choose the best
  19856. ApplicationCommandTarget to receive the specified command. To do this it will use the
  19857. current keyboard focus to see which component might be interested, and will search the
  19858. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  19859. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  19860. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  19861. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  19862. point if the command still hasn't been performed, it will be passed to the current
  19863. JUCEApplication object (which is itself an ApplicationCommandTarget).
  19864. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  19865. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  19866. the object yourself.
  19867. @see ApplicationCommandTarget, ApplicationCommandInfo
  19868. */
  19869. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  19870. private FocusChangeListener
  19871. {
  19872. public:
  19873. /** Creates an ApplicationCommandManager.
  19874. Once created, you'll need to register all your app's commands with it, using
  19875. ApplicationCommandManager::registerAllCommandsForTarget() or
  19876. ApplicationCommandManager::registerCommand().
  19877. */
  19878. ApplicationCommandManager();
  19879. /** Destructor.
  19880. Make sure that you don't delete this if pointers to it are still being used by
  19881. objects such as PopupMenus or Buttons.
  19882. */
  19883. virtual ~ApplicationCommandManager();
  19884. /** Clears the current list of all commands.
  19885. Note that this will also clear the contents of the KeyPressMappingSet.
  19886. */
  19887. void clearCommands();
  19888. /** Adds a command to the list of registered commands.
  19889. @see registerAllCommandsForTarget
  19890. */
  19891. void registerCommand (const ApplicationCommandInfo& newCommand);
  19892. /** Adds all the commands that this target publishes to the manager's list.
  19893. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  19894. to get details about all the commands that this target can do, and will call
  19895. registerCommand() to add each one to the manger's list.
  19896. @see registerCommand
  19897. */
  19898. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  19899. /** Removes the command with a specified ID.
  19900. Note that this will also remove any key mappings that are mapped to the command.
  19901. */
  19902. void removeCommand (const CommandID commandID);
  19903. /** This should be called to tell the manager that one of its registered commands may have changed
  19904. its active status.
  19905. Because the command manager only finds out whether a command is active or inactive by querying
  19906. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  19907. allows things like buttons to update their enablement, etc.
  19908. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  19909. for any registered listeners.
  19910. */
  19911. void commandStatusChanged();
  19912. /** Returns the number of commands that have been registered.
  19913. @see registerCommand
  19914. */
  19915. int getNumCommands() const throw() { return commands.size(); }
  19916. /** Returns the details about one of the registered commands.
  19917. The index is between 0 and (getNumCommands() - 1).
  19918. */
  19919. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  19920. /** Returns the details about a given command ID.
  19921. This will search the list of registered commands for one with the given command
  19922. ID number, and return its associated info. If no matching command is found, this
  19923. will return 0.
  19924. */
  19925. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  19926. /** Returns the name field for a command.
  19927. An empty string is returned if no command with this ID has been registered.
  19928. @see getDescriptionOfCommand
  19929. */
  19930. const String getNameOfCommand (const CommandID commandID) const throw();
  19931. /** Returns the description field for a command.
  19932. An empty string is returned if no command with this ID has been registered. If the
  19933. command has no description, this will return its short name field instead.
  19934. @see getNameOfCommand
  19935. */
  19936. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  19937. /** Returns the list of categories.
  19938. This will go through all registered commands, and return a list of all the distict
  19939. categoryName values from their ApplicationCommandInfo structure.
  19940. @see getCommandsInCategory()
  19941. */
  19942. const StringArray getCommandCategories() const throw();
  19943. /** Returns a list of all the command UIDs in a particular category.
  19944. @see getCommandCategories()
  19945. */
  19946. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  19947. /** Returns the manager's internal set of key mappings.
  19948. This object can be used to edit the keypresses. To actually link this object up
  19949. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  19950. class.
  19951. @see KeyPressMappingSet
  19952. */
  19953. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  19954. /** Invokes the given command directly, sending it to the default target.
  19955. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  19956. structure.
  19957. */
  19958. bool invokeDirectly (const CommandID commandID,
  19959. const bool asynchronously);
  19960. /** Sends a command to the default target.
  19961. This will choose a target using getFirstCommandTarget(), and send the specified command
  19962. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  19963. first target can't handle the command, it will be passed on to targets further down the
  19964. chain (see ApplicationCommandTarget::invoke() for more info).
  19965. @param invocationInfo this must be correctly filled-in, describing the context for
  19966. the invocation.
  19967. @param asynchronously if false, the command will be performed before this method returns.
  19968. If true, a message will be posted so that the command will be performed
  19969. later on the message thread, and this method will return immediately.
  19970. @see ApplicationCommandTarget::invoke
  19971. */
  19972. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  19973. const bool asynchronously);
  19974. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  19975. Whenever the manager needs to know which target a command should be sent to, it calls
  19976. this method to determine the first one to try.
  19977. By default, this method will return the target that was set by calling setFirstCommandTarget().
  19978. If no target is set, it will return the result of findDefaultComponentTarget().
  19979. If you need to make sure all commands go via your own custom target, then you can
  19980. either use setFirstCommandTarget() to specify a single target, or override this method
  19981. if you need more complex logic to choose one.
  19982. It may return 0 if no targets are available.
  19983. @see getTargetForCommand, invoke, invokeDirectly
  19984. */
  19985. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  19986. /** Sets a target to be returned by getFirstCommandTarget().
  19987. If this is set to 0, then getFirstCommandTarget() will by default return the
  19988. result of findDefaultComponentTarget().
  19989. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  19990. deleting the target object.
  19991. */
  19992. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  19993. /** Tries to find the best target to use to perform a given command.
  19994. This will call getFirstCommandTarget() to find the preferred target, and will
  19995. check whether that target can handle the given command. If it can't, then it'll use
  19996. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  19997. so on until no more are available.
  19998. If no targets are found that can perform the command, this method will return 0.
  19999. If a target is found, then it will get the target to fill-in the upToDateInfo
  20000. structure with the latest info about that command, so that the caller can see
  20001. whether the command is disabled, ticked, etc.
  20002. */
  20003. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  20004. ApplicationCommandInfo& upToDateInfo);
  20005. /** Registers a listener that will be called when various events occur. */
  20006. void addListener (ApplicationCommandManagerListener* const listener) throw();
  20007. /** Deregisters a previously-added listener. */
  20008. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  20009. /** Looks for a suitable command target based on which Components have the keyboard focus.
  20010. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  20011. but is exposed here in case it's useful.
  20012. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  20013. windows, etc., and using the findTargetForComponent() method.
  20014. */
  20015. static ApplicationCommandTarget* findDefaultComponentTarget();
  20016. /** Examines this component and all its parents in turn, looking for the first one
  20017. which is a ApplicationCommandTarget.
  20018. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  20019. that class.
  20020. */
  20021. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  20022. juce_UseDebuggingNewOperator
  20023. private:
  20024. OwnedArray <ApplicationCommandInfo> commands;
  20025. SortedSet <void*> listeners;
  20026. ScopedPointer <KeyPressMappingSet> keyMappings;
  20027. ApplicationCommandTarget* firstTarget;
  20028. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  20029. void handleAsyncUpdate();
  20030. void globalFocusChanged (Component*);
  20031. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  20032. // version of this method.
  20033. virtual short getFirstCommandTarget() { return 0; }
  20034. };
  20035. /**
  20036. A listener that receives callbacks from an ApplicationCommandManager when
  20037. commands are invoked or the command list is changed.
  20038. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  20039. */
  20040. class JUCE_API ApplicationCommandManagerListener
  20041. {
  20042. public:
  20043. /** Destructor. */
  20044. virtual ~ApplicationCommandManagerListener() {}
  20045. /** Called when an app command is about to be invoked. */
  20046. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  20047. /** Called when commands are registered or deregistered from the
  20048. command manager, or when commands are made active or inactive.
  20049. Note that if you're using this to watch for changes to whether a command is disabled,
  20050. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  20051. whenever the status of your command might have changed.
  20052. */
  20053. virtual void applicationCommandListChanged() = 0;
  20054. };
  20055. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20056. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  20057. #endif
  20058. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  20059. #endif
  20060. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  20061. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  20062. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  20063. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  20064. /********* Start of inlined file: juce_PropertiesFile.h *********/
  20065. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  20066. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  20067. /** Wrapper on a file that stores a list of key/value data pairs.
  20068. Useful for storing application settings, etc. See the PropertySet class for
  20069. the interfaces that read and write values.
  20070. Not designed for very large amounts of data, as it keeps all the values in
  20071. memory and writes them out to disk lazily when they are changed.
  20072. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  20073. with it, and these will be signalled when a value changes.
  20074. @see PropertySet
  20075. */
  20076. class JUCE_API PropertiesFile : public PropertySet,
  20077. public ChangeBroadcaster,
  20078. private Timer
  20079. {
  20080. public:
  20081. enum FileFormatOptions
  20082. {
  20083. ignoreCaseOfKeyNames = 1,
  20084. storeAsBinary = 2,
  20085. storeAsCompressedBinary = 4,
  20086. storeAsXML = 8
  20087. };
  20088. /**
  20089. Creates a PropertiesFile object.
  20090. @param file the file to use
  20091. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  20092. is changed, the object will wait for this amount
  20093. of time and then save the file. If zero, the file
  20094. will be written to disk immediately on being changed
  20095. (which might be slow, as it'll re-write synchronously
  20096. each time a value-change method is called). If it is
  20097. less than zero, the file won't be saved until
  20098. save() or saveIfNeeded() are explicitly called.
  20099. @param options a combination of the flags in the FileFormatOptions
  20100. enum, which specify the type of file to save, and other
  20101. options.
  20102. */
  20103. PropertiesFile (const File& file,
  20104. const int millisecondsBeforeSaving,
  20105. const int options);
  20106. /** Destructor.
  20107. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  20108. */
  20109. ~PropertiesFile();
  20110. /** This will flush all the values to disk if they've changed since the last
  20111. time they were saved.
  20112. Returns false if it fails to write to the file for some reason (maybe because
  20113. it's read-only or the directory doesn't exist or something).
  20114. @see save
  20115. */
  20116. bool saveIfNeeded();
  20117. /** This will force a write-to-disk of the current values, regardless of whether
  20118. anything has changed since the last save.
  20119. Returns false if it fails to write to the file for some reason (maybe because
  20120. it's read-only or the directory doesn't exist or something).
  20121. @see saveIfNeeded
  20122. */
  20123. bool save();
  20124. /** Returns true if the properties have been altered since the last time they were
  20125. saved.
  20126. */
  20127. bool needsToBeSaved() const;
  20128. /** Returns the file that's being used. */
  20129. const File getFile() const { return file; }
  20130. /** Handy utility to create a properties file in whatever the standard OS-specific
  20131. location is for these things.
  20132. This uses getDefaultAppSettingsFile() to decide what file to create, then
  20133. creates a PropertiesFile object with the specified properties. See
  20134. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  20135. what the parameters do.
  20136. @see getDefaultAppSettingsFile
  20137. */
  20138. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  20139. const String& fileNameSuffix,
  20140. const String& folderName,
  20141. const bool commonToAllUsers,
  20142. const int millisecondsBeforeSaving,
  20143. const int propertiesFileOptions);
  20144. /** Handy utility to choose a file in the standard OS-dependent location for application
  20145. settings files.
  20146. So on a Mac, this will return a file called:
  20147. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  20148. On Windows it'll return something like:
  20149. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  20150. On Linux it'll return
  20151. ~/.[folderName]/[applicationName].[fileNameSuffix]
  20152. If you pass an empty string as the folder name, it'll use the app name for this (or
  20153. omit the folder name on the Mac).
  20154. If commonToAllUsers is true, then this will return the same file for all users of the
  20155. computer, regardless of the current user. If it is false, the file will be specific to
  20156. only the current user. Use this to choose whether you're saving settings that are common
  20157. or user-specific.
  20158. */
  20159. static const File getDefaultAppSettingsFile (const String& applicationName,
  20160. const String& fileNameSuffix,
  20161. const String& folderName,
  20162. const bool commonToAllUsers);
  20163. juce_UseDebuggingNewOperator
  20164. protected:
  20165. virtual void propertyChanged();
  20166. private:
  20167. File file;
  20168. int timerInterval;
  20169. const int options;
  20170. bool needsWriting;
  20171. void timerCallback();
  20172. PropertiesFile (const PropertiesFile&);
  20173. const PropertiesFile& operator= (const PropertiesFile&);
  20174. };
  20175. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  20176. /********* End of inlined file: juce_PropertiesFile.h *********/
  20177. /**
  20178. Manages a collection of properties.
  20179. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  20180. as a singleton.
  20181. It holds two different PropertiesFile objects internally, one for user-specific
  20182. settings (stored in your user directory), and one for settings that are common to
  20183. all users (stored in a folder accessible to all users).
  20184. The class manages the creation of these files on-demand, allowing access via the
  20185. getUserSettings() and getCommonSettings() methods. It also has a few handy
  20186. methods like testWriteAccess() to check that the files can be saved.
  20187. If you're using one of these as a singleton, then your app's start-up code should
  20188. first of all call setStorageParameters() to tell it the parameters to use to create
  20189. the properties files.
  20190. @see PropertiesFile
  20191. */
  20192. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  20193. {
  20194. public:
  20195. /**
  20196. Creates an ApplicationProperties object.
  20197. Before using it, you must call setStorageParameters() to give it the info
  20198. it needs to create the property files.
  20199. */
  20200. ApplicationProperties() throw();
  20201. /** Destructor.
  20202. */
  20203. ~ApplicationProperties();
  20204. juce_DeclareSingleton (ApplicationProperties, false)
  20205. /** Gives the object the information it needs to create the appropriate properties files.
  20206. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  20207. info about how these parameters are used.
  20208. */
  20209. void setStorageParameters (const String& applicationName,
  20210. const String& fileNameSuffix,
  20211. const String& folderName,
  20212. const int millisecondsBeforeSaving,
  20213. const int propertiesFileOptions) throw();
  20214. /** Tests whether the files can be successfully written to, and can show
  20215. an error message if not.
  20216. Returns true if none of the tests fail.
  20217. @param testUserSettings if true, the user settings file will be tested
  20218. @param testCommonSettings if true, the common settings file will be tested
  20219. @param showWarningDialogOnFailure if true, the method will show a helpful error
  20220. message box if either of the tests fail
  20221. */
  20222. bool testWriteAccess (const bool testUserSettings,
  20223. const bool testCommonSettings,
  20224. const bool showWarningDialogOnFailure);
  20225. /** Returns the user settings file.
  20226. The first time this is called, it will create and load the properties file.
  20227. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  20228. the common settings are used as a second-chance place to look. This is done via the
  20229. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  20230. to the fallback for the user settings.
  20231. @see getCommonSettings
  20232. */
  20233. PropertiesFile* getUserSettings() throw();
  20234. /** Returns the common settings file.
  20235. The first time this is called, it will create and load the properties file.
  20236. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  20237. read-only (e.g. because the user doesn't have permission to write
  20238. to shared files), then this will return the user settings instead,
  20239. (like getUserSettings() would do). This is handy if you'd like to
  20240. write a value to the common settings, but if that's no possible,
  20241. then you'd rather write to the user settings than none at all.
  20242. If returnUserPropsIfReadOnly is false, this method will always return
  20243. the common settings, even if any changes to them can't be saved.
  20244. @see getUserSettings
  20245. */
  20246. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  20247. /** Saves both files if they need to be saved.
  20248. @see PropertiesFile::saveIfNeeded
  20249. */
  20250. bool saveIfNeeded();
  20251. /** Flushes and closes both files if they are open.
  20252. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  20253. and closes both files. They will then be re-opened the next time getUserSettings()
  20254. or getCommonSettings() is called.
  20255. */
  20256. void closeFiles();
  20257. juce_UseDebuggingNewOperator
  20258. private:
  20259. ScopedPointer <PropertiesFile> userProps, commonProps;
  20260. String appName, fileSuffix, folderName;
  20261. int msBeforeSaving, options;
  20262. int commonSettingsAreReadOnly;
  20263. ApplicationProperties (const ApplicationProperties&);
  20264. const ApplicationProperties& operator= (const ApplicationProperties&);
  20265. void openFiles() throw();
  20266. };
  20267. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  20268. /********* End of inlined file: juce_ApplicationProperties.h *********/
  20269. #endif
  20270. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20271. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  20272. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20273. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20274. /********* Start of inlined file: juce_AudioFormat.h *********/
  20275. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  20276. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  20277. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  20278. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  20279. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  20280. class AudioFormat;
  20281. /**
  20282. Reads samples from an audio file stream.
  20283. A subclass that reads a specific type of audio format will be created by
  20284. an AudioFormat object.
  20285. @see AudioFormat, AudioFormatWriter
  20286. */
  20287. class JUCE_API AudioFormatReader
  20288. {
  20289. protected:
  20290. /** Creates an AudioFormatReader object.
  20291. @param sourceStream the stream to read from - this will be deleted
  20292. by this object when it is no longer needed. (Some
  20293. specialised readers might not use this parameter and
  20294. can leave it as 0).
  20295. @param formatName the description that will be returned by the getFormatName()
  20296. method
  20297. */
  20298. AudioFormatReader (InputStream* const sourceStream,
  20299. const String& formatName);
  20300. public:
  20301. /** Destructor. */
  20302. virtual ~AudioFormatReader();
  20303. /** Returns a description of what type of format this is.
  20304. E.g. "AIFF"
  20305. */
  20306. const String getFormatName() const throw() { return formatName; }
  20307. /** Reads samples from the stream.
  20308. @param destSamples an array of buffers into which the sample data for each
  20309. channel will be written.
  20310. If the format is fixed-point, each channel will be written
  20311. as an array of 32-bit signed integers using the full
  20312. range -0x80000000 to 0x7fffffff, regardless of the source's
  20313. bit-depth. If it is a floating-point format, you should cast
  20314. the resulting array to a (float**) to get the values (in the
  20315. range -1.0 to 1.0 or beyond)
  20316. If the format is stereo, then destSamples[0] is the left channel
  20317. data, and destSamples[1] is the right channel.
  20318. The numDestChannels parameter indicates how many pointers this array
  20319. contains, but some of these pointers can be null if you don't want to
  20320. read data for some of the channels
  20321. @param numDestChannels the number of array elements in the destChannels array
  20322. @param startSampleInSource the position in the audio file or stream at which the samples
  20323. should be read, as a number of samples from the start of the
  20324. stream. It's ok for this to be beyond the start or end of the
  20325. available data - any samples that are out-of-range will be returned
  20326. as zeros.
  20327. @param numSamplesToRead the number of samples to read. If this is greater than the number
  20328. of samples that the file or stream contains. the result will be padded
  20329. with zeros
  20330. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  20331. for some of the channels that you pass in, then they should be filled with
  20332. copies of valid source channels.
  20333. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  20334. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  20335. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  20336. was false, then only the first channel would be filled with the file's contents, and
  20337. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  20338. from a stereo file, then the last 3 would all end up with copies of the same data.
  20339. @returns true if the operation succeeded, false if there was an error. Note
  20340. that reading sections of data beyond the extent of the stream isn't an
  20341. error - the reader should just return zeros for these regions
  20342. @see readMaxLevels
  20343. */
  20344. bool read (int** destSamples,
  20345. int numDestChannels,
  20346. int64 startSampleInSource,
  20347. int numSamplesToRead,
  20348. const bool fillLeftoverChannelsWithCopies);
  20349. /** Finds the highest and lowest sample levels from a section of the audio stream.
  20350. This will read a block of samples from the stream, and measure the
  20351. highest and lowest sample levels from the channels in that section, returning
  20352. these as normalised floating-point levels.
  20353. @param startSample the offset into the audio stream to start reading from. It's
  20354. ok for this to be beyond the start or end of the stream.
  20355. @param numSamples how many samples to read
  20356. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  20357. @param highestLeft on return, this is the highest absolute sample from the left channel
  20358. @param lowestRight on return, this is the lowest absolute sample from the right
  20359. channel (if there is one)
  20360. @param highestRight on return, this is the highest absolute sample from the right
  20361. channel (if there is one)
  20362. @see read
  20363. */
  20364. virtual void readMaxLevels (int64 startSample,
  20365. int64 numSamples,
  20366. float& lowestLeft,
  20367. float& highestLeft,
  20368. float& lowestRight,
  20369. float& highestRight);
  20370. /** Scans the source looking for a sample whose magnitude is in a specified range.
  20371. This will read from the source, either forwards or backwards between two sample
  20372. positions, until it finds a sample whose magnitude lies between two specified levels.
  20373. If it finds a suitable sample, it returns its position; if not, it will return -1.
  20374. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  20375. points when you're searching for a continuous range of samples
  20376. @param startSample the first sample to look at
  20377. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  20378. the search will go backwards
  20379. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  20380. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  20381. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  20382. of this many consecutive samples, all of which lie
  20383. within the target range. When it finds such a sequence,
  20384. it returns the position of the first in-range sample
  20385. it found (i.e. the earliest one if scanning forwards, the
  20386. latest one if scanning backwards)
  20387. */
  20388. int64 searchForLevel (int64 startSample,
  20389. int64 numSamplesToSearch,
  20390. const double magnitudeRangeMinimum,
  20391. const double magnitudeRangeMaximum,
  20392. const int minimumConsecutiveSamples);
  20393. /** The sample-rate of the stream. */
  20394. double sampleRate;
  20395. /** The number of bits per sample, e.g. 16, 24, 32. */
  20396. unsigned int bitsPerSample;
  20397. /** The total number of samples in the audio stream. */
  20398. int64 lengthInSamples;
  20399. /** The total number of channels in the audio stream. */
  20400. unsigned int numChannels;
  20401. /** Indicates whether the data is floating-point or fixed. */
  20402. bool usesFloatingPointData;
  20403. /** A set of metadata values that the reader has pulled out of the stream.
  20404. Exactly what these values are depends on the format, so you can
  20405. check out the format implementation code to see what kind of stuff
  20406. they understand.
  20407. */
  20408. StringPairArray metadataValues;
  20409. /** The input stream, for use by subclasses. */
  20410. InputStream* input;
  20411. /** Subclasses must implement this method to perform the low-level read operation.
  20412. Callers should use read() instead of calling this directly.
  20413. @param destSamples the array of destination buffers to fill. Some of these
  20414. pointers may be null
  20415. @param numDestChannels the number of items in the destSamples array. This
  20416. value is guaranteed not to be greater than the number of
  20417. channels that this reader object contains
  20418. @param startOffsetInDestBuffer the number of samples from the start of the
  20419. dest data at which to begin writing
  20420. @param startSampleInFile the number of samples into the source data at which
  20421. to begin reading. This value is guaranteed to be >= 0.
  20422. @param numSamples the number of samples to read
  20423. */
  20424. virtual bool readSamples (int** destSamples,
  20425. int numDestChannels,
  20426. int startOffsetInDestBuffer,
  20427. int64 startSampleInFile,
  20428. int numSamples) = 0;
  20429. juce_UseDebuggingNewOperator
  20430. private:
  20431. String formatName;
  20432. AudioFormatReader (const AudioFormatReader&);
  20433. const AudioFormatReader& operator= (const AudioFormatReader&);
  20434. };
  20435. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  20436. /********* End of inlined file: juce_AudioFormatReader.h *********/
  20437. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  20438. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  20439. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  20440. /********* Start of inlined file: juce_AudioSource.h *********/
  20441. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  20442. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  20443. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20444. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20445. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20446. class AudioFormatReader;
  20447. class AudioFormatWriter;
  20448. /**
  20449. A multi-channel buffer of 32-bit floating point audio samples.
  20450. */
  20451. class JUCE_API AudioSampleBuffer
  20452. {
  20453. public:
  20454. /** Creates a buffer with a specified number of channels and samples.
  20455. The contents of the buffer will initially be undefined, so use clear() to
  20456. set all the samples to zero.
  20457. The buffer will allocate its memory internally, and this will be released
  20458. when the buffer is deleted.
  20459. */
  20460. AudioSampleBuffer (const int numChannels,
  20461. const int numSamples) throw();
  20462. /** Creates a buffer using a pre-allocated block of memory.
  20463. Note that if the buffer is resized or its number of channels is changed, it
  20464. will re-allocate memory internally and copy the existing data to this new area,
  20465. so it will then stop directly addressing this memory.
  20466. @param dataToReferTo a pre-allocated array containing pointers to the data
  20467. for each channel that should be used by this buffer. The
  20468. buffer will only refer to this memory, it won't try to delete
  20469. it when the buffer is deleted or resized.
  20470. @param numChannels the number of channels to use - this must correspond to the
  20471. number of elements in the array passed in
  20472. @param numSamples the number of samples to use - this must correspond to the
  20473. size of the arrays passed in
  20474. */
  20475. AudioSampleBuffer (float** dataToReferTo,
  20476. const int numChannels,
  20477. const int numSamples) throw();
  20478. /** Copies another buffer.
  20479. This buffer will make its own copy of the other's data, unless the buffer was created
  20480. using an external data buffer, in which case boths buffers will just point to the same
  20481. shared block of data.
  20482. */
  20483. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20484. /** Copies another buffer onto this one.
  20485. This buffer's size will be changed to that of the other buffer.
  20486. */
  20487. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20488. /** Destructor.
  20489. This will free any memory allocated by the buffer.
  20490. */
  20491. virtual ~AudioSampleBuffer() throw();
  20492. /** Returns the number of channels of audio data that this buffer contains.
  20493. @see getSampleData
  20494. */
  20495. int getNumChannels() const throw() { return numChannels; }
  20496. /** Returns the number of samples allocated in each of the buffer's channels.
  20497. @see getSampleData
  20498. */
  20499. int getNumSamples() const throw() { return size; }
  20500. /** Returns a pointer one of the buffer's channels.
  20501. For speed, this doesn't check whether the channel number is out of range,
  20502. so be careful when using it!
  20503. */
  20504. float* getSampleData (const int channelNumber) const throw()
  20505. {
  20506. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20507. return channels [channelNumber];
  20508. }
  20509. /** Returns a pointer to a sample in one of the buffer's channels.
  20510. For speed, this doesn't check whether the channel and sample number
  20511. are out-of-range, so be careful when using it!
  20512. */
  20513. float* getSampleData (const int channelNumber,
  20514. const int sampleOffset) const throw()
  20515. {
  20516. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20517. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  20518. return channels [channelNumber] + sampleOffset;
  20519. }
  20520. /** Returns an array of pointers to the channels in the buffer.
  20521. Don't modify any of the pointers that are returned, and bear in mind that
  20522. these will become invalid if the buffer is resized.
  20523. */
  20524. float** getArrayOfChannels() const throw() { return channels; }
  20525. /** Chages the buffer's size or number of channels.
  20526. This can expand or contract the buffer's length, and add or remove channels.
  20527. If keepExistingContent is true, it will try to preserve as much of the
  20528. old data as it can in the new buffer.
  20529. If clearExtraSpace is true, then any extra channels or space that is
  20530. allocated will be also be cleared. If false, then this space is left
  20531. uninitialised.
  20532. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20533. amount of memory that is currently allocated (but it will still increase it if
  20534. the new size is bigger than the amount it currently has). If this is false, then
  20535. a new allocation will be done so that the buffer uses takes up the minimum amount
  20536. of memory that it needs.
  20537. */
  20538. void setSize (const int newNumChannels,
  20539. const int newNumSamples,
  20540. const bool keepExistingContent = false,
  20541. const bool clearExtraSpace = false,
  20542. const bool avoidReallocating = false) throw();
  20543. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20544. There's also a constructor that lets you specify arrays like this, but this
  20545. lets you change the channels dynamically.
  20546. Note that if the buffer is resized or its number of channels is changed, it
  20547. will re-allocate memory internally and copy the existing data to this new area,
  20548. so it will then stop directly addressing this memory.
  20549. @param dataToReferTo a pre-allocated array containing pointers to the data
  20550. for each channel that should be used by this buffer. The
  20551. buffer will only refer to this memory, it won't try to delete
  20552. it when the buffer is deleted or resized.
  20553. @param numChannels the number of channels to use - this must correspond to the
  20554. number of elements in the array passed in
  20555. @param numSamples the number of samples to use - this must correspond to the
  20556. size of the arrays passed in
  20557. */
  20558. void setDataToReferTo (float** dataToReferTo,
  20559. const int numChannels,
  20560. const int numSamples) throw();
  20561. /** Clears all the samples in all channels. */
  20562. void clear() throw();
  20563. /** Clears a specified region of all the channels.
  20564. For speed, this doesn't check whether the channel and sample number
  20565. are in-range, so be careful!
  20566. */
  20567. void clear (const int startSample,
  20568. const int numSamples) throw();
  20569. /** Clears a specified region of just one channel.
  20570. For speed, this doesn't check whether the channel and sample number
  20571. are in-range, so be careful!
  20572. */
  20573. void clear (const int channel,
  20574. const int startSample,
  20575. const int numSamples) throw();
  20576. /** Applies a gain multiple to a region of one channel.
  20577. For speed, this doesn't check whether the channel and sample number
  20578. are in-range, so be careful!
  20579. */
  20580. void applyGain (const int channel,
  20581. const int startSample,
  20582. int numSamples,
  20583. const float gain) throw();
  20584. /** Applies a gain multiple to a region of all the channels.
  20585. For speed, this doesn't check whether the sample numbers
  20586. are in-range, so be careful!
  20587. */
  20588. void applyGain (const int startSample,
  20589. const int numSamples,
  20590. const float gain) throw();
  20591. /** Applies a range of gains to a region of a channel.
  20592. The gain that is applied to each sample will vary from
  20593. startGain on the first sample to endGain on the last Sample,
  20594. so it can be used to do basic fades.
  20595. For speed, this doesn't check whether the sample numbers
  20596. are in-range, so be careful!
  20597. */
  20598. void applyGainRamp (const int channel,
  20599. const int startSample,
  20600. int numSamples,
  20601. float startGain,
  20602. float endGain) throw();
  20603. /** Adds samples from another buffer to this one.
  20604. @param destChannel the channel within this buffer to add the samples to
  20605. @param destStartSample the start sample within this buffer's channel
  20606. @param source the source buffer to add from
  20607. @param sourceChannel the channel within the source buffer to read from
  20608. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20609. @param numSamples the number of samples to process
  20610. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20611. added to this buffer's samples
  20612. @see copyFrom
  20613. */
  20614. void addFrom (const int destChannel,
  20615. const int destStartSample,
  20616. const AudioSampleBuffer& source,
  20617. const int sourceChannel,
  20618. const int sourceStartSample,
  20619. int numSamples,
  20620. const float gainToApplyToSource = 1.0f) throw();
  20621. /** Adds samples from an array of floats to one of the channels.
  20622. @param destChannel the channel within this buffer to add the samples to
  20623. @param destStartSample the start sample within this buffer's channel
  20624. @param source the source data to use
  20625. @param numSamples the number of samples to process
  20626. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20627. added to this buffer's samples
  20628. @see copyFrom
  20629. */
  20630. void addFrom (const int destChannel,
  20631. const int destStartSample,
  20632. const float* source,
  20633. int numSamples,
  20634. const float gainToApplyToSource = 1.0f) throw();
  20635. /** Adds samples from an array of floats, applying a gain ramp to them.
  20636. @param destChannel the channel within this buffer to add the samples to
  20637. @param destStartSample the start sample within this buffer's channel
  20638. @param source the source data to use
  20639. @param numSamples the number of samples to process
  20640. @param startGain the gain to apply to the first sample (this is multiplied with
  20641. the source samples before they are added to this buffer)
  20642. @param endGain the gain to apply to the final sample. The gain is linearly
  20643. interpolated between the first and last samples.
  20644. */
  20645. void addFromWithRamp (const int destChannel,
  20646. const int destStartSample,
  20647. const float* source,
  20648. int numSamples,
  20649. float startGain,
  20650. float endGain) throw();
  20651. /** Copies samples from another buffer to this one.
  20652. @param destChannel the channel within this buffer to copy the samples to
  20653. @param destStartSample the start sample within this buffer's channel
  20654. @param source the source buffer to read from
  20655. @param sourceChannel the channel within the source buffer to read from
  20656. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20657. @param numSamples the number of samples to process
  20658. @see addFrom
  20659. */
  20660. void copyFrom (const int destChannel,
  20661. const int destStartSample,
  20662. const AudioSampleBuffer& source,
  20663. const int sourceChannel,
  20664. const int sourceStartSample,
  20665. int numSamples) throw();
  20666. /** Copies samples from an array of floats into one of the channels.
  20667. @param destChannel the channel within this buffer to copy the samples to
  20668. @param destStartSample the start sample within this buffer's channel
  20669. @param source the source buffer to read from
  20670. @param numSamples the number of samples to process
  20671. @see addFrom
  20672. */
  20673. void copyFrom (const int destChannel,
  20674. const int destStartSample,
  20675. const float* source,
  20676. int numSamples) throw();
  20677. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20678. @param destChannel the channel within this buffer to copy the samples to
  20679. @param destStartSample the start sample within this buffer's channel
  20680. @param source the source buffer to read from
  20681. @param numSamples the number of samples to process
  20682. @param gain the gain to apply
  20683. @see addFrom
  20684. */
  20685. void copyFrom (const int destChannel,
  20686. const int destStartSample,
  20687. const float* source,
  20688. int numSamples,
  20689. const float gain) throw();
  20690. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20691. @param destChannel the channel within this buffer to copy the samples to
  20692. @param destStartSample the start sample within this buffer's channel
  20693. @param source the source buffer to read from
  20694. @param numSamples the number of samples to process
  20695. @param startGain the gain to apply to the first sample (this is multiplied with
  20696. the source samples before they are copied to this buffer)
  20697. @param endGain the gain to apply to the final sample. The gain is linearly
  20698. interpolated between the first and last samples.
  20699. @see addFrom
  20700. */
  20701. void copyFromWithRamp (const int destChannel,
  20702. const int destStartSample,
  20703. const float* source,
  20704. int numSamples,
  20705. float startGain,
  20706. float endGain) throw();
  20707. /** Finds the highest and lowest sample values in a given range.
  20708. @param channel the channel to read from
  20709. @param startSample the start sample within the channel
  20710. @param numSamples the number of samples to check
  20711. @param minVal on return, the lowest value that was found
  20712. @param maxVal on return, the highest value that was found
  20713. */
  20714. void findMinMax (const int channel,
  20715. const int startSample,
  20716. int numSamples,
  20717. float& minVal,
  20718. float& maxVal) const throw();
  20719. /** Finds the highest absolute sample value within a region of a channel.
  20720. */
  20721. float getMagnitude (const int channel,
  20722. const int startSample,
  20723. const int numSamples) const throw();
  20724. /** Finds the highest absolute sample value within a region on all channels.
  20725. */
  20726. float getMagnitude (const int startSample,
  20727. const int numSamples) const throw();
  20728. /** Returns the root mean squared level for a region of a channel.
  20729. */
  20730. float getRMSLevel (const int channel,
  20731. const int startSample,
  20732. const int numSamples) const throw();
  20733. /** Fills a section of the buffer using an AudioReader as its source.
  20734. This will convert the reader's fixed- or floating-point data to
  20735. the buffer's floating-point format, and will try to intelligently
  20736. cope with mismatches between the number of channels in the reader
  20737. and the buffer.
  20738. @see writeToAudioWriter
  20739. */
  20740. void readFromAudioReader (AudioFormatReader* reader,
  20741. const int startSample,
  20742. const int numSamples,
  20743. const int readerStartSample,
  20744. const bool useReaderLeftChan,
  20745. const bool useReaderRightChan) throw();
  20746. /** Writes a section of this buffer to an audio writer.
  20747. This saves you having to mess about with channels or floating/fixed
  20748. point conversion.
  20749. @see readFromAudioReader
  20750. */
  20751. void writeToAudioWriter (AudioFormatWriter* writer,
  20752. const int startSample,
  20753. const int numSamples) const throw();
  20754. juce_UseDebuggingNewOperator
  20755. private:
  20756. int numChannels, size, allocatedBytes;
  20757. float** channels;
  20758. HeapBlock <char> allocatedData;
  20759. float* preallocatedChannelSpace [32];
  20760. void allocateData();
  20761. void allocateChannels (float** const dataToReferTo);
  20762. };
  20763. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20764. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20765. /**
  20766. Used by AudioSource::getNextAudioBlock().
  20767. */
  20768. struct JUCE_API AudioSourceChannelInfo
  20769. {
  20770. /** The destination buffer to fill with audio data.
  20771. When the AudioSource::getNextAudioBlock() method is called, the active section
  20772. of this buffer should be filled with whatever output the source produces.
  20773. Only the samples specified by the startSample and numSamples members of this structure
  20774. should be affected by the call.
  20775. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  20776. method can be treated as the input if the source is performing some kind of filter operation,
  20777. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  20778. a handy way of doing this.
  20779. The number of channels in the buffer could be anything, so the AudioSource
  20780. must cope with this in whatever way is appropriate for its function.
  20781. */
  20782. AudioSampleBuffer* buffer;
  20783. /** The first sample in the buffer from which the callback is expected
  20784. to write data. */
  20785. int startSample;
  20786. /** The number of samples in the buffer which the callback is expected to
  20787. fill with data. */
  20788. int numSamples;
  20789. /** Convenient method to clear the buffer if the source is not producing any data. */
  20790. void clearActiveBufferRegion() const
  20791. {
  20792. if (buffer != 0)
  20793. buffer->clear (startSample, numSamples);
  20794. }
  20795. };
  20796. /**
  20797. Base class for objects that can produce a continuous stream of audio.
  20798. @see AudioFormatReaderSource, ResamplingAudioSource
  20799. */
  20800. class JUCE_API AudioSource
  20801. {
  20802. protected:
  20803. /** Creates an AudioSource. */
  20804. AudioSource() throw() {}
  20805. public:
  20806. /** Destructor. */
  20807. virtual ~AudioSource() {}
  20808. /** Tells the source to prepare for playing.
  20809. The source can use this opportunity to initialise anything it needs to.
  20810. Note that this method could be called more than once in succession without
  20811. a matching call to releaseResources(), so make sure your code is robust and
  20812. can handle that kind of situation.
  20813. @param samplesPerBlockExpected the number of samples that the source
  20814. will be expected to supply each time its
  20815. getNextAudioBlock() method is called. This
  20816. number may vary slightly, because it will be dependent
  20817. on audio hardware callbacks, and these aren't
  20818. guaranteed to always use a constant block size, so
  20819. the source should be able to cope with small variations.
  20820. @param sampleRate the sample rate that the output will be used at - this
  20821. is needed by sources such as tone generators.
  20822. @see releaseResources, getNextAudioBlock
  20823. */
  20824. virtual void prepareToPlay (int samplesPerBlockExpected,
  20825. double sampleRate) = 0;
  20826. /** Allows the source to release anything it no longer needs after playback has stopped.
  20827. This will be called when the source is no longer going to have its getNextAudioBlock()
  20828. method called, so it should release any spare memory, etc. that it might have
  20829. allocated during the prepareToPlay() call.
  20830. Note that there's no guarantee that prepareToPlay() will actually have been called before
  20831. releaseResources(), and it may be called more than once in succession, so make sure your
  20832. code is robust and doesn't make any assumptions about when it will be called.
  20833. @see prepareToPlay, getNextAudioBlock
  20834. */
  20835. virtual void releaseResources() = 0;
  20836. /** Called repeatedly to fetch subsequent blocks of audio data.
  20837. After calling the prepareToPlay() method, this callback will be made each
  20838. time the audio playback hardware (or whatever other destination the audio
  20839. data is going to) needs another block of data.
  20840. It will generally be called on a high-priority system thread, or possibly even
  20841. an interrupt, so be careful not to do too much work here, as that will cause
  20842. audio glitches!
  20843. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  20844. */
  20845. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  20846. };
  20847. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  20848. /********* End of inlined file: juce_AudioSource.h *********/
  20849. /**
  20850. Writes samples to an audio file stream.
  20851. A subclass that writes a specific type of audio format will be created by
  20852. an AudioFormat object.
  20853. After creating one of these with the AudioFormat::createWriterFor() method
  20854. you can call its write() method to store the samples, and then delete it.
  20855. @see AudioFormat, AudioFormatReader
  20856. */
  20857. class JUCE_API AudioFormatWriter
  20858. {
  20859. protected:
  20860. /** Creates an AudioFormatWriter object.
  20861. @param destStream the stream to write to - this will be deleted
  20862. by this object when it is no longer needed
  20863. @param formatName the description that will be returned by the getFormatName()
  20864. method
  20865. @param sampleRate the sample rate to use - the base class just stores
  20866. this value, it doesn't do anything with it
  20867. @param numberOfChannels the number of channels to write - the base class just stores
  20868. this value, it doesn't do anything with it
  20869. @param bitsPerSample the bit depth of the stream - the base class just stores
  20870. this value, it doesn't do anything with it
  20871. */
  20872. AudioFormatWriter (OutputStream* const destStream,
  20873. const String& formatName,
  20874. const double sampleRate,
  20875. const unsigned int numberOfChannels,
  20876. const unsigned int bitsPerSample);
  20877. public:
  20878. /** Destructor. */
  20879. virtual ~AudioFormatWriter();
  20880. /** Returns a description of what type of format this is.
  20881. E.g. "AIFF file"
  20882. */
  20883. const String getFormatName() const throw() { return formatName; }
  20884. /** Writes a set of samples to the audio stream.
  20885. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  20886. can use AudioSampleBuffer::writeToAudioWriter().
  20887. @param samplesToWrite an array of arrays containing the sample data for
  20888. each channel to write. This is a zero-terminated
  20889. array of arrays, and can contain a different number
  20890. of channels than the actual stream uses, and the
  20891. writer should do its best to cope with this.
  20892. If the format is fixed-point, each channel will be formatted
  20893. as an array of signed integers using the full 32-bit
  20894. range -0x80000000 to 0x7fffffff, regardless of the source's
  20895. bit-depth. If it is a floating-point format, you should treat
  20896. the arrays as arrays of floats, and just cast it to an (int**)
  20897. to pass it into the method.
  20898. @param numSamples the number of samples to write
  20899. */
  20900. virtual bool write (const int** samplesToWrite,
  20901. int numSamples) = 0;
  20902. /** Reads a section of samples from an AudioFormatReader, and writes these to
  20903. the output.
  20904. This will take care of any floating-point conversion that's required to convert
  20905. between the two formats. It won't deal with sample-rate conversion, though.
  20906. If numSamplesToRead < 0, it will write the entire length of the reader.
  20907. @returns false if it can't read or write properly during the operation
  20908. */
  20909. bool writeFromAudioReader (AudioFormatReader& reader,
  20910. int64 startSample,
  20911. int64 numSamplesToRead);
  20912. /** Reads some samples from an AudioSource, and writes these to the output.
  20913. The source must already have been initialised with the AudioSource::prepareToPlay() method
  20914. @param source the source to read from
  20915. @param numSamplesToRead total number of samples to read and write
  20916. @param samplesPerBlock the maximum number of samples to fetch from the source
  20917. @returns false if it can't read or write properly during the operation
  20918. */
  20919. bool writeFromAudioSource (AudioSource& source,
  20920. int numSamplesToRead,
  20921. const int samplesPerBlock = 2048);
  20922. /** Returns the sample rate being used. */
  20923. double getSampleRate() const throw() { return sampleRate; }
  20924. /** Returns the number of channels being written. */
  20925. int getNumChannels() const throw() { return numChannels; }
  20926. /** Returns the bit-depth of the data being written. */
  20927. int getBitsPerSample() const throw() { return bitsPerSample; }
  20928. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  20929. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  20930. juce_UseDebuggingNewOperator
  20931. protected:
  20932. /** The sample rate of the stream. */
  20933. double sampleRate;
  20934. /** The number of channels being written to the stream. */
  20935. unsigned int numChannels;
  20936. /** The bit depth of the file. */
  20937. unsigned int bitsPerSample;
  20938. /** True if it's a floating-point format, false if it's fixed-point. */
  20939. bool usesFloatingPointData;
  20940. /** The output stream for Use by subclasses. */
  20941. OutputStream* output;
  20942. private:
  20943. String formatName;
  20944. };
  20945. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  20946. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  20947. /**
  20948. Subclasses of AudioFormat are used to read and write different audio
  20949. file formats.
  20950. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  20951. */
  20952. class JUCE_API AudioFormat
  20953. {
  20954. public:
  20955. /** Destructor. */
  20956. virtual ~AudioFormat();
  20957. /** Returns the name of this format.
  20958. e.g. "WAV file" or "AIFF file"
  20959. */
  20960. const String& getFormatName() const;
  20961. /** Returns all the file extensions that might apply to a file of this format.
  20962. The first item will be the one that's preferred when creating a new file.
  20963. So for a wav file this might just return ".wav"; for an AIFF file it might
  20964. return two items, ".aif" and ".aiff"
  20965. */
  20966. const StringArray& getFileExtensions() const;
  20967. /** Returns true if this the given file can be read by this format.
  20968. Subclasses shouldn't do too much work here, just check the extension or
  20969. file type. The base class implementation just checks the file's extension
  20970. against one of the ones that was registered in the constructor.
  20971. */
  20972. virtual bool canHandleFile (const File& fileToTest);
  20973. /** Returns a set of sample rates that the format can read and write. */
  20974. virtual const Array <int> getPossibleSampleRates() = 0;
  20975. /** Returns a set of bit depths that the format can read and write. */
  20976. virtual const Array <int> getPossibleBitDepths() = 0;
  20977. /** Returns true if the format can do 2-channel audio. */
  20978. virtual bool canDoStereo() = 0;
  20979. /** Returns true if the format can do 1-channel audio. */
  20980. virtual bool canDoMono() = 0;
  20981. /** Returns true if the format uses compressed data. */
  20982. virtual bool isCompressed();
  20983. /** Returns a list of different qualities that can be used when writing.
  20984. Non-compressed formats will just return an empty array, but for something
  20985. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  20986. When calling createWriterFor(), an index from this array is passed in to
  20987. tell the format which option is required.
  20988. */
  20989. virtual const StringArray getQualityOptions();
  20990. /** Tries to create an object that can read from a stream containing audio
  20991. data in this format.
  20992. The reader object that is returned can be used to read from the stream, and
  20993. should then be deleted by the caller.
  20994. @param sourceStream the stream to read from - the AudioFormatReader object
  20995. that is returned will delete this stream when it no longer
  20996. needs it.
  20997. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  20998. should delete the stream object that was passed-in. (If a valid
  20999. reader is returned, it will always be in charge of deleting the
  21000. stream, so this parameter is ignored)
  21001. @see AudioFormatReader
  21002. */
  21003. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21004. const bool deleteStreamIfOpeningFails) = 0;
  21005. /** Tries to create an object that can write to a stream with this audio format.
  21006. The writer object that is returned can be used to write to the stream, and
  21007. should then be deleted by the caller.
  21008. If the stream can't be created for some reason (e.g. the parameters passed in
  21009. here aren't suitable), this will return 0.
  21010. @param streamToWriteTo the stream that the data will go to - this will be
  21011. deleted by the AudioFormatWriter object when it's no longer
  21012. needed. If no AudioFormatWriter can be created by this method,
  21013. the stream will NOT be deleted, so that the caller can re-use it
  21014. to try to open a different format, etc
  21015. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  21016. returned by getPossibleSampleRates()
  21017. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  21018. the choice will depend on the results of canDoMono() and
  21019. canDoStereo()
  21020. @param bitsPerSample the bits per sample to use - this must be one of the values
  21021. returned by getPossibleBitDepths()
  21022. @param metadataValues a set of metadata values that the writer should try to write
  21023. to the stream. Exactly what these are depends on the format,
  21024. and the subclass doesn't actually have to do anything with
  21025. them if it doesn't want to. Have a look at the specific format
  21026. implementation classes to see possible values that can be
  21027. used
  21028. @param qualityOptionIndex the index of one of compression qualities returned by the
  21029. getQualityOptions() method. If there aren't any quality options
  21030. for this format, just pass 0 in this parameter, as it'll be
  21031. ignored
  21032. @see AudioFormatWriter
  21033. */
  21034. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21035. double sampleRateToUse,
  21036. unsigned int numberOfChannels,
  21037. int bitsPerSample,
  21038. const StringPairArray& metadataValues,
  21039. int qualityOptionIndex) = 0;
  21040. protected:
  21041. /** Creates an AudioFormat object.
  21042. @param formatName this sets the value that will be returned by getFormatName()
  21043. @param fileExtensions a zero-terminated list of file extensions - this is what will
  21044. be returned by getFileExtension()
  21045. */
  21046. AudioFormat (const String& formatName,
  21047. const tchar** const fileExtensions);
  21048. private:
  21049. String formatName;
  21050. StringArray fileExtensions;
  21051. };
  21052. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  21053. /********* End of inlined file: juce_AudioFormat.h *********/
  21054. /**
  21055. Reads and Writes AIFF format audio files.
  21056. @see AudioFormat
  21057. */
  21058. class JUCE_API AiffAudioFormat : public AudioFormat
  21059. {
  21060. public:
  21061. /** Creates an format object. */
  21062. AiffAudioFormat();
  21063. /** Destructor. */
  21064. ~AiffAudioFormat();
  21065. const Array <int> getPossibleSampleRates();
  21066. const Array <int> getPossibleBitDepths();
  21067. bool canDoStereo();
  21068. bool canDoMono();
  21069. #if JUCE_MAC
  21070. bool canHandleFile (const File& fileToTest);
  21071. #endif
  21072. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21073. const bool deleteStreamIfOpeningFails);
  21074. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21075. double sampleRateToUse,
  21076. unsigned int numberOfChannels,
  21077. int bitsPerSample,
  21078. const StringPairArray& metadataValues,
  21079. int qualityOptionIndex);
  21080. juce_UseDebuggingNewOperator
  21081. };
  21082. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21083. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  21084. #endif
  21085. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  21086. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  21087. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  21088. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  21089. #if JUCE_USE_CDBURNER
  21090. /**
  21091. */
  21092. class AudioCDBurner
  21093. {
  21094. public:
  21095. /** Returns a list of available optical drives.
  21096. Use openDevice() to open one of the items from this list.
  21097. */
  21098. static const StringArray findAvailableDevices();
  21099. /** Tries to open one of the optical drives.
  21100. The deviceIndex is an index into the array returned by findAvailableDevices().
  21101. */
  21102. static AudioCDBurner* openDevice (const int deviceIndex);
  21103. /** Destructor. */
  21104. ~AudioCDBurner();
  21105. /** Returns true if there's a writable disk in the drive.
  21106. */
  21107. bool isDiskPresent() const;
  21108. /** Returns the number of free blocks on the disk.
  21109. There are 75 blocks per second, at 44100Hz.
  21110. */
  21111. int getNumAvailableAudioBlocks() const;
  21112. /** Adds a track to be written.
  21113. The source passed-in here will be kept by this object, and it will
  21114. be used and deleted at some point in the future, either during the
  21115. burn() method or when this AudioCDBurner object is deleted. Your caller
  21116. method shouldn't keep a reference to it or use it again after passing
  21117. it in here.
  21118. */
  21119. bool addAudioTrack (AudioSource* source, int numSamples);
  21120. /**
  21121. Return true to cancel the current burn operation
  21122. */
  21123. class BurnProgressListener
  21124. {
  21125. public:
  21126. BurnProgressListener() throw() {}
  21127. virtual ~BurnProgressListener() {}
  21128. /** Called at intervals to report on the progress of the AudioCDBurner.
  21129. To cancel the burn, return true from this.
  21130. */
  21131. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  21132. };
  21133. const String burn (BurnProgressListener* listener,
  21134. const bool ejectDiscAfterwards,
  21135. const bool peformFakeBurnForTesting);
  21136. juce_UseDebuggingNewOperator
  21137. private:
  21138. AudioCDBurner (const int deviceIndex);
  21139. void* internal;
  21140. };
  21141. #endif
  21142. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  21143. /********* End of inlined file: juce_AudioCDBurner.h *********/
  21144. #endif
  21145. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  21146. /********* Start of inlined file: juce_AudioCDReader.h *********/
  21147. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  21148. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  21149. #if JUCE_USE_CDREADER
  21150. #if JUCE_MAC
  21151. #endif
  21152. /**
  21153. A type of AudioFormatReader that reads from an audio CD.
  21154. One of these can be used to read a CD as if it's one big audio stream. Use the
  21155. getPositionOfTrackStart() method to find where the individual tracks are
  21156. within the stream.
  21157. @see AudioFormatReader
  21158. */
  21159. class JUCE_API AudioCDReader : public AudioFormatReader
  21160. {
  21161. public:
  21162. /** Returns a list of names of Audio CDs currently available for reading.
  21163. If there's a CD drive but no CD in it, this might return an empty list, or
  21164. possibly a device that can be opened but which has no tracks, depending
  21165. on the platform.
  21166. @see createReaderForCD
  21167. */
  21168. static const StringArray getAvailableCDNames();
  21169. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  21170. @param index the index of one of the available CDs - use getAvailableCDNames()
  21171. to find out how many there are.
  21172. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  21173. caller will be responsible for deleting the object returned.
  21174. */
  21175. static AudioCDReader* createReaderForCD (const int index);
  21176. /** Destructor. */
  21177. ~AudioCDReader();
  21178. /** Implementation of the AudioFormatReader method. */
  21179. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  21180. int64 startSampleInFile, int numSamples);
  21181. /** Checks whether the CD has been removed from the drive.
  21182. */
  21183. bool isCDStillPresent() const;
  21184. /** Returns the total number of tracks (audio + data).
  21185. */
  21186. int getNumTracks() const;
  21187. /** Finds the sample offset of the start of a track.
  21188. @param trackNum the track number, where 0 is the first track.
  21189. */
  21190. int getPositionOfTrackStart (int trackNum) const;
  21191. /** Returns true if a given track is an audio track.
  21192. @param trackNum the track number, where 0 is the first track.
  21193. */
  21194. bool isTrackAudio (int trackNum) const;
  21195. /** Refreshes the object's table of contents.
  21196. If the disc has been ejected and a different one put in since this
  21197. object was created, this will cause it to update its idea of how many tracks
  21198. there are, etc.
  21199. */
  21200. void refreshTrackLengths();
  21201. /** Enables scanning for indexes within tracks.
  21202. @see getLastIndex
  21203. */
  21204. void enableIndexScanning (bool enabled);
  21205. /** Returns the index number found during the last read() call.
  21206. Index scanning is turned off by default - turn it on with enableIndexScanning().
  21207. Then when the read() method is called, if it comes across an index within that
  21208. block, the index number is stored and returned by this method.
  21209. Some devices might not support indexes, of course.
  21210. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  21211. @see enableIndexScanning
  21212. */
  21213. int getLastIndex() const;
  21214. /** Scans a track to find the position of any indexes within it.
  21215. @param trackNumber the track to look in, where 0 is the first track on the disc
  21216. @returns an array of sample positions of any index points found (not including
  21217. the index that marks the start of the track)
  21218. */
  21219. const Array <int> findIndexesInTrack (const int trackNumber);
  21220. /** Returns the CDDB id number for the CD.
  21221. It's not a great way of identifying a disc, but it's traditional.
  21222. */
  21223. int getCDDBId();
  21224. /** Tries to eject the disk.
  21225. Of course this might not be possible, if some other process is using it.
  21226. */
  21227. void ejectDisk();
  21228. juce_UseDebuggingNewOperator
  21229. private:
  21230. #if JUCE_MAC
  21231. File volumeDir;
  21232. OwnedArray<File> tracks;
  21233. Array <int> trackStartSamples;
  21234. int currentReaderTrack;
  21235. ScopedPointer <AudioFormatReader> reader;
  21236. AudioCDReader (const File& volume);
  21237. public:
  21238. static int compareElements (const File* const, const File* const) throw();
  21239. private:
  21240. #elif JUCE_WINDOWS
  21241. int numTracks;
  21242. int trackStarts[100];
  21243. bool audioTracks [100];
  21244. void* handle;
  21245. bool indexingEnabled;
  21246. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  21247. MemoryBlock buffer;
  21248. AudioCDReader (void* handle);
  21249. int getIndexAt (int samplePos);
  21250. #elif JUCE_LINUX
  21251. AudioCDReader();
  21252. #endif
  21253. AudioCDReader (const AudioCDReader&);
  21254. const AudioCDReader& operator= (const AudioCDReader&);
  21255. };
  21256. #endif
  21257. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  21258. /********* End of inlined file: juce_AudioCDReader.h *********/
  21259. #endif
  21260. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  21261. #endif
  21262. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21263. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  21264. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21265. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21266. /**
  21267. A class for keeping a list of available audio formats, and for deciding which
  21268. one to use to open a given file.
  21269. You can either use this class as a singleton object, or create instances of it
  21270. yourself. Once created, use its registerFormat() method to tell it which
  21271. formats it should use.
  21272. @see AudioFormat
  21273. */
  21274. class JUCE_API AudioFormatManager
  21275. {
  21276. public:
  21277. /** Creates an empty format manager.
  21278. Before it'll be any use, you'll need to call registerFormat() with all the
  21279. formats you want it to be able to recognise.
  21280. */
  21281. AudioFormatManager();
  21282. /** Destructor. */
  21283. ~AudioFormatManager();
  21284. juce_DeclareSingleton (AudioFormatManager, false);
  21285. /** Adds a format to the manager's list of available file types.
  21286. The object passed-in will be deleted by this object, so don't keep a pointer
  21287. to it!
  21288. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  21289. return this one when called.
  21290. */
  21291. void registerFormat (AudioFormat* newFormat,
  21292. const bool makeThisTheDefaultFormat);
  21293. /** Handy method to make it easy to register the formats that come with Juce.
  21294. Currently, this will add WAV and AIFF to the list.
  21295. */
  21296. void registerBasicFormats();
  21297. /** Clears the list of known formats. */
  21298. void clearFormats();
  21299. /** Returns the number of currently registered file formats. */
  21300. int getNumKnownFormats() const;
  21301. /** Returns one of the registered file formats. */
  21302. AudioFormat* getKnownFormat (const int index) const;
  21303. /** Looks for which of the known formats is listed as being for a given file
  21304. extension.
  21305. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  21306. */
  21307. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  21308. /** Returns the format which has been set as the default one.
  21309. You can set a format as being the default when it is registered. It's useful
  21310. when you want to write to a file, because the best format may change between
  21311. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  21312. If none has been set as the default, this method will just return the first
  21313. one in the list.
  21314. */
  21315. AudioFormat* getDefaultFormat() const;
  21316. /** Returns a set of wildcards for file-matching that contains the extensions for
  21317. all known formats.
  21318. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  21319. */
  21320. const String getWildcardForAllFormats() const;
  21321. /** Searches through the known formats to try to create a suitable reader for
  21322. this file.
  21323. If none of the registered formats can open the file, it'll return 0. If it
  21324. returns a reader, it's the caller's responsibility to delete the reader.
  21325. */
  21326. AudioFormatReader* createReaderFor (const File& audioFile);
  21327. /** Searches through the known formats to try to create a suitable reader for
  21328. this stream.
  21329. The stream object that is passed-in will be deleted by this method or by the
  21330. reader that is returned, so the caller should not keep any references to it.
  21331. The stream that is passed-in must be capable of being repositioned so
  21332. that all the formats can have a go at opening it.
  21333. If none of the registered formats can open the stream, it'll return 0. If it
  21334. returns a reader, it's the caller's responsibility to delete the reader.
  21335. */
  21336. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  21337. juce_UseDebuggingNewOperator
  21338. private:
  21339. VoidArray knownFormats;
  21340. int defaultFormatIndex;
  21341. };
  21342. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21343. /********* End of inlined file: juce_AudioFormatManager.h *********/
  21344. #endif
  21345. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21346. #endif
  21347. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21348. #endif
  21349. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21350. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  21351. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21352. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21353. /**
  21354. This class is used to wrap an AudioFormatReader and only read from a
  21355. subsection of the file.
  21356. So if you have a reader which can read a 1000 sample file, you could wrap it
  21357. in one of these to only access, e.g. samples 100 to 200, and any samples
  21358. outside that will come back as 0. Accessing sample 0 from this reader will
  21359. actually read the first sample from the other's subsection, which might
  21360. be at a non-zero position.
  21361. @see AudioFormatReader
  21362. */
  21363. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  21364. {
  21365. public:
  21366. /** Creates a AudioSubsectionReader for a given data source.
  21367. @param sourceReader the source reader from which we'll be taking data
  21368. @param subsectionStartSample the sample within the source reader which will be
  21369. mapped onto sample 0 for this reader.
  21370. @param subsectionLength the number of samples from the source that will
  21371. make up the subsection. If this reader is asked for
  21372. any samples beyond this region, it will return zero.
  21373. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  21374. this object is deleted.
  21375. */
  21376. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  21377. const int64 subsectionStartSample,
  21378. const int64 subsectionLength,
  21379. const bool deleteSourceWhenDeleted);
  21380. /** Destructor. */
  21381. ~AudioSubsectionReader();
  21382. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  21383. int64 startSampleInFile, int numSamples);
  21384. void readMaxLevels (int64 startSample,
  21385. int64 numSamples,
  21386. float& lowestLeft,
  21387. float& highestLeft,
  21388. float& lowestRight,
  21389. float& highestRight);
  21390. juce_UseDebuggingNewOperator
  21391. private:
  21392. AudioFormatReader* const source;
  21393. int64 startSample, length;
  21394. const bool deleteSourceWhenDeleted;
  21395. AudioSubsectionReader (const AudioSubsectionReader&);
  21396. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  21397. };
  21398. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21399. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  21400. #endif
  21401. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21402. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  21403. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21404. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21405. class AudioThumbnailCache;
  21406. /**
  21407. Makes it easy to quickly draw scaled views of the waveform shape of an
  21408. audio file.
  21409. To use this class, just create an AudioThumbNail class for the file you want
  21410. to draw, call setSource to tell it which file or resource to use, then call
  21411. drawChannel() to draw it.
  21412. The class will asynchronously scan the wavefile to create its scaled-down view,
  21413. so you should make your UI repaint itself as this data comes in. To do this, the
  21414. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  21415. listeners should repaint themselves.
  21416. The thumbnail stores an internal low-res version of the wave data, and this can
  21417. be loaded and saved to avoid having to scan the file again.
  21418. @see AudioThumbnailCache
  21419. */
  21420. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  21421. public TimeSliceClient,
  21422. private Timer
  21423. {
  21424. public:
  21425. /** Creates an audio thumbnail.
  21426. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  21427. of the audio data, this is the scale at which it should be done. (This
  21428. number is the number of original samples that will be averaged for each
  21429. low-res sample)
  21430. @param formatManagerToUse the audio format manager that is used to open the file
  21431. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  21432. thread and storage that is used to by the thumbnail, and the cache
  21433. object can be shared between multiple thumbnails
  21434. */
  21435. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  21436. AudioFormatManager& formatManagerToUse,
  21437. AudioThumbnailCache& cacheToUse);
  21438. /** Destructor. */
  21439. ~AudioThumbnail();
  21440. /** Specifies the file or stream that contains the audio file.
  21441. For a file, just call
  21442. @code
  21443. setSource (new FileInputSource (file))
  21444. @endcode
  21445. You can pass a zero in here to clear the thumbnail.
  21446. The source that is passed in will be deleted by this object when it is no
  21447. longer needed
  21448. */
  21449. void setSource (InputSource* const newSource);
  21450. /** Reloads the low res thumbnail data from an input stream.
  21451. The thumb will automatically attempt to reload itself from its
  21452. AudioThumbnailCache.
  21453. */
  21454. void loadFrom (InputStream& input);
  21455. /** Saves the low res thumbnail data to an output stream.
  21456. The thumb will automatically attempt to save itself to its
  21457. AudioThumbnailCache after it finishes scanning the wave file.
  21458. */
  21459. void saveTo (OutputStream& output) const;
  21460. /** Returns the number of channels in the file.
  21461. */
  21462. int getNumChannels() const throw();
  21463. /** Returns the length of the audio file, in seconds.
  21464. */
  21465. double getTotalLength() const throw();
  21466. /** Renders the waveform shape for a channel.
  21467. The waveform will be drawn within the specified rectangle, where startTime
  21468. and endTime specify the times within the audio file that should be positioned
  21469. at the left and right edges of the rectangle.
  21470. The waveform will be scaled vertically so that a full-volume sample will fill
  21471. the rectangle vertically, but you can also specify an extra vertical scale factor
  21472. with the verticalZoomFactor parameter.
  21473. */
  21474. void drawChannel (Graphics& g,
  21475. int x, int y, int w, int h,
  21476. double startTimeSeconds,
  21477. double endTimeSeconds,
  21478. int channelNum,
  21479. const float verticalZoomFactor);
  21480. /** Returns true if the low res preview is fully generated.
  21481. */
  21482. bool isFullyLoaded() const throw();
  21483. /** @internal */
  21484. bool useTimeSlice();
  21485. /** @internal */
  21486. void timerCallback();
  21487. juce_UseDebuggingNewOperator
  21488. private:
  21489. AudioFormatManager& formatManagerToUse;
  21490. AudioThumbnailCache& cache;
  21491. ScopedPointer <InputSource> source;
  21492. CriticalSection readerLock;
  21493. ScopedPointer <AudioFormatReader> reader;
  21494. MemoryBlock data, cachedLevels;
  21495. int orginalSamplesPerThumbnailSample;
  21496. int numChannelsCached, numSamplesCached;
  21497. double cachedStart, cachedTimePerPixel;
  21498. bool cacheNeedsRefilling;
  21499. void clear();
  21500. AudioFormatReader* createReader() const;
  21501. void generateSection (AudioFormatReader& reader,
  21502. int64 startSample,
  21503. int numSamples);
  21504. char* getChannelData (int channel) const;
  21505. void refillCache (const int numSamples,
  21506. double startTime,
  21507. const double timePerPixel);
  21508. friend class AudioThumbnailCache;
  21509. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  21510. bool initialiseFromAudioFile (AudioFormatReader& reader);
  21511. // returns true if more needs to be read
  21512. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  21513. };
  21514. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21515. /********* End of inlined file: juce_AudioThumbnail.h *********/
  21516. #endif
  21517. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21518. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  21519. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21520. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21521. struct ThumbnailCacheEntry;
  21522. /**
  21523. An instance of this class is used to manage multiple AudioThumbnail objects.
  21524. The cache runs a single background thread that is shared by all the thumbnails
  21525. that need it, and it maintains a set of low-res previews in memory, to avoid
  21526. having to re-scan audio files too often.
  21527. @see AudioThumbnail
  21528. */
  21529. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  21530. {
  21531. public:
  21532. /** Creates a cache object.
  21533. The maxNumThumbsToStore parameter lets you specify how many previews should
  21534. be kept in memory at once.
  21535. */
  21536. AudioThumbnailCache (const int maxNumThumbsToStore);
  21537. /** Destructor. */
  21538. ~AudioThumbnailCache();
  21539. /** Clears out any stored thumbnails.
  21540. */
  21541. void clear();
  21542. /** Reloads the specified thumb if this cache contains the appropriate stored
  21543. data.
  21544. This is called automatically by the AudioThumbnail class, so you shouldn't
  21545. normally need to call it directly.
  21546. */
  21547. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  21548. /** Stores the cachable data from the specified thumb in this cache.
  21549. This is called automatically by the AudioThumbnail class, so you shouldn't
  21550. normally need to call it directly.
  21551. */
  21552. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  21553. juce_UseDebuggingNewOperator
  21554. private:
  21555. OwnedArray <ThumbnailCacheEntry> thumbs;
  21556. int maxNumThumbsToStore;
  21557. friend class AudioThumbnail;
  21558. void addThumbnail (AudioThumbnail* const thumb);
  21559. void removeThumbnail (AudioThumbnail* const thumb);
  21560. };
  21561. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21562. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  21563. #endif
  21564. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21565. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  21566. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21567. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21568. #if JUCE_USE_FLAC || defined (DOXYGEN)
  21569. /**
  21570. Reads and writes the lossless-compression FLAC audio format.
  21571. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  21572. and make sure your include search path and library search path are set up to find
  21573. the FLAC header files and static libraries.
  21574. @see AudioFormat
  21575. */
  21576. class JUCE_API FlacAudioFormat : public AudioFormat
  21577. {
  21578. public:
  21579. FlacAudioFormat();
  21580. ~FlacAudioFormat();
  21581. const Array <int> getPossibleSampleRates();
  21582. const Array <int> getPossibleBitDepths();
  21583. bool canDoStereo();
  21584. bool canDoMono();
  21585. bool isCompressed();
  21586. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21587. const bool deleteStreamIfOpeningFails);
  21588. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21589. double sampleRateToUse,
  21590. unsigned int numberOfChannels,
  21591. int bitsPerSample,
  21592. const StringPairArray& metadataValues,
  21593. int qualityOptionIndex);
  21594. juce_UseDebuggingNewOperator
  21595. };
  21596. #endif
  21597. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21598. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  21599. #endif
  21600. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21601. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  21602. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21603. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21604. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  21605. /**
  21606. Reads and writes the Ogg-Vorbis audio format.
  21607. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  21608. and make sure your include search path and library search path are set up to find
  21609. the Vorbis and Ogg header files and static libraries.
  21610. @see AudioFormat,
  21611. */
  21612. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  21613. {
  21614. public:
  21615. OggVorbisAudioFormat();
  21616. ~OggVorbisAudioFormat();
  21617. const Array <int> getPossibleSampleRates();
  21618. const Array <int> getPossibleBitDepths();
  21619. bool canDoStereo();
  21620. bool canDoMono();
  21621. bool isCompressed();
  21622. const StringArray getQualityOptions();
  21623. /** Tries to estimate the quality level of an ogg file based on its size.
  21624. If it can't read the file for some reason, this will just return 1 (medium quality),
  21625. otherwise it will return the approximate quality setting that would have been used
  21626. to create the file.
  21627. @see getQualityOptions
  21628. */
  21629. int estimateOggFileQuality (const File& source);
  21630. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21631. const bool deleteStreamIfOpeningFails);
  21632. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21633. double sampleRateToUse,
  21634. unsigned int numberOfChannels,
  21635. int bitsPerSample,
  21636. const StringPairArray& metadataValues,
  21637. int qualityOptionIndex);
  21638. juce_UseDebuggingNewOperator
  21639. };
  21640. #endif
  21641. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21642. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  21643. #endif
  21644. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21645. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  21646. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21647. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21648. #if JUCE_QUICKTIME
  21649. /**
  21650. Uses QuickTime to read the audio track a movie or media file.
  21651. As well as QuickTime movies, this should also manage to open other audio
  21652. files that quicktime can understand, like mp3, m4a, etc.
  21653. @see AudioFormat
  21654. */
  21655. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  21656. {
  21657. public:
  21658. /** Creates a format object. */
  21659. QuickTimeAudioFormat();
  21660. /** Destructor. */
  21661. ~QuickTimeAudioFormat();
  21662. const Array <int> getPossibleSampleRates();
  21663. const Array <int> getPossibleBitDepths();
  21664. bool canDoStereo();
  21665. bool canDoMono();
  21666. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21667. const bool deleteStreamIfOpeningFails);
  21668. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21669. double sampleRateToUse,
  21670. unsigned int numberOfChannels,
  21671. int bitsPerSample,
  21672. const StringPairArray& metadataValues,
  21673. int qualityOptionIndex);
  21674. juce_UseDebuggingNewOperator
  21675. };
  21676. #endif
  21677. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21678. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  21679. #endif
  21680. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21681. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  21682. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21683. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21684. /**
  21685. Reads and Writes WAV format audio files.
  21686. @see AudioFormat
  21687. */
  21688. class JUCE_API WavAudioFormat : public AudioFormat
  21689. {
  21690. public:
  21691. /** Creates a format object. */
  21692. WavAudioFormat();
  21693. /** Destructor. */
  21694. ~WavAudioFormat();
  21695. /** Metadata property name used by wav readers and writers for adding
  21696. a BWAV chunk to the file.
  21697. @see AudioFormatReader::metadataValues, createWriterFor
  21698. */
  21699. static const tchar* const bwavDescription;
  21700. /** Metadata property name used by wav readers and writers for adding
  21701. a BWAV chunk to the file.
  21702. @see AudioFormatReader::metadataValues, createWriterFor
  21703. */
  21704. static const tchar* const bwavOriginator;
  21705. /** Metadata property name used by wav readers and writers for adding
  21706. a BWAV chunk to the file.
  21707. @see AudioFormatReader::metadataValues, createWriterFor
  21708. */
  21709. static const tchar* const bwavOriginatorRef;
  21710. /** Metadata property name used by wav readers and writers for adding
  21711. a BWAV chunk to the file.
  21712. Date format is: yyyy-mm-dd
  21713. @see AudioFormatReader::metadataValues, createWriterFor
  21714. */
  21715. static const tchar* const bwavOriginationDate;
  21716. /** Metadata property name used by wav readers and writers for adding
  21717. a BWAV chunk to the file.
  21718. Time format is: hh-mm-ss
  21719. @see AudioFormatReader::metadataValues, createWriterFor
  21720. */
  21721. static const tchar* const bwavOriginationTime;
  21722. /** Metadata property name used by wav readers and writers for adding
  21723. a BWAV chunk to the file.
  21724. This is the number of samples from the start of an edit that the
  21725. file is supposed to begin at. Seems like an obvious mistake to
  21726. only allow a file to occur in an edit once, but that's the way
  21727. it is..
  21728. @see AudioFormatReader::metadataValues, createWriterFor
  21729. */
  21730. static const tchar* const bwavTimeReference;
  21731. /** Metadata property name used by wav readers and writers for adding
  21732. a BWAV chunk to the file.
  21733. This is a
  21734. @see AudioFormatReader::metadataValues, createWriterFor
  21735. */
  21736. static const tchar* const bwavCodingHistory;
  21737. /** Utility function to fill out the appropriate metadata for a BWAV file.
  21738. This just makes it easier than using the property names directly, and it
  21739. fills out the time and date in the right format.
  21740. */
  21741. static const StringPairArray createBWAVMetadata (const String& description,
  21742. const String& originator,
  21743. const String& originatorRef,
  21744. const Time& dateAndTime,
  21745. const int64 timeReferenceSamples,
  21746. const String& codingHistory);
  21747. const Array <int> getPossibleSampleRates();
  21748. const Array <int> getPossibleBitDepths();
  21749. bool canDoStereo();
  21750. bool canDoMono();
  21751. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21752. const bool deleteStreamIfOpeningFails);
  21753. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21754. double sampleRateToUse,
  21755. unsigned int numberOfChannels,
  21756. int bitsPerSample,
  21757. const StringPairArray& metadataValues,
  21758. int qualityOptionIndex);
  21759. /** Utility function to replace the metadata in a wav file with a new set of values.
  21760. If possible, this cheats by overwriting just the metadata region of the file, rather
  21761. than by copying the whole file again.
  21762. */
  21763. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  21764. juce_UseDebuggingNewOperator
  21765. };
  21766. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21767. /********* End of inlined file: juce_WavAudioFormat.h *********/
  21768. #endif
  21769. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21770. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  21771. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21772. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21773. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  21774. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  21775. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  21776. /**
  21777. A type of AudioSource which can be repositioned.
  21778. The basic AudioSource just streams continuously with no idea of a current
  21779. time or length, so the PositionableAudioSource is used for a finite stream
  21780. that has a current read position.
  21781. @see AudioSource, AudioTransportSource
  21782. */
  21783. class JUCE_API PositionableAudioSource : public AudioSource
  21784. {
  21785. protected:
  21786. /** Creates the PositionableAudioSource. */
  21787. PositionableAudioSource() throw() {}
  21788. public:
  21789. /** Destructor */
  21790. ~PositionableAudioSource() {}
  21791. /** Tells the stream to move to a new position.
  21792. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  21793. should return samples from this position.
  21794. Note that this may be called on a different thread to getNextAudioBlock(),
  21795. so the subclass should make sure it's synchronised.
  21796. */
  21797. virtual void setNextReadPosition (int newPosition) = 0;
  21798. /** Returns the position from which the next block will be returned.
  21799. @see setNextReadPosition
  21800. */
  21801. virtual int getNextReadPosition() const = 0;
  21802. /** Returns the total length of the stream (in samples). */
  21803. virtual int getTotalLength() const = 0;
  21804. /** Returns true if this source is actually playing in a loop. */
  21805. virtual bool isLooping() const = 0;
  21806. };
  21807. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  21808. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  21809. /**
  21810. A type of AudioSource that will read from an AudioFormatReader.
  21811. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  21812. */
  21813. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  21814. {
  21815. public:
  21816. /** Creates an AudioFormatReaderSource for a given reader.
  21817. @param sourceReader the reader to use as the data source
  21818. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  21819. when this object is deleted; if false it will be
  21820. left up to the caller to manage its lifetime
  21821. */
  21822. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  21823. const bool deleteReaderWhenThisIsDeleted);
  21824. /** Destructor. */
  21825. ~AudioFormatReaderSource();
  21826. /** Toggles loop-mode.
  21827. If set to true, it will continuously loop the input source. If false,
  21828. it will just emit silence after the source has finished.
  21829. @see isLooping
  21830. */
  21831. void setLooping (const bool shouldLoop) throw();
  21832. /** Returns whether loop-mode is turned on or not. */
  21833. bool isLooping() const { return looping; }
  21834. /** Returns the reader that's being used. */
  21835. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  21836. /** Implementation of the AudioSource method. */
  21837. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  21838. /** Implementation of the AudioSource method. */
  21839. void releaseResources();
  21840. /** Implementation of the AudioSource method. */
  21841. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  21842. /** Implements the PositionableAudioSource method. */
  21843. void setNextReadPosition (int newPosition);
  21844. /** Implements the PositionableAudioSource method. */
  21845. int getNextReadPosition() const;
  21846. /** Implements the PositionableAudioSource method. */
  21847. int getTotalLength() const;
  21848. juce_UseDebuggingNewOperator
  21849. private:
  21850. AudioFormatReader* reader;
  21851. bool deleteReader;
  21852. int volatile nextPlayPos;
  21853. bool volatile looping;
  21854. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  21855. AudioFormatReaderSource (const AudioFormatReaderSource&);
  21856. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  21857. };
  21858. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21859. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  21860. #endif
  21861. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  21862. #endif
  21863. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21864. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  21865. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21866. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21867. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21868. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21869. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21870. class AudioIODevice;
  21871. /**
  21872. One of these is passed to an AudioIODevice object to stream the audio data
  21873. in and out.
  21874. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21875. method on its own high-priority audio thread, when it needs to send or receive
  21876. the next block of data.
  21877. @see AudioIODevice, AudioDeviceManager
  21878. */
  21879. class JUCE_API AudioIODeviceCallback
  21880. {
  21881. public:
  21882. /** Destructor. */
  21883. virtual ~AudioIODeviceCallback() {}
  21884. /** Processes a block of incoming and outgoing audio data.
  21885. The subclass's implementation should use the incoming audio for whatever
  21886. purposes it needs to, and must fill all the output channels with the next
  21887. block of output data before returning.
  21888. The channel data is arranged with the same array indices as the channel name
  21889. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21890. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21891. associated channel, so remember to check for this.
  21892. @param inputChannelData a set of arrays containing the audio data for each
  21893. incoming channel - this data is valid until the function
  21894. returns. There will be one channel of data for each input
  21895. channel that was enabled when the audio device was opened
  21896. (see AudioIODevice::open())
  21897. @param numInputChannels the number of pointers to channel data in the
  21898. inputChannelData array.
  21899. @param outputChannelData a set of arrays which need to be filled with the data
  21900. that should be sent to each outgoing channel of the device.
  21901. There will be one channel of data for each output channel
  21902. that was enabled when the audio device was opened (see
  21903. AudioIODevice::open())
  21904. The initial contents of the array is undefined, so the
  21905. callback function must fill all the channels with zeros if
  21906. its output is silence. Failing to do this could cause quite
  21907. an unpleasant noise!
  21908. @param numOutputChannels the number of pointers to channel data in the
  21909. outputChannelData array.
  21910. @param numSamples the number of samples in each channel of the input and
  21911. output arrays. The number of samples will depend on the
  21912. audio device's buffer size and will usually remain constant,
  21913. although this isn't guaranteed, so make sure your code can
  21914. cope with reasonable changes in the buffer size from one
  21915. callback to the next.
  21916. */
  21917. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21918. int numInputChannels,
  21919. float** outputChannelData,
  21920. int numOutputChannels,
  21921. int numSamples) = 0;
  21922. /** Called to indicate that the device is about to start calling back.
  21923. This will be called just before the audio callbacks begin, either when this
  21924. callback has just been added to an audio device, or after the device has been
  21925. restarted because of a sample-rate or block-size change.
  21926. You can use this opportunity to find out the sample rate and block size
  21927. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21928. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21929. @param device the audio IO device that will be used to drive the callback.
  21930. Note that if you're going to store this this pointer, it is
  21931. only valid until the next time that audioDeviceStopped is called.
  21932. */
  21933. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21934. /** Called to indicate that the device has stopped.
  21935. */
  21936. virtual void audioDeviceStopped() = 0;
  21937. };
  21938. /**
  21939. Base class for an audio device with synchronised input and output channels.
  21940. Subclasses of this are used to implement different protocols such as DirectSound,
  21941. ASIO, CoreAudio, etc.
  21942. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21943. documentation for that class for more info.
  21944. For an easier way of managing audio devices and their settings, have a look at the
  21945. AudioDeviceManager class.
  21946. @see AudioIODeviceType, AudioDeviceManager
  21947. */
  21948. class JUCE_API AudioIODevice
  21949. {
  21950. public:
  21951. /** Destructor. */
  21952. virtual ~AudioIODevice();
  21953. /** Returns the device's name, (as set in the constructor). */
  21954. const String& getName() const throw() { return name; }
  21955. /** Returns the type of the device.
  21956. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21957. */
  21958. const String& getTypeName() const throw() { return typeName; }
  21959. /** Returns the names of all the available output channels on this device.
  21960. To find out which of these are currently in use, call getActiveOutputChannels().
  21961. */
  21962. virtual const StringArray getOutputChannelNames() = 0;
  21963. /** Returns the names of all the available input channels on this device.
  21964. To find out which of these are currently in use, call getActiveInputChannels().
  21965. */
  21966. virtual const StringArray getInputChannelNames() = 0;
  21967. /** Returns the number of sample-rates this device supports.
  21968. To find out which rates are available on this device, use this method to
  21969. find out how many there are, and getSampleRate() to get the rates.
  21970. @see getSampleRate
  21971. */
  21972. virtual int getNumSampleRates() = 0;
  21973. /** Returns one of the sample-rates this device supports.
  21974. To find out which rates are available on this device, use getNumSampleRates() to
  21975. find out how many there are, and getSampleRate() to get the individual rates.
  21976. The sample rate is set by the open() method.
  21977. (Note that for DirectSound some rates might not work, depending on combinations
  21978. of i/o channels that are being opened).
  21979. @see getNumSampleRates
  21980. */
  21981. virtual double getSampleRate (int index) = 0;
  21982. /** Returns the number of sizes of buffer that are available.
  21983. @see getBufferSizeSamples, getDefaultBufferSize
  21984. */
  21985. virtual int getNumBufferSizesAvailable() = 0;
  21986. /** Returns one of the possible buffer-sizes.
  21987. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21988. @returns a number of samples
  21989. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21990. */
  21991. virtual int getBufferSizeSamples (int index) = 0;
  21992. /** Returns the default buffer-size to use.
  21993. @returns a number of samples
  21994. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21995. */
  21996. virtual int getDefaultBufferSize() = 0;
  21997. /** Tries to open the device ready to play.
  21998. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21999. input channel should be enabled
  22000. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  22001. output channel should be enabled
  22002. @param sampleRate the sample rate to try to use - to find out which rates are
  22003. available, see getNumSampleRates() and getSampleRate()
  22004. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  22005. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  22006. @returns an error description if there's a problem, or an empty string if it succeeds in
  22007. opening the device
  22008. @see close
  22009. */
  22010. virtual const String open (const BitArray& inputChannels,
  22011. const BitArray& outputChannels,
  22012. double sampleRate,
  22013. int bufferSizeSamples) = 0;
  22014. /** Closes and releases the device if it's open. */
  22015. virtual void close() = 0;
  22016. /** Returns true if the device is still open.
  22017. A device might spontaneously close itself if something goes wrong, so this checks if
  22018. it's still open.
  22019. */
  22020. virtual bool isOpen() = 0;
  22021. /** Starts the device actually playing.
  22022. This must be called after the device has been opened.
  22023. @param callback the callback to use for streaming the data.
  22024. @see AudioIODeviceCallback, open
  22025. */
  22026. virtual void start (AudioIODeviceCallback* callback) = 0;
  22027. /** Stops the device playing.
  22028. Once a device has been started, this will stop it. Any pending calls to the
  22029. callback class will be flushed before this method returns.
  22030. */
  22031. virtual void stop() = 0;
  22032. /** Returns true if the device is still calling back.
  22033. The device might mysteriously stop, so this checks whether it's
  22034. still playing.
  22035. */
  22036. virtual bool isPlaying() = 0;
  22037. /** Returns the last error that happened if anything went wrong. */
  22038. virtual const String getLastError() = 0;
  22039. /** Returns the buffer size that the device is currently using.
  22040. If the device isn't actually open, this value doesn't really mean much.
  22041. */
  22042. virtual int getCurrentBufferSizeSamples() = 0;
  22043. /** Returns the sample rate that the device is currently using.
  22044. If the device isn't actually open, this value doesn't really mean much.
  22045. */
  22046. virtual double getCurrentSampleRate() = 0;
  22047. /** Returns the device's current physical bit-depth.
  22048. If the device isn't actually open, this value doesn't really mean much.
  22049. */
  22050. virtual int getCurrentBitDepth() = 0;
  22051. /** Returns a mask showing which of the available output channels are currently
  22052. enabled.
  22053. @see getOutputChannelNames
  22054. */
  22055. virtual const BitArray getActiveOutputChannels() const = 0;
  22056. /** Returns a mask showing which of the available input channels are currently
  22057. enabled.
  22058. @see getInputChannelNames
  22059. */
  22060. virtual const BitArray getActiveInputChannels() const = 0;
  22061. /** Returns the device's output latency.
  22062. This is the delay in samples between a callback getting a block of data, and
  22063. that data actually getting played.
  22064. */
  22065. virtual int getOutputLatencyInSamples() = 0;
  22066. /** Returns the device's input latency.
  22067. This is the delay in samples between some audio actually arriving at the soundcard,
  22068. and the callback getting passed this block of data.
  22069. */
  22070. virtual int getInputLatencyInSamples() = 0;
  22071. /** True if this device can show a pop-up control panel for editing its settings.
  22072. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22073. to display it.
  22074. */
  22075. virtual bool hasControlPanel() const;
  22076. /** Shows a device-specific control panel if there is one.
  22077. This should only be called for devices which return true from hasControlPanel().
  22078. */
  22079. virtual bool showControlPanel();
  22080. protected:
  22081. /** Creates a device, setting its name and type member variables. */
  22082. AudioIODevice (const String& deviceName,
  22083. const String& typeName);
  22084. /** @internal */
  22085. String name, typeName;
  22086. };
  22087. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22088. /********* End of inlined file: juce_AudioIODevice.h *********/
  22089. /**
  22090. Wrapper class to continuously stream audio from an audio source to an
  22091. AudioIODevice.
  22092. This object acts as an AudioIODeviceCallback, so can be attached to an
  22093. output device, and will stream audio from an AudioSource.
  22094. */
  22095. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  22096. {
  22097. public:
  22098. /** Creates an empty AudioSourcePlayer. */
  22099. AudioSourcePlayer();
  22100. /** Destructor.
  22101. Make sure this object isn't still being used by an AudioIODevice before
  22102. deleting it!
  22103. */
  22104. virtual ~AudioSourcePlayer();
  22105. /** Changes the current audio source to play from.
  22106. If the source passed in is already being used, this method will do nothing.
  22107. If the source is not null, its prepareToPlay() method will be called
  22108. before it starts being used for playback.
  22109. If there's another source currently playing, its releaseResources() method
  22110. will be called after it has been swapped for the new one.
  22111. @param newSource the new source to use - this will NOT be deleted
  22112. by this object when no longer needed, so it's the
  22113. caller's responsibility to manage it.
  22114. */
  22115. void setSource (AudioSource* newSource);
  22116. /** Returns the source that's playing.
  22117. May return 0 if there's no source.
  22118. */
  22119. AudioSource* getCurrentSource() const throw() { return source; }
  22120. /** Sets a gain to apply to the audio data. */
  22121. void setGain (const float newGain) throw();
  22122. /** Implementation of the AudioIODeviceCallback method. */
  22123. void audioDeviceIOCallback (const float** inputChannelData,
  22124. int totalNumInputChannels,
  22125. float** outputChannelData,
  22126. int totalNumOutputChannels,
  22127. int numSamples);
  22128. /** Implementation of the AudioIODeviceCallback method. */
  22129. void audioDeviceAboutToStart (AudioIODevice* device);
  22130. /** Implementation of the AudioIODeviceCallback method. */
  22131. void audioDeviceStopped();
  22132. juce_UseDebuggingNewOperator
  22133. private:
  22134. CriticalSection readLock;
  22135. AudioSource* source;
  22136. double sampleRate;
  22137. int bufferSize;
  22138. float* channels [128];
  22139. float* outputChans [128];
  22140. const float* inputChans [128];
  22141. AudioSampleBuffer tempBuffer;
  22142. float lastGain, gain;
  22143. AudioSourcePlayer (const AudioSourcePlayer&);
  22144. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  22145. };
  22146. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  22147. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  22148. #endif
  22149. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  22150. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  22151. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  22152. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  22153. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  22154. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  22155. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  22156. /**
  22157. An AudioSource which takes another source as input, and buffers it using a thread.
  22158. Create this as a wrapper around another thread, and it will read-ahead with
  22159. a background thread to smooth out playback. You can either create one of these
  22160. directly, or use it indirectly using an AudioTransportSource.
  22161. @see PositionableAudioSource, AudioTransportSource
  22162. */
  22163. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  22164. {
  22165. public:
  22166. /** Creates a BufferingAudioSource.
  22167. @param source the input source to read from
  22168. @param deleteSourceWhenDeleted if true, then the input source object will
  22169. be deleted when this object is deleted
  22170. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  22171. */
  22172. BufferingAudioSource (PositionableAudioSource* source,
  22173. const bool deleteSourceWhenDeleted,
  22174. int numberOfSamplesToBuffer);
  22175. /** Destructor.
  22176. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  22177. flag was set in the constructor.
  22178. */
  22179. ~BufferingAudioSource();
  22180. /** Implementation of the AudioSource method. */
  22181. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22182. /** Implementation of the AudioSource method. */
  22183. void releaseResources();
  22184. /** Implementation of the AudioSource method. */
  22185. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22186. /** Implements the PositionableAudioSource method. */
  22187. void setNextReadPosition (int newPosition);
  22188. /** Implements the PositionableAudioSource method. */
  22189. int getNextReadPosition() const;
  22190. /** Implements the PositionableAudioSource method. */
  22191. int getTotalLength() const { return source->getTotalLength(); }
  22192. /** Implements the PositionableAudioSource method. */
  22193. bool isLooping() const { return source->isLooping(); }
  22194. juce_UseDebuggingNewOperator
  22195. private:
  22196. PositionableAudioSource* source;
  22197. bool deleteSourceWhenDeleted;
  22198. int numberOfSamplesToBuffer;
  22199. AudioSampleBuffer buffer;
  22200. CriticalSection bufferStartPosLock;
  22201. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  22202. bool wasSourceLooping;
  22203. double volatile sampleRate;
  22204. friend class SharedBufferingAudioSourceThread;
  22205. bool readNextBufferChunk();
  22206. void readBufferSection (int start, int length, int bufferOffset);
  22207. BufferingAudioSource (const BufferingAudioSource&);
  22208. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  22209. };
  22210. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  22211. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  22212. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  22213. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22214. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22215. /**
  22216. A type of AudioSource that takes an input source and changes its sample rate.
  22217. @see AudioSource
  22218. */
  22219. class JUCE_API ResamplingAudioSource : public AudioSource
  22220. {
  22221. public:
  22222. /** Creates a ResamplingAudioSource for a given input source.
  22223. @param inputSource the input source to read from
  22224. @param deleteInputWhenDeleted if true, the input source will be deleted when
  22225. this object is deleted
  22226. */
  22227. ResamplingAudioSource (AudioSource* const inputSource,
  22228. const bool deleteInputWhenDeleted);
  22229. /** Destructor. */
  22230. ~ResamplingAudioSource();
  22231. /** Changes the resampling ratio.
  22232. (This value can be changed at any time, even while the source is running).
  22233. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  22234. values will speed it up; lower values will slow it
  22235. down. The ratio must be greater than 0
  22236. */
  22237. void setResamplingRatio (const double samplesInPerOutputSample);
  22238. /** Returns the current resampling ratio.
  22239. This is the value that was set by setResamplingRatio().
  22240. */
  22241. double getResamplingRatio() const throw() { return ratio; }
  22242. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22243. void releaseResources();
  22244. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22245. juce_UseDebuggingNewOperator
  22246. private:
  22247. AudioSource* const input;
  22248. const bool deleteInputWhenDeleted;
  22249. double ratio, lastRatio;
  22250. AudioSampleBuffer buffer;
  22251. int bufferPos, sampsInBuffer;
  22252. double subSampleOffset;
  22253. double coefficients[6];
  22254. CriticalSection ratioLock;
  22255. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  22256. void createLowPass (const double proportionalRate);
  22257. struct FilterState
  22258. {
  22259. double x1, x2, y1, y2;
  22260. };
  22261. FilterState filterStates[2];
  22262. void resetFilters();
  22263. void applyFilter (float* samples, int num, FilterState& fs);
  22264. ResamplingAudioSource (const ResamplingAudioSource&);
  22265. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  22266. };
  22267. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22268. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  22269. /**
  22270. An AudioSource that takes a PositionableAudioSource and allows it to be
  22271. played, stopped, started, etc.
  22272. This can also be told use a buffer and background thread to read ahead, and
  22273. if can correct for different sample-rates.
  22274. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  22275. to control playback of an audio file.
  22276. @see AudioSource, AudioSourcePlayer
  22277. */
  22278. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  22279. public ChangeBroadcaster
  22280. {
  22281. public:
  22282. /** Creates an AudioTransportSource.
  22283. After creating one of these, use the setSource() method to select an input source.
  22284. */
  22285. AudioTransportSource();
  22286. /** Destructor. */
  22287. ~AudioTransportSource();
  22288. /** Sets the reader that is being used as the input source.
  22289. This will stop playback, reset the position to 0 and change to the new reader.
  22290. The source passed in will not be deleted by this object, so must be managed by
  22291. the caller.
  22292. @param newSource the new input source to use. This may be zero
  22293. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  22294. is zero, no reading ahead will be done; if it's
  22295. greater than zero, a BufferingAudioSource will be used
  22296. to do the reading-ahead
  22297. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  22298. rate of the source, and playback will be sample-rate
  22299. adjusted to maintain playback at the correct pitch. If
  22300. this is 0, no sample-rate adjustment will be performed
  22301. */
  22302. void setSource (PositionableAudioSource* const newSource,
  22303. int readAheadBufferSize = 0,
  22304. double sourceSampleRateToCorrectFor = 0.0);
  22305. /** Changes the current playback position in the source stream.
  22306. The next time the getNextAudioBlock() method is called, this
  22307. is the time from which it'll read data.
  22308. @see getPosition
  22309. */
  22310. void setPosition (double newPosition);
  22311. /** Returns the position that the next data block will be read from
  22312. This is a time in seconds.
  22313. */
  22314. double getCurrentPosition() const;
  22315. /** Returns true if the player has stopped because its input stream ran out of data.
  22316. */
  22317. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  22318. /** Starts playing (if a source has been selected).
  22319. If it starts playing, this will send a message to any ChangeListeners
  22320. that are registered with this object.
  22321. */
  22322. void start();
  22323. /** Stops playing.
  22324. If it's actually playing, this will send a message to any ChangeListeners
  22325. that are registered with this object.
  22326. */
  22327. void stop();
  22328. /** Returns true if it's currently playing. */
  22329. bool isPlaying() const throw() { return playing; }
  22330. /** Changes the gain to apply to the output.
  22331. @param newGain a factor by which to multiply the outgoing samples,
  22332. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  22333. */
  22334. void setGain (const float newGain) throw();
  22335. /** Returns the current gain setting.
  22336. @see setGain
  22337. */
  22338. float getGain() const throw() { return gain; }
  22339. /** Implementation of the AudioSource method. */
  22340. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22341. /** Implementation of the AudioSource method. */
  22342. void releaseResources();
  22343. /** Implementation of the AudioSource method. */
  22344. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22345. /** Implements the PositionableAudioSource method. */
  22346. void setNextReadPosition (int newPosition);
  22347. /** Implements the PositionableAudioSource method. */
  22348. int getNextReadPosition() const;
  22349. /** Implements the PositionableAudioSource method. */
  22350. int getTotalLength() const;
  22351. /** Implements the PositionableAudioSource method. */
  22352. bool isLooping() const;
  22353. juce_UseDebuggingNewOperator
  22354. private:
  22355. PositionableAudioSource* source;
  22356. ResamplingAudioSource* resamplerSource;
  22357. BufferingAudioSource* bufferingSource;
  22358. PositionableAudioSource* positionableSource;
  22359. AudioSource* masterSource;
  22360. CriticalSection callbackLock;
  22361. float volatile gain, lastGain;
  22362. bool volatile playing, stopped;
  22363. double sampleRate, sourceSampleRate;
  22364. int blockSize, readAheadBufferSize;
  22365. bool isPrepared, inputStreamEOF;
  22366. AudioTransportSource (const AudioTransportSource&);
  22367. const AudioTransportSource& operator= (const AudioTransportSource&);
  22368. };
  22369. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  22370. /********* End of inlined file: juce_AudioTransportSource.h *********/
  22371. #endif
  22372. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  22373. #endif
  22374. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22375. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  22376. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22377. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22378. /**
  22379. An AudioSource that takes the audio from another source, and re-maps its
  22380. input and output channels to a different arrangement.
  22381. You can use this to increase or decrease the number of channels that an
  22382. audio source uses, or to re-order those channels.
  22383. Call the reset() method before using it to set up a default mapping, and then
  22384. the setInputChannelMapping() and setOutputChannelMapping() methods to
  22385. create an appropriate mapping, otherwise no channels will be connected and
  22386. it'll produce silence.
  22387. @see AudioSource
  22388. */
  22389. class ChannelRemappingAudioSource : public AudioSource
  22390. {
  22391. public:
  22392. /** Creates a remapping source that will pass on audio from the given input.
  22393. @param source the input source to use. Make sure that this doesn't
  22394. get deleted before the ChannelRemappingAudioSource object
  22395. @param deleteSourceWhenDeleted if true, the input source will be deleted
  22396. when this object is deleted, if false, the caller is
  22397. responsible for its deletion
  22398. */
  22399. ChannelRemappingAudioSource (AudioSource* const source,
  22400. const bool deleteSourceWhenDeleted);
  22401. /** Destructor. */
  22402. ~ChannelRemappingAudioSource();
  22403. /** Specifies a number of channels that this audio source must produce from its
  22404. getNextAudioBlock() callback.
  22405. */
  22406. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  22407. /** Clears any mapped channels.
  22408. After this, no channels are mapped, so this object will produce silence. Create
  22409. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  22410. */
  22411. void clearAllMappings() throw();
  22412. /** Creates an input channel mapping.
  22413. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  22414. data will be sent to destChannelIndex of our input source.
  22415. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  22416. source specified when this object was created).
  22417. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  22418. during our getNextAudioBlock() callback
  22419. */
  22420. void setInputChannelMapping (const int destChannelIndex,
  22421. const int sourceChannelIndex) throw();
  22422. /** Creates an output channel mapping.
  22423. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  22424. our input audio source will be copied to channel destChannelIndex of the final buffer.
  22425. @param sourceChannelIndex the index of an output channel coming from our input audio source
  22426. (i.e. the source specified when this object was created).
  22427. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  22428. during our getNextAudioBlock() callback
  22429. */
  22430. void setOutputChannelMapping (const int sourceChannelIndex,
  22431. const int destChannelIndex) throw();
  22432. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  22433. our input audio source.
  22434. */
  22435. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  22436. /** Returns the output channel to which channel outputChannelIndex of our input audio
  22437. source will be sent to.
  22438. */
  22439. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  22440. /** Returns an XML object to encapsulate the state of the mappings.
  22441. @see restoreFromXml
  22442. */
  22443. XmlElement* createXml() const throw();
  22444. /** Restores the mappings from an XML object created by createXML().
  22445. @see createXml
  22446. */
  22447. void restoreFromXml (const XmlElement& e) throw();
  22448. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22449. void releaseResources();
  22450. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22451. juce_UseDebuggingNewOperator
  22452. private:
  22453. int requiredNumberOfChannels;
  22454. Array <int> remappedInputs, remappedOutputs;
  22455. AudioSource* const source;
  22456. const bool deleteSourceWhenDeleted;
  22457. AudioSampleBuffer buffer;
  22458. AudioSourceChannelInfo remappedInfo;
  22459. CriticalSection lock;
  22460. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  22461. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  22462. };
  22463. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22464. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  22465. #endif
  22466. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22467. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  22468. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22469. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22470. /********* Start of inlined file: juce_IIRFilter.h *********/
  22471. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  22472. #define __JUCE_IIRFILTER_JUCEHEADER__
  22473. /**
  22474. An IIR filter that can perform low, high, or band-pass filtering on an
  22475. audio signal.
  22476. @see IIRFilterAudioSource
  22477. */
  22478. class JUCE_API IIRFilter
  22479. {
  22480. public:
  22481. /** Creates a filter.
  22482. Initially the filter is inactive, so will have no effect on samples that
  22483. you process with it. Use the appropriate method to turn it into the type
  22484. of filter needed.
  22485. */
  22486. IIRFilter() throw();
  22487. /** Creates a copy of another filter. */
  22488. IIRFilter (const IIRFilter& other) throw();
  22489. /** Destructor. */
  22490. ~IIRFilter() throw();
  22491. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  22492. Note that this clears the processing state, but the type of filter and
  22493. its coefficients aren't changed. To put a filter into an inactive state, use
  22494. the makeInactive() method.
  22495. */
  22496. void reset() throw();
  22497. /** Performs the filter operation on the given set of samples.
  22498. */
  22499. void processSamples (float* const samples,
  22500. const int numSamples) throw();
  22501. /** Processes a single sample, without any locking or checking.
  22502. Use this if you need fast processing of a single value, but be aware that
  22503. this isn't thread-safe in the way that processSamples() is.
  22504. */
  22505. float processSingleSampleRaw (const float sample) throw();
  22506. /** Sets the filter up to act as a low-pass filter.
  22507. */
  22508. void makeLowPass (const double sampleRate,
  22509. const double frequency) throw();
  22510. /** Sets the filter up to act as a high-pass filter.
  22511. */
  22512. void makeHighPass (const double sampleRate,
  22513. const double frequency) throw();
  22514. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  22515. The gain is a scale factor that the low frequencies are multiplied by, so values
  22516. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  22517. attenuate them.
  22518. */
  22519. void makeLowShelf (const double sampleRate,
  22520. const double cutOffFrequency,
  22521. const double Q,
  22522. const float gainFactor) throw();
  22523. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  22524. The gain is a scale factor that the high frequencies are multiplied by, so values
  22525. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  22526. attenuate them.
  22527. */
  22528. void makeHighShelf (const double sampleRate,
  22529. const double cutOffFrequency,
  22530. const double Q,
  22531. const float gainFactor) throw();
  22532. /** Sets the filter up to act as a band pass filter centred around a
  22533. frequency, with a variable Q and gain.
  22534. The gain is a scale factor that the centre frequencies are multiplied by, so
  22535. values greater than 1.0 will boost the centre frequencies, values less than
  22536. 1.0 will attenuate them.
  22537. */
  22538. void makeBandPass (const double sampleRate,
  22539. const double centreFrequency,
  22540. const double Q,
  22541. const float gainFactor) throw();
  22542. /** Clears the filter's coefficients so that it becomes inactive.
  22543. */
  22544. void makeInactive() throw();
  22545. /** Makes this filter duplicate the set-up of another one.
  22546. */
  22547. void copyCoefficientsFrom (const IIRFilter& other) throw();
  22548. juce_UseDebuggingNewOperator
  22549. protected:
  22550. CriticalSection processLock;
  22551. void setCoefficients (double c1, double c2, double c3,
  22552. double c4, double c5, double c6) throw();
  22553. bool active;
  22554. float coefficients[6];
  22555. float x1, x2, y1, y2;
  22556. // (use the copyCoefficientsFrom() method instead of this operator)
  22557. const IIRFilter& operator= (const IIRFilter&);
  22558. };
  22559. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  22560. /********* End of inlined file: juce_IIRFilter.h *********/
  22561. /**
  22562. An AudioSource that performs an IIR filter on another source.
  22563. */
  22564. class JUCE_API IIRFilterAudioSource : public AudioSource
  22565. {
  22566. public:
  22567. /** Creates a IIRFilterAudioSource for a given input source.
  22568. @param inputSource the input source to read from
  22569. @param deleteInputWhenDeleted if true, the input source will be deleted when
  22570. this object is deleted
  22571. */
  22572. IIRFilterAudioSource (AudioSource* const inputSource,
  22573. const bool deleteInputWhenDeleted);
  22574. /** Destructor. */
  22575. ~IIRFilterAudioSource();
  22576. /** Changes the filter to use the same parameters as the one being passed in.
  22577. */
  22578. void setFilterParameters (const IIRFilter& newSettings);
  22579. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22580. void releaseResources();
  22581. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22582. juce_UseDebuggingNewOperator
  22583. private:
  22584. AudioSource* const input;
  22585. const bool deleteInputWhenDeleted;
  22586. OwnedArray <IIRFilter> iirFilters;
  22587. IIRFilterAudioSource (const IIRFilterAudioSource&);
  22588. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  22589. };
  22590. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22591. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  22592. #endif
  22593. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22594. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  22595. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22596. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22597. /**
  22598. An AudioSource that mixes together the output of a set of other AudioSources.
  22599. Input sources can be added and removed while the mixer is running as long as their
  22600. prepareToPlay() and releaseResources() methods are called before and after adding
  22601. them to the mixer.
  22602. */
  22603. class JUCE_API MixerAudioSource : public AudioSource
  22604. {
  22605. public:
  22606. /** Creates a MixerAudioSource.
  22607. */
  22608. MixerAudioSource();
  22609. /** Destructor. */
  22610. ~MixerAudioSource();
  22611. /** Adds an input source to the mixer.
  22612. If the mixer is running you'll need to make sure that the input source
  22613. is ready to play by calling its prepareToPlay() method before adding it.
  22614. If the mixer is stopped, then its input sources will be automatically
  22615. prepared when the mixer's prepareToPlay() method is called.
  22616. @param newInput the source to add to the mixer
  22617. @param deleteWhenRemoved if true, then this source will be deleted when
  22618. the mixer is deleted or when removeAllInputs() is
  22619. called (unless the source is previously removed
  22620. with the removeInputSource method)
  22621. */
  22622. void addInputSource (AudioSource* newInput,
  22623. const bool deleteWhenRemoved);
  22624. /** Removes an input source.
  22625. If the mixer is running, this will remove the source but not call its
  22626. releaseResources() method, so the caller might want to do this manually.
  22627. @param input the source to remove
  22628. @param deleteSource whether to delete this source after it's been removed
  22629. */
  22630. void removeInputSource (AudioSource* input,
  22631. const bool deleteSource);
  22632. /** Removes all the input sources.
  22633. If the mixer is running, this will remove the sources but not call their
  22634. releaseResources() method, so the caller might want to do this manually.
  22635. Any sources which were added with the deleteWhenRemoved flag set will be
  22636. deleted by this method.
  22637. */
  22638. void removeAllInputs();
  22639. /** Implementation of the AudioSource method.
  22640. This will call prepareToPlay() on all its input sources.
  22641. */
  22642. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22643. /** Implementation of the AudioSource method.
  22644. This will call releaseResources() on all its input sources.
  22645. */
  22646. void releaseResources();
  22647. /** Implementation of the AudioSource method. */
  22648. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22649. juce_UseDebuggingNewOperator
  22650. private:
  22651. VoidArray inputs;
  22652. BitArray inputsToDelete;
  22653. CriticalSection lock;
  22654. AudioSampleBuffer tempBuffer;
  22655. double currentSampleRate;
  22656. int bufferSizeExpected;
  22657. MixerAudioSource (const MixerAudioSource&);
  22658. const MixerAudioSource& operator= (const MixerAudioSource&);
  22659. };
  22660. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22661. /********* End of inlined file: juce_MixerAudioSource.h *********/
  22662. #endif
  22663. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22664. #endif
  22665. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22666. #endif
  22667. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22668. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  22669. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22670. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22671. /**
  22672. A simple AudioSource that generates a sine wave.
  22673. */
  22674. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  22675. {
  22676. public:
  22677. /** Creates a ToneGeneratorAudioSource. */
  22678. ToneGeneratorAudioSource();
  22679. /** Destructor. */
  22680. ~ToneGeneratorAudioSource();
  22681. /** Sets the signal's amplitude. */
  22682. void setAmplitude (const float newAmplitude);
  22683. /** Sets the signal's frequency. */
  22684. void setFrequency (const double newFrequencyHz);
  22685. /** Implementation of the AudioSource method. */
  22686. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22687. /** Implementation of the AudioSource method. */
  22688. void releaseResources();
  22689. /** Implementation of the AudioSource method. */
  22690. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22691. juce_UseDebuggingNewOperator
  22692. private:
  22693. double frequency, sampleRate;
  22694. double currentPhase, phasePerSample;
  22695. float amplitude;
  22696. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  22697. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  22698. };
  22699. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22700. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  22701. #endif
  22702. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  22703. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  22704. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  22705. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  22706. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  22707. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  22708. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  22709. class AudioDeviceManager;
  22710. class Component;
  22711. /**
  22712. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  22713. To get a list of available audio driver types, use the createDeviceTypes()
  22714. method. Each of the objects returned can then be used to list the available
  22715. devices of that type. E.g.
  22716. @code
  22717. OwnedArray <AudioIODeviceType> types;
  22718. AudioIODeviceType::createDeviceTypes (types);
  22719. for (int i = 0; i < types.size(); ++i)
  22720. {
  22721. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  22722. types[i]->scanForDevices(); // This must be called before getting the list of devices
  22723. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  22724. for (int j = 0; j < deviceNames.size(); ++j)
  22725. {
  22726. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  22727. ...
  22728. }
  22729. }
  22730. @endcode
  22731. For an easier way of managing audio devices and their settings, have a look at the
  22732. AudioDeviceManager class.
  22733. @see AudioIODevice, AudioDeviceManager
  22734. */
  22735. class JUCE_API AudioIODeviceType
  22736. {
  22737. public:
  22738. /** Returns the name of this type of driver that this object manages.
  22739. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  22740. */
  22741. const String& getTypeName() const throw() { return typeName; }
  22742. /** Refreshes the object's cached list of known devices.
  22743. This must be called at least once before calling getDeviceNames() or any of
  22744. the other device creation methods.
  22745. */
  22746. virtual void scanForDevices() = 0;
  22747. /** Returns the list of available devices of this type.
  22748. The scanForDevices() method must have been called to create this list.
  22749. @param wantInputNames only really used by DirectSound where devices are split up
  22750. into inputs and outputs, this indicates whether to use
  22751. the input or output name to refer to a pair of devices.
  22752. */
  22753. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  22754. /** Returns the name of the default device.
  22755. This will be one of the names from the getDeviceNames() list.
  22756. @param forInput if true, this means that a default input device should be
  22757. returned; if false, it should return the default output
  22758. */
  22759. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  22760. /** Returns the index of a given device in the list of device names.
  22761. If asInput is true, it shows the index in the inputs list, otherwise it
  22762. looks for it in the outputs list.
  22763. */
  22764. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  22765. /** Returns true if two different devices can be used for the input and output.
  22766. */
  22767. virtual bool hasSeparateInputsAndOutputs() const = 0;
  22768. /** Creates one of the devices of this type.
  22769. The deviceName must be one of the strings returned by getDeviceNames(), and
  22770. scanForDevices() must have been called before this method is used.
  22771. */
  22772. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  22773. const String& inputDeviceName) = 0;
  22774. struct DeviceSetupDetails
  22775. {
  22776. AudioDeviceManager* manager;
  22777. int minNumInputChannels, maxNumInputChannels;
  22778. int minNumOutputChannels, maxNumOutputChannels;
  22779. bool useStereoPairs;
  22780. };
  22781. /** Destructor. */
  22782. virtual ~AudioIODeviceType();
  22783. protected:
  22784. AudioIODeviceType (const tchar* const typeName);
  22785. private:
  22786. String typeName;
  22787. AudioIODeviceType (const AudioIODeviceType&);
  22788. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  22789. };
  22790. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  22791. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  22792. /********* Start of inlined file: juce_MidiInput.h *********/
  22793. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  22794. #define __JUCE_MIDIINPUT_JUCEHEADER__
  22795. /********* Start of inlined file: juce_MidiMessage.h *********/
  22796. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  22797. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  22798. /**
  22799. Encapsulates a MIDI message.
  22800. @see MidiMessageSequence, MidiOutput, MidiInput
  22801. */
  22802. class JUCE_API MidiMessage
  22803. {
  22804. public:
  22805. /** Creates a 3-byte short midi message.
  22806. @param byte1 message byte 1
  22807. @param byte2 message byte 2
  22808. @param byte3 message byte 3
  22809. @param timeStamp the time to give the midi message - this value doesn't
  22810. use any particular units, so will be application-specific
  22811. */
  22812. MidiMessage (const int byte1,
  22813. const int byte2,
  22814. const int byte3,
  22815. const double timeStamp = 0) throw();
  22816. /** Creates a 2-byte short midi message.
  22817. @param byte1 message byte 1
  22818. @param byte2 message byte 2
  22819. @param timeStamp the time to give the midi message - this value doesn't
  22820. use any particular units, so will be application-specific
  22821. */
  22822. MidiMessage (const int byte1,
  22823. const int byte2,
  22824. const double timeStamp = 0) throw();
  22825. /** Creates a 1-byte short midi message.
  22826. @param byte1 message byte 1
  22827. @param timeStamp the time to give the midi message - this value doesn't
  22828. use any particular units, so will be application-specific
  22829. */
  22830. MidiMessage (const int byte1,
  22831. const double timeStamp = 0) throw();
  22832. /** Creates a midi message from a block of data. */
  22833. MidiMessage (const uint8* const data,
  22834. const int dataSize,
  22835. const double timeStamp = 0) throw();
  22836. /** Reads the next midi message from some data.
  22837. This will read as many bytes from a data stream as it needs to make a
  22838. complete message, and will return the number of bytes it used. This lets
  22839. you read a sequence of midi messages from a file or stream.
  22840. @param data the data to read from
  22841. @param size the maximum number of bytes it's allowed to read
  22842. @param numBytesUsed returns the number of bytes that were actually needed
  22843. @param lastStatusByte in a sequence of midi messages, the initial byte
  22844. can be dropped from a message if it's the same as the
  22845. first byte of the previous message, so this lets you
  22846. supply the byte to use if the first byte of the message
  22847. has in fact been dropped.
  22848. @param timeStamp the time to give the midi message - this value doesn't
  22849. use any particular units, so will be application-specific
  22850. */
  22851. MidiMessage (const uint8* data,
  22852. int size,
  22853. int& numBytesUsed,
  22854. uint8 lastStatusByte,
  22855. double timeStamp = 0) throw();
  22856. /** Creates a copy of another midi message. */
  22857. MidiMessage (const MidiMessage& other) throw();
  22858. /** Creates a copy of another midi message, with a different timestamp. */
  22859. MidiMessage (const MidiMessage& other,
  22860. const double newTimeStamp) throw();
  22861. /** Destructor. */
  22862. ~MidiMessage() throw();
  22863. /** Copies this message from another one. */
  22864. const MidiMessage& operator= (const MidiMessage& other) throw();
  22865. /** Returns a pointer to the raw midi data.
  22866. @see getRawDataSize
  22867. */
  22868. uint8* getRawData() const throw() { return data; }
  22869. /** Returns the number of bytes of data in the message.
  22870. @see getRawData
  22871. */
  22872. int getRawDataSize() const throw() { return size; }
  22873. /** Returns the timestamp associated with this message.
  22874. The exact meaning of this time and its units will vary, as messages are used in
  22875. a variety of different contexts.
  22876. If you're getting the message from a midi file, this could be a time in seconds, or
  22877. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  22878. If the message is being used in a MidiBuffer, it might indicate the number of
  22879. audio samples from the start of the buffer.
  22880. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  22881. for details of the way that it initialises this value.
  22882. @see setTimeStamp, addToTimeStamp
  22883. */
  22884. double getTimeStamp() const throw() { return timeStamp; }
  22885. /** Changes the message's associated timestamp.
  22886. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  22887. @see addToTimeStamp, getTimeStamp
  22888. */
  22889. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  22890. /** Adds a value to the message's timestamp.
  22891. The units for the timestamp will be application-specific.
  22892. */
  22893. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  22894. /** Returns the midi channel associated with the message.
  22895. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  22896. if it's a sysex)
  22897. @see isForChannel, setChannel
  22898. */
  22899. int getChannel() const throw();
  22900. /** Returns true if the message applies to the given midi channel.
  22901. @param channelNumber the channel number to look for, in the range 1 to 16
  22902. @see getChannel, setChannel
  22903. */
  22904. bool isForChannel (const int channelNumber) const throw();
  22905. /** Changes the message's midi channel.
  22906. This won't do anything for non-channel messages like sysexes.
  22907. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  22908. */
  22909. void setChannel (const int newChannelNumber) throw();
  22910. /** Returns true if this is a system-exclusive message.
  22911. */
  22912. bool isSysEx() const throw();
  22913. /** Returns a pointer to the sysex data inside the message.
  22914. If this event isn't a sysex event, it'll return 0.
  22915. @see getSysExDataSize
  22916. */
  22917. const uint8* getSysExData() const throw();
  22918. /** Returns the size of the sysex data.
  22919. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  22920. @see getSysExData
  22921. */
  22922. int getSysExDataSize() const throw();
  22923. /** Returns true if this message is a 'key-down' event.
  22924. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  22925. velocity 0, it will still be considered to be a note-on and the
  22926. method will return true. If returnTrueForVelocity0 is false, then
  22927. if this is a note-on event with velocity 0, it'll be regarded as
  22928. a note-off, and the method will return false
  22929. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  22930. */
  22931. bool isNoteOn (const bool returnTrueForVelocity0 = false) const throw();
  22932. /** Creates a key-down message (using a floating-point velocity).
  22933. @param channel the midi channel, in the range 1 to 16
  22934. @param noteNumber the key number, 0 to 127
  22935. @param velocity in the range 0 to 1.0
  22936. @see isNoteOn
  22937. */
  22938. static const MidiMessage noteOn (const int channel,
  22939. const int noteNumber,
  22940. const float velocity) throw();
  22941. /** Creates a key-down message (using an integer velocity).
  22942. @param channel the midi channel, in the range 1 to 16
  22943. @param noteNumber the key number, 0 to 127
  22944. @param velocity in the range 0 to 127
  22945. @see isNoteOn
  22946. */
  22947. static const MidiMessage noteOn (const int channel,
  22948. const int noteNumber,
  22949. const uint8 velocity) throw();
  22950. /** Returns true if this message is a 'key-up' event.
  22951. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  22952. for a note-on event with a velocity of 0.
  22953. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  22954. */
  22955. bool isNoteOff (const bool returnTrueForNoteOnVelocity0 = true) const throw();
  22956. /** Creates a key-up message.
  22957. @param channel the midi channel, in the range 1 to 16
  22958. @param noteNumber the key number, 0 to 127
  22959. @see isNoteOff
  22960. */
  22961. static const MidiMessage noteOff (const int channel,
  22962. const int noteNumber) throw();
  22963. /** Returns true if this message is a 'key-down' or 'key-up' event.
  22964. @see isNoteOn, isNoteOff
  22965. */
  22966. bool isNoteOnOrOff() const throw();
  22967. /** Returns the midi note number for note-on and note-off messages.
  22968. If the message isn't a note-on or off, the value returned will be
  22969. meaningless.
  22970. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  22971. */
  22972. int getNoteNumber() const throw();
  22973. /** Changes the midi note number of a note-on or note-off message.
  22974. If the message isn't a note on or off, this will do nothing.
  22975. */
  22976. void setNoteNumber (const int newNoteNumber) throw();
  22977. /** Returns the velocity of a note-on or note-off message.
  22978. The value returned will be in the range 0 to 127.
  22979. If the message isn't a note-on or off event, it will return 0.
  22980. @see getFloatVelocity
  22981. */
  22982. uint8 getVelocity() const throw();
  22983. /** Returns the velocity of a note-on or note-off message.
  22984. The value returned will be in the range 0 to 1.0
  22985. If the message isn't a note-on or off event, it will return 0.
  22986. @see getVelocity, setVelocity
  22987. */
  22988. float getFloatVelocity() const throw();
  22989. /** Changes the velocity of a note-on or note-off message.
  22990. If the message isn't a note on or off, this will do nothing.
  22991. @param newVelocity the new velocity, in the range 0 to 1.0
  22992. @see getFloatVelocity, multiplyVelocity
  22993. */
  22994. void setVelocity (const float newVelocity) throw();
  22995. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  22996. If the message isn't a note on or off, this will do nothing.
  22997. @param scaleFactor the value by which to multiply the velocity
  22998. @see setVelocity
  22999. */
  23000. void multiplyVelocity (const float scaleFactor) throw();
  23001. /** Returns true if the message is a program (patch) change message.
  23002. @see getProgramChangeNumber, getGMInstrumentName
  23003. */
  23004. bool isProgramChange() const throw();
  23005. /** Returns the new program number of a program change message.
  23006. If the message isn't a program change, the value returned will be
  23007. nonsense.
  23008. @see isProgramChange, getGMInstrumentName
  23009. */
  23010. int getProgramChangeNumber() const throw();
  23011. /** Creates a program-change message.
  23012. @param channel the midi channel, in the range 1 to 16
  23013. @param programNumber the midi program number, 0 to 127
  23014. @see isProgramChange, getGMInstrumentName
  23015. */
  23016. static const MidiMessage programChange (const int channel,
  23017. const int programNumber) throw();
  23018. /** Returns true if the message is a pitch-wheel move.
  23019. @see getPitchWheelValue, pitchWheel
  23020. */
  23021. bool isPitchWheel() const throw();
  23022. /** Returns the pitch wheel position from a pitch-wheel move message.
  23023. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  23024. If called for messages which aren't pitch wheel events, the number returned will be
  23025. nonsense.
  23026. @see isPitchWheel
  23027. */
  23028. int getPitchWheelValue() const throw();
  23029. /** Creates a pitch-wheel move message.
  23030. @param channel the midi channel, in the range 1 to 16
  23031. @param position the wheel position, in the range 0 to 16383
  23032. @see isPitchWheel
  23033. */
  23034. static const MidiMessage pitchWheel (const int channel,
  23035. const int position) throw();
  23036. /** Returns true if the message is an aftertouch event.
  23037. For aftertouch events, use the getNoteNumber() method to find out the key
  23038. that it applies to, and getAftertouchValue() to find out the amount. Use
  23039. getChannel() to find out the channel.
  23040. @see getAftertouchValue, getNoteNumber
  23041. */
  23042. bool isAftertouch() const throw();
  23043. /** Returns the amount of aftertouch from an aftertouch messages.
  23044. The value returned is in the range 0 to 127, and will be nonsense for messages
  23045. other than aftertouch messages.
  23046. @see isAftertouch
  23047. */
  23048. int getAfterTouchValue() const throw();
  23049. /** Creates an aftertouch message.
  23050. @param channel the midi channel, in the range 1 to 16
  23051. @param noteNumber the key number, 0 to 127
  23052. @param aftertouchAmount the amount of aftertouch, 0 to 127
  23053. @see isAftertouch
  23054. */
  23055. static const MidiMessage aftertouchChange (const int channel,
  23056. const int noteNumber,
  23057. const int aftertouchAmount) throw();
  23058. /** Returns true if the message is a channel-pressure change event.
  23059. This is like aftertouch, but common to the whole channel rather than a specific
  23060. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  23061. to find out the channel.
  23062. @see channelPressureChange
  23063. */
  23064. bool isChannelPressure() const throw();
  23065. /** Returns the pressure from a channel pressure change message.
  23066. @returns the pressure, in the range 0 to 127
  23067. @see isChannelPressure, channelPressureChange
  23068. */
  23069. int getChannelPressureValue() const throw();
  23070. /** Creates a channel-pressure change event.
  23071. @param channel the midi channel: 1 to 16
  23072. @param pressure the pressure, 0 to 127
  23073. @see isChannelPressure
  23074. */
  23075. static const MidiMessage channelPressureChange (const int channel,
  23076. const int pressure) throw();
  23077. /** Returns true if this is a midi controller message.
  23078. @see getControllerNumber, getControllerValue, controllerEvent
  23079. */
  23080. bool isController() const throw();
  23081. /** Returns the controller number of a controller message.
  23082. The name of the controller can be looked up using the getControllerName() method.
  23083. Note that the value returned is invalid for messages that aren't controller changes.
  23084. @see isController, getControllerName, getControllerValue
  23085. */
  23086. int getControllerNumber() const throw();
  23087. /** Returns the controller value from a controller message.
  23088. A value 0 to 127 is returned to indicate the new controller position.
  23089. Note that the value returned is invalid for messages that aren't controller changes.
  23090. @see isController, getControllerNumber
  23091. */
  23092. int getControllerValue() const throw();
  23093. /** Creates a controller message.
  23094. @param channel the midi channel, in the range 1 to 16
  23095. @param controllerType the type of controller
  23096. @param value the controller value
  23097. @see isController
  23098. */
  23099. static const MidiMessage controllerEvent (const int channel,
  23100. const int controllerType,
  23101. const int value) throw();
  23102. /** Checks whether this message is an all-notes-off message.
  23103. @see allNotesOff
  23104. */
  23105. bool isAllNotesOff() const throw();
  23106. /** Checks whether this message is an all-sound-off message.
  23107. @see allSoundOff
  23108. */
  23109. bool isAllSoundOff() const throw();
  23110. /** Creates an all-notes-off message.
  23111. @param channel the midi channel, in the range 1 to 16
  23112. @see isAllNotesOff
  23113. */
  23114. static const MidiMessage allNotesOff (const int channel) throw();
  23115. /** Creates an all-sound-off message.
  23116. @param channel the midi channel, in the range 1 to 16
  23117. @see isAllSoundOff
  23118. */
  23119. static const MidiMessage allSoundOff (const int channel) throw();
  23120. /** Creates an all-controllers-off message.
  23121. @param channel the midi channel, in the range 1 to 16
  23122. */
  23123. static const MidiMessage allControllersOff (const int channel) throw();
  23124. /** Returns true if this event is a meta-event.
  23125. Meta-events are things like tempo changes, track names, etc.
  23126. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  23127. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  23128. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  23129. */
  23130. bool isMetaEvent() const throw();
  23131. /** Returns a meta-event's type number.
  23132. If the message isn't a meta-event, this will return -1.
  23133. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  23134. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  23135. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  23136. */
  23137. int getMetaEventType() const throw();
  23138. /** Returns a pointer to the data in a meta-event.
  23139. @see isMetaEvent, getMetaEventLength
  23140. */
  23141. const uint8* getMetaEventData() const throw();
  23142. /** Returns the length of the data for a meta-event.
  23143. @see isMetaEvent, getMetaEventData
  23144. */
  23145. int getMetaEventLength() const throw();
  23146. /** Returns true if this is a 'track' meta-event. */
  23147. bool isTrackMetaEvent() const throw();
  23148. /** Returns true if this is an 'end-of-track' meta-event. */
  23149. bool isEndOfTrackMetaEvent() const throw();
  23150. /** Creates an end-of-track meta-event.
  23151. @see isEndOfTrackMetaEvent
  23152. */
  23153. static const MidiMessage endOfTrack() throw();
  23154. /** Returns true if this is an 'track name' meta-event.
  23155. You can use the getTextFromTextMetaEvent() method to get the track's name.
  23156. */
  23157. bool isTrackNameEvent() const throw();
  23158. /** Returns true if this is a 'text' meta-event.
  23159. @see getTextFromTextMetaEvent
  23160. */
  23161. bool isTextMetaEvent() const throw();
  23162. /** Returns the text from a text meta-event.
  23163. @see isTextMetaEvent
  23164. */
  23165. const String getTextFromTextMetaEvent() const throw();
  23166. /** Returns true if this is a 'tempo' meta-event.
  23167. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  23168. */
  23169. bool isTempoMetaEvent() const throw();
  23170. /** Returns the tick length from a tempo meta-event.
  23171. @param timeFormat the 16-bit time format value from the midi file's header.
  23172. @returns the tick length (in seconds).
  23173. @see isTempoMetaEvent
  23174. */
  23175. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  23176. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  23177. @see isTempoMetaEvent, getTempoMetaEventTickLength
  23178. */
  23179. double getTempoSecondsPerQuarterNote() const throw();
  23180. /** Creates a tempo meta-event.
  23181. @see isTempoMetaEvent
  23182. */
  23183. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  23184. /** Returns true if this is a 'time-signature' meta-event.
  23185. @see getTimeSignatureInfo
  23186. */
  23187. bool isTimeSignatureMetaEvent() const throw();
  23188. /** Returns the time-signature values from a time-signature meta-event.
  23189. @see isTimeSignatureMetaEvent
  23190. */
  23191. void getTimeSignatureInfo (int& numerator,
  23192. int& denominator) const throw();
  23193. /** Creates a time-signature meta-event.
  23194. @see isTimeSignatureMetaEvent
  23195. */
  23196. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  23197. const int denominator) throw();
  23198. /** Returns true if this is a 'key-signature' meta-event.
  23199. @see getKeySignatureNumberOfSharpsOrFlats
  23200. */
  23201. bool isKeySignatureMetaEvent() const throw();
  23202. /** Returns the key from a key-signature meta-event.
  23203. @see isKeySignatureMetaEvent
  23204. */
  23205. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  23206. /** Returns true if this is a 'channel' meta-event.
  23207. A channel meta-event specifies the midi channel that should be used
  23208. for subsequent meta-events.
  23209. @see getMidiChannelMetaEventChannel
  23210. */
  23211. bool isMidiChannelMetaEvent() const throw();
  23212. /** Returns the channel number from a channel meta-event.
  23213. @returns the channel, in the range 1 to 16.
  23214. @see isMidiChannelMetaEvent
  23215. */
  23216. int getMidiChannelMetaEventChannel() const throw();
  23217. /** Creates a midi channel meta-event.
  23218. @param channel the midi channel, in the range 1 to 16
  23219. @see isMidiChannelMetaEvent
  23220. */
  23221. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  23222. /** Returns true if this is an active-sense message. */
  23223. bool isActiveSense() const throw();
  23224. /** Returns true if this is a midi start event.
  23225. @see midiStart
  23226. */
  23227. bool isMidiStart() const throw();
  23228. /** Creates a midi start event. */
  23229. static const MidiMessage midiStart() throw();
  23230. /** Returns true if this is a midi continue event.
  23231. @see midiContinue
  23232. */
  23233. bool isMidiContinue() const throw();
  23234. /** Creates a midi continue event. */
  23235. static const MidiMessage midiContinue() throw();
  23236. /** Returns true if this is a midi stop event.
  23237. @see midiStop
  23238. */
  23239. bool isMidiStop() const throw();
  23240. /** Creates a midi stop event. */
  23241. static const MidiMessage midiStop() throw();
  23242. /** Returns true if this is a midi clock event.
  23243. @see midiClock, songPositionPointer
  23244. */
  23245. bool isMidiClock() const throw();
  23246. /** Creates a midi clock event. */
  23247. static const MidiMessage midiClock() throw();
  23248. /** Returns true if this is a song-position-pointer message.
  23249. @see getSongPositionPointerMidiBeat, songPositionPointer
  23250. */
  23251. bool isSongPositionPointer() const throw();
  23252. /** Returns the midi beat-number of a song-position-pointer message.
  23253. @see isSongPositionPointer, songPositionPointer
  23254. */
  23255. int getSongPositionPointerMidiBeat() const throw();
  23256. /** Creates a song-position-pointer message.
  23257. The position is a number of midi beats from the start of the song, where 1 midi
  23258. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  23259. are 4 midi beats in a quarter-note.
  23260. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  23261. */
  23262. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  23263. /** Returns true if this is a quarter-frame midi timecode message.
  23264. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  23265. */
  23266. bool isQuarterFrame() const throw();
  23267. /** Returns the sequence number of a quarter-frame midi timecode message.
  23268. This will be a value between 0 and 7.
  23269. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  23270. */
  23271. int getQuarterFrameSequenceNumber() const throw();
  23272. /** Returns the value from a quarter-frame message.
  23273. This will be the lower nybble of the message's data-byte, a value
  23274. between 0 and 15
  23275. */
  23276. int getQuarterFrameValue() const throw();
  23277. /** Creates a quarter-frame MTC message.
  23278. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  23279. @param value a value 0 to 15 for the lower nybble of the message's data byte
  23280. */
  23281. static const MidiMessage quarterFrame (const int sequenceNumber,
  23282. const int value) throw();
  23283. /** SMPTE timecode types.
  23284. Used by the getFullFrameParameters() and fullFrame() methods.
  23285. */
  23286. enum SmpteTimecodeType
  23287. {
  23288. fps24 = 0,
  23289. fps25 = 1,
  23290. fps30drop = 2,
  23291. fps30 = 3
  23292. };
  23293. /** Returns true if this is a full-frame midi timecode message.
  23294. */
  23295. bool isFullFrame() const throw();
  23296. /** Extracts the timecode information from a full-frame midi timecode message.
  23297. You should only call this on messages where you've used isFullFrame() to
  23298. check that they're the right kind.
  23299. */
  23300. void getFullFrameParameters (int& hours,
  23301. int& minutes,
  23302. int& seconds,
  23303. int& frames,
  23304. SmpteTimecodeType& timecodeType) const throw();
  23305. /** Creates a full-frame MTC message.
  23306. */
  23307. static const MidiMessage fullFrame (const int hours,
  23308. const int minutes,
  23309. const int seconds,
  23310. const int frames,
  23311. SmpteTimecodeType timecodeType);
  23312. /** Types of MMC command.
  23313. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  23314. */
  23315. enum MidiMachineControlCommand
  23316. {
  23317. mmc_stop = 1,
  23318. mmc_play = 2,
  23319. mmc_deferredplay = 3,
  23320. mmc_fastforward = 4,
  23321. mmc_rewind = 5,
  23322. mmc_recordStart = 6,
  23323. mmc_recordStop = 7,
  23324. mmc_pause = 9
  23325. };
  23326. /** Checks whether this is an MMC message.
  23327. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  23328. */
  23329. bool isMidiMachineControlMessage() const throw();
  23330. /** For an MMC message, this returns its type.
  23331. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  23332. calling this method.
  23333. */
  23334. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  23335. /** Creates an MMC message.
  23336. */
  23337. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  23338. /** Checks whether this is an MMC "goto" message.
  23339. If it is, the parameters passed-in are set to the time that the message contains.
  23340. @see midiMachineControlGoto
  23341. */
  23342. bool isMidiMachineControlGoto (int& hours,
  23343. int& minutes,
  23344. int& seconds,
  23345. int& frames) const throw();
  23346. /** Creates an MMC "goto" message.
  23347. This messages tells the device to go to a specific frame.
  23348. @see isMidiMachineControlGoto
  23349. */
  23350. static const MidiMessage midiMachineControlGoto (int hours,
  23351. int minutes,
  23352. int seconds,
  23353. int frames);
  23354. /** Creates a master-volume change message.
  23355. @param volume the volume, 0 to 1.0
  23356. */
  23357. static const MidiMessage masterVolume (const float volume) throw();
  23358. /** Creates a system-exclusive message.
  23359. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  23360. */
  23361. static const MidiMessage createSysExMessage (const uint8* sysexData,
  23362. const int dataSize) throw();
  23363. /** Reads a midi variable-length integer.
  23364. @param data the data to read the number from
  23365. @param numBytesUsed on return, this will be set to the number of bytes that were read
  23366. */
  23367. static int readVariableLengthVal (const uint8* data,
  23368. int& numBytesUsed) throw();
  23369. /** Based on the first byte of a short midi message, this uses a lookup table
  23370. to return the message length (either 1, 2, or 3 bytes).
  23371. The value passed in must be 0x80 or higher.
  23372. */
  23373. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  23374. /** Returns the name of a midi note number.
  23375. E.g "C", "D#", etc.
  23376. @param noteNumber the midi note number, 0 to 127
  23377. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  23378. they'll be flattened, e.g. "Db"
  23379. @param includeOctaveNumber if true, the octave number will be appended to the string,
  23380. e.g. "C#4"
  23381. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  23382. number that will be used for middle C's octave
  23383. @see getMidiNoteInHertz
  23384. */
  23385. static const String getMidiNoteName (int noteNumber,
  23386. bool useSharps,
  23387. bool includeOctaveNumber,
  23388. int octaveNumForMiddleC) throw();
  23389. /** Returns the frequency of a midi note number.
  23390. @see getMidiNoteName
  23391. */
  23392. static const double getMidiNoteInHertz (int noteNumber) throw();
  23393. /** Returns the standard name of a GM instrument.
  23394. @param midiInstrumentNumber the program number 0 to 127
  23395. @see getProgramChangeNumber
  23396. */
  23397. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  23398. /** Returns the name of a bank of GM instruments.
  23399. @param midiBankNumber the bank, 0 to 15
  23400. */
  23401. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  23402. /** Returns the standard name of a channel 10 percussion sound.
  23403. @param midiNoteNumber the key number, 35 to 81
  23404. */
  23405. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  23406. /** Returns the name of a controller type number.
  23407. @see getControllerNumber
  23408. */
  23409. static const String getControllerName (int controllerNumber) throw();
  23410. juce_UseDebuggingNewOperator
  23411. private:
  23412. double timeStamp;
  23413. uint8* data;
  23414. int message, size;
  23415. };
  23416. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  23417. /********* End of inlined file: juce_MidiMessage.h *********/
  23418. class MidiInput;
  23419. /**
  23420. Receives midi messages from a midi input device.
  23421. This class is overridden to handle incoming midi messages. See the MidiInput
  23422. class for more details.
  23423. @see MidiInput
  23424. */
  23425. class JUCE_API MidiInputCallback
  23426. {
  23427. public:
  23428. /** Destructor. */
  23429. virtual ~MidiInputCallback() {}
  23430. /** Receives an incoming message.
  23431. A MidiInput object will call this method when a midi event arrives. It'll be
  23432. called on a high-priority system thread, so avoid doing anything time-consuming
  23433. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  23434. for queueing incoming messages for use later.
  23435. @param source the MidiInput object that generated the message
  23436. @param message the incoming message. The message's timestamp is set to a value
  23437. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  23438. time when the message arrived.
  23439. */
  23440. virtual void handleIncomingMidiMessage (MidiInput* source,
  23441. const MidiMessage& message) = 0;
  23442. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  23443. If a long sysex message is broken up into multiple packets, this callback is made
  23444. for each packet that arrives until the message is finished, at which point
  23445. the normal handleIncomingMidiMessage() callback will be made with the entire
  23446. message.
  23447. The message passed in will contain the start of a sysex, but won't be finished
  23448. with the terminating 0xf7 byte.
  23449. */
  23450. virtual void handlePartialSysexMessage (MidiInput* source,
  23451. const uint8* messageData,
  23452. const int numBytesSoFar,
  23453. const double timestamp)
  23454. {
  23455. // (this bit is just to avoid compiler warnings about unused variables)
  23456. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  23457. }
  23458. };
  23459. /**
  23460. Represents a midi input device.
  23461. To create one of these, use the static getDevices() method to find out what inputs are
  23462. available, and then use the openDevice() method to try to open one.
  23463. @see MidiOutput
  23464. */
  23465. class JUCE_API MidiInput
  23466. {
  23467. public:
  23468. /** Returns a list of the available midi input devices.
  23469. You can open one of the devices by passing its index into the
  23470. openDevice() method.
  23471. @see getDefaultDeviceIndex, openDevice
  23472. */
  23473. static const StringArray getDevices();
  23474. /** Returns the index of the default midi input device to use.
  23475. This refers to the index in the list returned by getDevices().
  23476. */
  23477. static int getDefaultDeviceIndex();
  23478. /** Tries to open one of the midi input devices.
  23479. This will return a MidiInput object if it manages to open it. You can then
  23480. call start() and stop() on this device, and delete it when no longer needed.
  23481. If the device can't be opened, this will return a null pointer.
  23482. @param deviceIndex the index of a device from the list returned by getDevices()
  23483. @param callback the object that will receive the midi messages from this device.
  23484. @see MidiInputCallback, getDevices
  23485. */
  23486. static MidiInput* openDevice (int deviceIndex,
  23487. MidiInputCallback* callback);
  23488. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  23489. /** This will try to create a new midi input device (Not available on Windows).
  23490. This will attempt to create a new midi input device with the specified name,
  23491. for other apps to connect to.
  23492. Returns 0 if a device can't be created.
  23493. @param deviceName the name to use for the new device
  23494. @param callback the object that will receive the midi messages from this device.
  23495. */
  23496. static MidiInput* createNewDevice (const String& deviceName,
  23497. MidiInputCallback* callback);
  23498. #endif
  23499. /** Destructor. */
  23500. virtual ~MidiInput();
  23501. /** Returns the name of this device.
  23502. */
  23503. virtual const String getName() const throw() { return name; }
  23504. /** Allows you to set a custom name for the device, in case you don't like the name
  23505. it was given when created.
  23506. */
  23507. virtual void setName (const String& newName) throw() { name = newName; }
  23508. /** Starts the device running.
  23509. After calling this, the device will start sending midi messages to the
  23510. MidiInputCallback object that was specified when the openDevice() method
  23511. was called.
  23512. @see stop
  23513. */
  23514. virtual void start();
  23515. /** Stops the device running.
  23516. @see start
  23517. */
  23518. virtual void stop();
  23519. juce_UseDebuggingNewOperator
  23520. protected:
  23521. String name;
  23522. void* internal;
  23523. MidiInput (const String& name);
  23524. MidiInput (const MidiInput&);
  23525. };
  23526. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  23527. /********* End of inlined file: juce_MidiInput.h *********/
  23528. /********* Start of inlined file: juce_MidiOutput.h *********/
  23529. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  23530. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  23531. /********* Start of inlined file: juce_MidiBuffer.h *********/
  23532. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  23533. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  23534. /**
  23535. Holds a sequence of time-stamped midi events.
  23536. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  23537. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  23538. @see MidiMessage
  23539. */
  23540. class JUCE_API MidiBuffer
  23541. {
  23542. public:
  23543. /** Creates an empty MidiBuffer. */
  23544. MidiBuffer() throw();
  23545. /** Creates a MidiBuffer containing a single midi message. */
  23546. MidiBuffer (const MidiMessage& message) throw();
  23547. /** Creates a copy of another MidiBuffer. */
  23548. MidiBuffer (const MidiBuffer& other) throw();
  23549. /** Makes a copy of another MidiBuffer. */
  23550. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  23551. /** Destructor */
  23552. ~MidiBuffer() throw();
  23553. /** Removes all events from the buffer. */
  23554. void clear() throw();
  23555. /** Removes all events between two times from the buffer.
  23556. All events for which (start <= event position < start + numSamples) will
  23557. be removed.
  23558. */
  23559. void clear (const int start,
  23560. const int numSamples) throw();
  23561. /** Returns true if the buffer is empty.
  23562. To actually retrieve the events, use a MidiBuffer::Iterator object
  23563. */
  23564. bool isEmpty() const throw();
  23565. /** Counts the number of events in the buffer.
  23566. This is actually quite a slow operation, as it has to iterate through all
  23567. the events, so you might prefer to call isEmpty() if that's all you need
  23568. to know.
  23569. */
  23570. int getNumEvents() const throw();
  23571. /** Adds an event to the buffer.
  23572. The sample number will be used to determine the position of the event in
  23573. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  23574. ignored.
  23575. If an event is added whose sample position is the same as one or more events
  23576. already in the buffer, the new event will be placed after the existing ones.
  23577. To retrieve events, use a MidiBuffer::Iterator object
  23578. */
  23579. void addEvent (const MidiMessage& midiMessage,
  23580. const int sampleNumber) throw();
  23581. /** Adds an event to the buffer from raw midi data.
  23582. The sample number will be used to determine the position of the event in
  23583. the buffer, which is always kept sorted.
  23584. If an event is added whose sample position is the same as one or more events
  23585. already in the buffer, the new event will be placed after the existing ones.
  23586. The event data will be inspected to calculate the number of bytes in length that
  23587. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  23588. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  23589. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  23590. add an event at all.
  23591. To retrieve events, use a MidiBuffer::Iterator object
  23592. */
  23593. void addEvent (const uint8* const rawMidiData,
  23594. const int maxBytesOfMidiData,
  23595. const int sampleNumber) throw();
  23596. /** Adds some events from another buffer to this one.
  23597. @param otherBuffer the buffer containing the events you want to add
  23598. @param startSample the lowest sample number in the source buffer for which
  23599. events should be added. Any source events whose timestamp is
  23600. less than this will be ignored
  23601. @param numSamples the valid range of samples from the source buffer for which
  23602. events should be added - i.e. events in the source buffer whose
  23603. timestamp is greater than or equal to (startSample + numSamples)
  23604. will be ignored. If this value is less than 0, all events after
  23605. startSample will be taken.
  23606. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  23607. that are added to this buffer
  23608. */
  23609. void addEvents (const MidiBuffer& otherBuffer,
  23610. const int startSample,
  23611. const int numSamples,
  23612. const int sampleDeltaToAdd) throw();
  23613. /** Returns the sample number of the first event in the buffer.
  23614. If the buffer's empty, this will just return 0.
  23615. */
  23616. int getFirstEventTime() const throw();
  23617. /** Returns the sample number of the last event in the buffer.
  23618. If the buffer's empty, this will just return 0.
  23619. */
  23620. int getLastEventTime() const throw();
  23621. /** Exchanges the contents of this buffer with another one.
  23622. This is a quick operation, because no memory allocating or copying is done, it
  23623. just swaps the internal state of the two buffers.
  23624. */
  23625. void swap (MidiBuffer& other);
  23626. /**
  23627. Used to iterate through the events in a MidiBuffer.
  23628. Note that altering the buffer while an iterator is using it isn't a
  23629. safe operation.
  23630. @see MidiBuffer
  23631. */
  23632. class Iterator
  23633. {
  23634. public:
  23635. /** Creates an Iterator for this MidiBuffer. */
  23636. Iterator (const MidiBuffer& buffer) throw();
  23637. /** Destructor. */
  23638. ~Iterator() throw();
  23639. /** Repositions the iterator so that the next event retrieved will be the first
  23640. one whose sample position is at greater than or equal to the given position.
  23641. */
  23642. void setNextSamplePosition (const int samplePosition) throw();
  23643. /** Retrieves a copy of the next event from the buffer.
  23644. @param result on return, this will be the message (the MidiMessage's timestamp
  23645. is not set)
  23646. @param samplePosition on return, this will be the position of the event
  23647. @returns true if an event was found, or false if the iterator has reached
  23648. the end of the buffer
  23649. */
  23650. bool getNextEvent (MidiMessage& result,
  23651. int& samplePosition) throw();
  23652. /** Retrieves the next event from the buffer.
  23653. @param midiData on return, this pointer will be set to a block of data containing
  23654. the midi message. Note that to make it fast, this is a pointer
  23655. directly into the MidiBuffer's internal data, so is only valid
  23656. temporarily until the MidiBuffer is altered.
  23657. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  23658. midi message
  23659. @param samplePosition on return, this will be the position of the event
  23660. @returns true if an event was found, or false if the iterator has reached
  23661. the end of the buffer
  23662. */
  23663. bool getNextEvent (const uint8* &midiData,
  23664. int& numBytesOfMidiData,
  23665. int& samplePosition) throw();
  23666. juce_UseDebuggingNewOperator
  23667. private:
  23668. const MidiBuffer& buffer;
  23669. const uint8* data;
  23670. Iterator (const Iterator&);
  23671. const Iterator& operator= (const Iterator&);
  23672. };
  23673. juce_UseDebuggingNewOperator
  23674. private:
  23675. friend class MidiBuffer::Iterator;
  23676. ArrayAllocationBase <uint8> data;
  23677. int bytesUsed;
  23678. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  23679. };
  23680. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  23681. /********* End of inlined file: juce_MidiBuffer.h *********/
  23682. /**
  23683. Represents a midi output device.
  23684. To create one of these, use the static getDevices() method to find out what
  23685. outputs are available, then use the openDevice() method to try to open one.
  23686. @see MidiInput
  23687. */
  23688. class JUCE_API MidiOutput : private Thread
  23689. {
  23690. public:
  23691. /** Returns a list of the available midi output devices.
  23692. You can open one of the devices by passing its index into the
  23693. openDevice() method.
  23694. @see getDefaultDeviceIndex, openDevice
  23695. */
  23696. static const StringArray getDevices();
  23697. /** Returns the index of the default midi output device to use.
  23698. This refers to the index in the list returned by getDevices().
  23699. */
  23700. static int getDefaultDeviceIndex();
  23701. /** Tries to open one of the midi output devices.
  23702. This will return a MidiOutput object if it manages to open it. You can then
  23703. send messages to this device, and delete it when no longer needed.
  23704. If the device can't be opened, this will return a null pointer.
  23705. @param deviceIndex the index of a device from the list returned by getDevices()
  23706. @see getDevices
  23707. */
  23708. static MidiOutput* openDevice (int deviceIndex);
  23709. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  23710. /** This will try to create a new midi output device (Not available on Windows).
  23711. This will attempt to create a new midi output device that other apps can connect
  23712. to and use as their midi input.
  23713. Returns 0 if a device can't be created.
  23714. @param deviceName the name to use for the new device
  23715. */
  23716. static MidiOutput* createNewDevice (const String& deviceName);
  23717. #endif
  23718. /** Destructor. */
  23719. virtual ~MidiOutput();
  23720. /** Makes this device output a midi message.
  23721. @see MidiMessage
  23722. */
  23723. virtual void sendMessageNow (const MidiMessage& message);
  23724. /** Sends a midi reset to the device. */
  23725. virtual void reset();
  23726. /** Returns the current volume setting for this device. */
  23727. virtual bool getVolume (float& leftVol,
  23728. float& rightVol);
  23729. /** Changes the overall volume for this device. */
  23730. virtual void setVolume (float leftVol,
  23731. float rightVol);
  23732. /** This lets you supply a block of messages that will be sent out at some point
  23733. in the future.
  23734. The MidiOutput class has an internal thread that can send out timestamped
  23735. messages - this appends a set of messages to its internal buffer, ready for
  23736. sending.
  23737. This will only work if you've already started the thread with startBackgroundThread().
  23738. A time is supplied, at which the block of messages should be sent. This time uses
  23739. the same time base as Time::getMillisecondCounter(), and must be in the future.
  23740. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  23741. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  23742. samplesPerSecondForBuffer value is needed to convert this sample position to a
  23743. real time.
  23744. */
  23745. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  23746. const double millisecondCounterToStartAt,
  23747. double samplesPerSecondForBuffer) throw();
  23748. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  23749. */
  23750. virtual void clearAllPendingMessages() throw();
  23751. /** Starts up a background thread so that the device can send blocks of data.
  23752. Call this to get the device ready, before using sendBlockOfMessages().
  23753. */
  23754. virtual void startBackgroundThread() throw();
  23755. /** Stops the background thread, and clears any pending midi events.
  23756. @see startBackgroundThread
  23757. */
  23758. virtual void stopBackgroundThread() throw();
  23759. juce_UseDebuggingNewOperator
  23760. protected:
  23761. void* internal;
  23762. struct PendingMessage
  23763. {
  23764. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  23765. MidiMessage message;
  23766. PendingMessage* next;
  23767. juce_UseDebuggingNewOperator
  23768. };
  23769. CriticalSection lock;
  23770. PendingMessage* firstMessage;
  23771. MidiOutput() throw();
  23772. MidiOutput (const MidiOutput&);
  23773. void run();
  23774. };
  23775. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  23776. /********* End of inlined file: juce_MidiOutput.h *********/
  23777. /********* Start of inlined file: juce_ComboBox.h *********/
  23778. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  23779. #define __JUCE_COMBOBOX_JUCEHEADER__
  23780. /********* Start of inlined file: juce_Label.h *********/
  23781. #ifndef __JUCE_LABEL_JUCEHEADER__
  23782. #define __JUCE_LABEL_JUCEHEADER__
  23783. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  23784. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23785. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23786. /**
  23787. Object for monitoring a component, and later testing whether it's still valid.
  23788. Slightly obscure, this one, but it's used internally for making sure that
  23789. after some callbacks, a component hasn't been deleted. It's more reliable than
  23790. just using isValidComponent(), which can provide false-positives if a new
  23791. component is created at the same memory location as an old one.
  23792. */
  23793. class JUCE_API ComponentDeletionWatcher
  23794. {
  23795. public:
  23796. /** Creates a watcher for a given component.
  23797. The component must be valid at the time it's passed in.
  23798. */
  23799. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  23800. /** Destructor. */
  23801. ~ComponentDeletionWatcher() throw();
  23802. /** Returns true if the component has been deleted since the time that this
  23803. object was created.
  23804. */
  23805. bool hasBeenDeleted() const throw();
  23806. /** Returns the component that's being watched, or null if it has been deleted. */
  23807. const Component* getComponent() const throw();
  23808. juce_UseDebuggingNewOperator
  23809. private:
  23810. const Component* const componentToWatch;
  23811. const uint32 componentUID;
  23812. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  23813. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  23814. };
  23815. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23816. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  23817. /********* Start of inlined file: juce_TextEditor.h *********/
  23818. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  23819. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  23820. /********* Start of inlined file: juce_Viewport.h *********/
  23821. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  23822. #define __JUCE_VIEWPORT_JUCEHEADER__
  23823. /********* Start of inlined file: juce_ScrollBar.h *********/
  23824. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  23825. #define __JUCE_SCROLLBAR_JUCEHEADER__
  23826. /********* Start of inlined file: juce_Button.h *********/
  23827. #ifndef __JUCE_BUTTON_JUCEHEADER__
  23828. #define __JUCE_BUTTON_JUCEHEADER__
  23829. /********* Start of inlined file: juce_TooltipWindow.h *********/
  23830. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23831. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23832. /********* Start of inlined file: juce_TooltipClient.h *********/
  23833. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23834. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23835. /**
  23836. Components that want to use pop-up tooltips should implement this interface.
  23837. A TooltipWindow will wait for the mouse to hover over a component that
  23838. implements the TooltipClient interface, and when it finds one, it will display
  23839. the tooltip returned by its getTooltip() method.
  23840. @see TooltipWindow, SettableTooltipClient
  23841. */
  23842. class JUCE_API TooltipClient
  23843. {
  23844. public:
  23845. /** Destructor. */
  23846. virtual ~TooltipClient() {}
  23847. /** Returns the string that this object wants to show as its tooltip. */
  23848. virtual const String getTooltip() = 0;
  23849. };
  23850. /**
  23851. An implementation of TooltipClient that stores the tooltip string and a method
  23852. for changing it.
  23853. This makes it easy to add a tooltip to a custom component, by simply adding this
  23854. as a base class and calling setTooltip().
  23855. Many of the Juce widgets already use this as a base class to implement their
  23856. tooltips.
  23857. @see TooltipClient, TooltipWindow
  23858. */
  23859. class JUCE_API SettableTooltipClient : public TooltipClient
  23860. {
  23861. public:
  23862. /** Destructor. */
  23863. virtual ~SettableTooltipClient() {}
  23864. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  23865. virtual const String getTooltip() { return tooltipString; }
  23866. juce_UseDebuggingNewOperator
  23867. protected:
  23868. String tooltipString;
  23869. };
  23870. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23871. /********* End of inlined file: juce_TooltipClient.h *********/
  23872. /**
  23873. A window that displays a pop-up tooltip when the mouse hovers over another component.
  23874. To enable tooltips in your app, just create a single instance of a TooltipWindow
  23875. object.
  23876. The TooltipWindow object will then stay invisible, waiting until the mouse
  23877. hovers for the specified length of time - it will then see if it's currently
  23878. over a component which implements the TooltipClient interface, and if so,
  23879. it will make itself visible to show the tooltip in the appropriate place.
  23880. @see TooltipClient, SettableTooltipClient
  23881. */
  23882. class JUCE_API TooltipWindow : public Component,
  23883. private Timer
  23884. {
  23885. public:
  23886. /** Creates a tooltip window.
  23887. Make sure your app only creates one instance of this class, otherwise you'll
  23888. get multiple overlaid tooltips appearing. The window will initially be invisible
  23889. and will make itself visible when it needs to display a tip.
  23890. To change the style of tooltips, see the LookAndFeel class for its tooltip
  23891. methods.
  23892. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  23893. otherwise the tooltip will be added to the given parent
  23894. component.
  23895. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  23896. before a tooltip will be shown
  23897. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  23898. */
  23899. TooltipWindow (Component* parentComponent = 0,
  23900. const int millisecondsBeforeTipAppears = 700);
  23901. /** Destructor. */
  23902. ~TooltipWindow();
  23903. /** Changes the time before the tip appears.
  23904. This lets you change the value that was set in the constructor.
  23905. */
  23906. void setMillisecondsBeforeTipAppears (const int newTimeMs = 700) throw();
  23907. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  23908. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23909. methods.
  23910. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23911. */
  23912. enum ColourIds
  23913. {
  23914. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  23915. textColourId = 0x1001c00, /**< The colour to use for the text. */
  23916. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  23917. };
  23918. juce_UseDebuggingNewOperator
  23919. private:
  23920. int millisecondsBeforeTipAppears;
  23921. int mouseX, mouseY, mouseClicks;
  23922. unsigned int lastCompChangeTime, lastHideTime;
  23923. Component* lastComponentUnderMouse;
  23924. bool changedCompsSinceShown;
  23925. String tipShowing, lastTipUnderMouse;
  23926. void paint (Graphics& g);
  23927. void mouseEnter (const MouseEvent& e);
  23928. void timerCallback();
  23929. static const String getTipFor (Component* const c);
  23930. void showFor (Component* const c, const String& tip);
  23931. void hide();
  23932. TooltipWindow (const TooltipWindow&);
  23933. const TooltipWindow& operator= (const TooltipWindow&);
  23934. };
  23935. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23936. /********* End of inlined file: juce_TooltipWindow.h *********/
  23937. class Button;
  23938. /**
  23939. Used to receive callbacks when a button is clicked.
  23940. @see Button::addButtonListener, Button::removeButtonListener
  23941. */
  23942. class JUCE_API ButtonListener
  23943. {
  23944. public:
  23945. /** Destructor. */
  23946. virtual ~ButtonListener() {}
  23947. /** Called when the button is clicked. */
  23948. virtual void buttonClicked (Button* button) = 0;
  23949. /** Called when the button's state changes. */
  23950. virtual void buttonStateChanged (Button*) {}
  23951. };
  23952. /**
  23953. A base class for buttons.
  23954. This contains all the logic for button behaviours such as enabling/disabling,
  23955. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  23956. and radio groups, etc.
  23957. @see TextButton, DrawableButton, ToggleButton
  23958. */
  23959. class JUCE_API Button : public Component,
  23960. public SettableTooltipClient,
  23961. public ApplicationCommandManagerListener,
  23962. public Value::Listener,
  23963. private KeyListener
  23964. {
  23965. protected:
  23966. /** Creates a button.
  23967. @param buttonName the text to put in the button (the component's name is also
  23968. initially set to this string, but these can be changed later
  23969. using the setName() and setButtonText() methods)
  23970. */
  23971. Button (const String& buttonName);
  23972. public:
  23973. /** Destructor. */
  23974. virtual ~Button();
  23975. /** Changes the button's text.
  23976. @see getButtonText
  23977. */
  23978. void setButtonText (const String& newText) throw();
  23979. /** Returns the text displayed in the button.
  23980. @see setButtonText
  23981. */
  23982. const String getButtonText() const throw() { return text; }
  23983. /** Returns true if the button is currently being held down by the mouse.
  23984. @see isOver
  23985. */
  23986. bool isDown() const throw();
  23987. /** Returns true if the mouse is currently over the button.
  23988. This will be also be true if the mouse is being held down.
  23989. @see isDown
  23990. */
  23991. bool isOver() const throw();
  23992. /** A button has an on/off state associated with it, and this changes that.
  23993. By default buttons are 'off' and for simple buttons that you click to perform
  23994. an action you won't change this. Toggle buttons, however will want to
  23995. change their state when turned on or off.
  23996. @param shouldBeOn whether to set the button's toggle state to be on or
  23997. off. If it's a member of a button group, this will
  23998. always try to turn it on, and to turn off any other
  23999. buttons in the group
  24000. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  24001. the button will be repainted but no notification will
  24002. be sent
  24003. @see getToggleState, setRadioGroupId
  24004. */
  24005. void setToggleState (const bool shouldBeOn,
  24006. const bool sendChangeNotification);
  24007. /** Returns true if the button in 'on'.
  24008. By default buttons are 'off' and for simple buttons that you click to perform
  24009. an action you won't change this. Toggle buttons, however will want to
  24010. change their state when turned on or off.
  24011. @see setToggleState
  24012. */
  24013. bool getToggleState() const throw() { return isOn.getValue(); }
  24014. /** Returns the Value object that represents the botton's toggle state.
  24015. You can use this Value object to connect the button's state to external values or setters,
  24016. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  24017. your own Value object.
  24018. @see getToggleState, Value
  24019. */
  24020. Value& getToggleStateValue() { return isOn; }
  24021. /** This tells the button to automatically flip the toggle state when
  24022. the button is clicked.
  24023. If set to true, then before the clicked() callback occurs, the toggle-state
  24024. of the button is flipped.
  24025. */
  24026. void setClickingTogglesState (const bool shouldToggle) throw();
  24027. /** Returns true if this button is set to be an automatic toggle-button.
  24028. This returns the last value that was passed to setClickingTogglesState().
  24029. */
  24030. bool getClickingTogglesState() const throw();
  24031. /** Enables the button to act as a member of a mutually-exclusive group
  24032. of 'radio buttons'.
  24033. If the group ID is set to a non-zero number, then this button will
  24034. act as part of a group of buttons with the same ID, only one of
  24035. which can be 'on' at the same time. Note that when it's part of
  24036. a group, clicking a toggle-button that's 'on' won't turn it off.
  24037. To find other buttons with the same ID, this button will search through
  24038. its sibling components for ToggleButtons, so all the buttons for a
  24039. particular group must be placed inside the same parent component.
  24040. Set the group ID back to zero if you want it to act as a normal toggle
  24041. button again.
  24042. @see getRadioGroupId
  24043. */
  24044. void setRadioGroupId (const int newGroupId);
  24045. /** Returns the ID of the group to which this button belongs.
  24046. (See setRadioGroupId() for an explanation of this).
  24047. */
  24048. int getRadioGroupId() const throw() { return radioGroupId; }
  24049. /** Registers a listener to receive events when this button's state changes.
  24050. If the listener is already registered, this will not register it again.
  24051. @see removeButtonListener
  24052. */
  24053. void addButtonListener (ButtonListener* const newListener) throw();
  24054. /** Removes a previously-registered button listener
  24055. @see addButtonListener
  24056. */
  24057. void removeButtonListener (ButtonListener* const listener) throw();
  24058. /** Causes the button to act as if it's been clicked.
  24059. This will asynchronously make the button draw itself going down and up, and
  24060. will then call back the clicked() method as if mouse was clicked on it.
  24061. @see clicked
  24062. */
  24063. virtual void triggerClick();
  24064. /** Sets a command ID for this button to automatically invoke when it's clicked.
  24065. When the button is pressed, it will use the given manager to trigger the
  24066. command ID.
  24067. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  24068. before this button is. To disable the command triggering, call this method and
  24069. pass 0 for the parameters.
  24070. If generateTooltip is true, then the button's tooltip will be automatically
  24071. generated based on the name of this command and its current shortcut key.
  24072. @see addShortcut, getCommandID
  24073. */
  24074. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  24075. const int commandID,
  24076. const bool generateTooltip);
  24077. /** Returns the command ID that was set by setCommandToTrigger().
  24078. */
  24079. int getCommandID() const throw() { return commandID; }
  24080. /** Assigns a shortcut key to trigger the button.
  24081. The button registers itself with its top-level parent component for keypresses.
  24082. Note that a different way of linking buttons to keypresses is by using the
  24083. setCommandToTrigger() method to invoke a command.
  24084. @see clearShortcuts
  24085. */
  24086. void addShortcut (const KeyPress& key);
  24087. /** Removes all key shortcuts that had been set for this button.
  24088. @see addShortcut
  24089. */
  24090. void clearShortcuts();
  24091. /** Returns true if the given keypress is a shortcut for this button.
  24092. @see addShortcut
  24093. */
  24094. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  24095. /** Sets an auto-repeat speed for the button when it is held down.
  24096. (Auto-repeat is disabled by default).
  24097. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  24098. triggering the next click. If this is zero, auto-repeat
  24099. is disabled
  24100. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  24101. triggered
  24102. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  24103. get faster, the longer the button is held down, up to the
  24104. minimum interval specified here
  24105. */
  24106. void setRepeatSpeed (const int initialDelayInMillisecs,
  24107. const int repeatDelayInMillisecs,
  24108. const int minimumDelayInMillisecs = -1) throw();
  24109. /** Sets whether the button click should happen when the mouse is pressed or released.
  24110. By default the button is only considered to have been clicked when the mouse is
  24111. released, but setting this to true will make it call the clicked() method as soon
  24112. as the button is pressed.
  24113. This is useful if the button is being used to show a pop-up menu, as it allows
  24114. the click to be used as a drag onto the menu.
  24115. */
  24116. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  24117. /** Returns the number of milliseconds since the last time the button
  24118. went into the 'down' state.
  24119. */
  24120. uint32 getMillisecondsSinceButtonDown() const throw();
  24121. /** (overridden from Component to do special stuff). */
  24122. void setVisible (bool shouldBeVisible);
  24123. /** Sets the tooltip for this button.
  24124. @see TooltipClient, TooltipWindow
  24125. */
  24126. void setTooltip (const String& newTooltip);
  24127. // (implementation of the TooltipClient method)
  24128. const String getTooltip();
  24129. /** A combination of these flags are used by setConnectedEdges().
  24130. */
  24131. enum ConnectedEdgeFlags
  24132. {
  24133. ConnectedOnLeft = 1,
  24134. ConnectedOnRight = 2,
  24135. ConnectedOnTop = 4,
  24136. ConnectedOnBottom = 8
  24137. };
  24138. /** Hints about which edges of the button might be connected to adjoining buttons.
  24139. The value passed in is a bitwise combination of any of the values in the
  24140. ConnectedEdgeFlags enum.
  24141. E.g. if you are placing two buttons adjacent to each other, you could use this to
  24142. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  24143. without rounded corners on the edges that connect. It's only a hint, so the
  24144. LookAndFeel can choose to ignore it if it's not relevent for this type of
  24145. button.
  24146. */
  24147. void setConnectedEdges (const int connectedEdgeFlags) throw();
  24148. /** Returns the set of flags passed into setConnectedEdges(). */
  24149. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  24150. /** Indicates whether the button adjoins another one on its left edge.
  24151. @see setConnectedEdges
  24152. */
  24153. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  24154. /** Indicates whether the button adjoins another one on its right edge.
  24155. @see setConnectedEdges
  24156. */
  24157. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  24158. /** Indicates whether the button adjoins another one on its top edge.
  24159. @see setConnectedEdges
  24160. */
  24161. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  24162. /** Indicates whether the button adjoins another one on its bottom edge.
  24163. @see setConnectedEdges
  24164. */
  24165. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  24166. /** Used by setState(). */
  24167. enum ButtonState
  24168. {
  24169. buttonNormal,
  24170. buttonOver,
  24171. buttonDown
  24172. };
  24173. /** Can be used to force the button into a particular state.
  24174. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  24175. from happening.
  24176. The state that you set here will only last until it is automatically changed when the mouse
  24177. enters or exits the button, or the mouse-button is pressed or released.
  24178. */
  24179. void setState (const ButtonState newState);
  24180. juce_UseDebuggingNewOperator
  24181. protected:
  24182. /** This method is called when the button has been clicked.
  24183. Subclasses can override this to perform whatever they actions they need
  24184. to do.
  24185. Alternatively, a ButtonListener can be added to the button, and these listeners
  24186. will be called when the click occurs.
  24187. @see triggerClick
  24188. */
  24189. virtual void clicked();
  24190. /** This method is called when the button has been clicked.
  24191. By default it just calls clicked(), but you might want to override it to handle
  24192. things like clicking when a modifier key is pressed, etc.
  24193. @see ModifierKeys
  24194. */
  24195. virtual void clicked (const ModifierKeys& modifiers);
  24196. /** Subclasses should override this to actually paint the button's contents.
  24197. It's better to use this than the paint method, because it gives you information
  24198. about the over/down state of the button.
  24199. @param g the graphics context to use
  24200. @param isMouseOverButton true if the button is either in the 'over' or
  24201. 'down' state
  24202. @param isButtonDown true if the button should be drawn in the 'down' position
  24203. */
  24204. virtual void paintButton (Graphics& g,
  24205. bool isMouseOverButton,
  24206. bool isButtonDown) = 0;
  24207. /** Called when the button's up/down/over state changes.
  24208. Subclasses can override this if they need to do something special when the button
  24209. goes up or down.
  24210. @see isDown, isOver
  24211. */
  24212. virtual void buttonStateChanged();
  24213. /** @internal */
  24214. virtual void internalClickCallback (const ModifierKeys& modifiers);
  24215. /** @internal */
  24216. void handleCommandMessage (int commandId);
  24217. /** @internal */
  24218. void mouseEnter (const MouseEvent& e);
  24219. /** @internal */
  24220. void mouseExit (const MouseEvent& e);
  24221. /** @internal */
  24222. void mouseDown (const MouseEvent& e);
  24223. /** @internal */
  24224. void mouseDrag (const MouseEvent& e);
  24225. /** @internal */
  24226. void mouseUp (const MouseEvent& e);
  24227. /** @internal */
  24228. bool keyPressed (const KeyPress& key);
  24229. /** @internal */
  24230. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  24231. /** @internal */
  24232. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  24233. /** @internal */
  24234. void paint (Graphics& g);
  24235. /** @internal */
  24236. void parentHierarchyChanged();
  24237. /** @internal */
  24238. void focusGained (FocusChangeType cause);
  24239. /** @internal */
  24240. void focusLost (FocusChangeType cause);
  24241. /** @internal */
  24242. void enablementChanged();
  24243. /** @internal */
  24244. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  24245. /** @internal */
  24246. void applicationCommandListChanged();
  24247. /** @internal */
  24248. void valueChanged (Value& value);
  24249. private:
  24250. Array <KeyPress> shortcuts;
  24251. Component* keySource;
  24252. String text;
  24253. SortedSet <void*> buttonListeners;
  24254. friend class InternalButtonRepeatTimer;
  24255. ScopedPointer <Timer> repeatTimer;
  24256. uint32 buttonPressTime, lastTimeCallbackTime;
  24257. ApplicationCommandManager* commandManagerToUse;
  24258. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  24259. int radioGroupId, commandID, connectedEdgeFlags;
  24260. ButtonState buttonState;
  24261. Value isOn;
  24262. bool lastToggleState : 1;
  24263. bool clickTogglesState : 1;
  24264. bool needsToRelease : 1;
  24265. bool needsRepainting : 1;
  24266. bool isKeyDown : 1;
  24267. bool triggerOnMouseDown : 1;
  24268. bool generateTooltip : 1;
  24269. void repeatTimerCallback() throw();
  24270. Timer& getRepeatTimer() throw();
  24271. ButtonState updateState (const MouseEvent* const e) throw();
  24272. bool isShortcutPressed() const throw();
  24273. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  24274. void flashButtonState() throw();
  24275. void sendClickMessage (const ModifierKeys& modifiers);
  24276. void sendStateMessage();
  24277. Button (const Button&);
  24278. const Button& operator= (const Button&);
  24279. };
  24280. #endif // __JUCE_BUTTON_JUCEHEADER__
  24281. /********* End of inlined file: juce_Button.h *********/
  24282. class ScrollBar;
  24283. /**
  24284. A class for receiving events from a ScrollBar.
  24285. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  24286. method, and it will be called when the bar's position changes.
  24287. @see ScrollBar::addListener, ScrollBar::removeListener
  24288. */
  24289. class JUCE_API ScrollBarListener
  24290. {
  24291. public:
  24292. /** Destructor. */
  24293. virtual ~ScrollBarListener() {}
  24294. /** Called when a ScrollBar is moved.
  24295. @param scrollBarThatHasMoved the bar that has moved
  24296. @param newRangeStart the new range start of this bar
  24297. */
  24298. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  24299. const double newRangeStart) = 0;
  24300. };
  24301. /**
  24302. A scrollbar component.
  24303. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  24304. sets the range of values it can represent. Then you can use setCurrentRange() to
  24305. change the position and size of the scrollbar's 'thumb'.
  24306. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  24307. the user moves it, and you can use the getCurrentRangeStart() to find out where
  24308. they moved it to.
  24309. The scrollbar will adjust its own visibility according to whether its thumb size
  24310. allows it to actually be scrolled.
  24311. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  24312. instead of handling a scrollbar directly.
  24313. @see ScrollBarListener
  24314. */
  24315. class JUCE_API ScrollBar : public Component,
  24316. public AsyncUpdater,
  24317. private Timer
  24318. {
  24319. public:
  24320. /** Creates a Scrollbar.
  24321. @param isVertical whether it should be a vertical or horizontal bar
  24322. @param buttonsAreVisible whether to show the up/down or left/right buttons
  24323. */
  24324. ScrollBar (const bool isVertical,
  24325. const bool buttonsAreVisible = true);
  24326. /** Destructor. */
  24327. ~ScrollBar();
  24328. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  24329. bool isVertical() const throw() { return vertical; }
  24330. /** Changes the scrollbar's direction.
  24331. You'll also need to resize the bar appropriately - this just changes its internal
  24332. layout.
  24333. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  24334. */
  24335. void setOrientation (const bool shouldBeVertical) throw();
  24336. /** Shows or hides the scrollbar's buttons. */
  24337. void setButtonVisibility (const bool buttonsAreVisible);
  24338. /** Tells the scrollbar whether to make itself invisible when not needed.
  24339. The default behaviour is for a scrollbar to become invisible when the thumb
  24340. fills the whole of its range (i.e. when it can't be moved). Setting this
  24341. value to false forces the bar to always be visible.
  24342. */
  24343. void setAutoHide (const bool shouldHideWhenFullRange);
  24344. /** Sets the minimum and maximum values that the bar will move between.
  24345. The bar's thumb will always be constrained so that the top of the thumb
  24346. will be >= minimum, and the bottom of the thumb <= maximum.
  24347. @see setCurrentRange
  24348. */
  24349. void setRangeLimits (const double minimum,
  24350. const double maximum) throw();
  24351. /** Returns the lower value that the thumb can be set to.
  24352. This is the value set by setRangeLimits().
  24353. */
  24354. double getMinimumRangeLimit() const throw() { return minimum; }
  24355. /** Returns the upper value that the thumb can be set to.
  24356. This is the value set by setRangeLimits().
  24357. */
  24358. double getMaximumRangeLimit() const throw() { return maximum; }
  24359. /** Changes the position of the scrollbar's 'thumb'.
  24360. This sets both the position and size of the thumb - to just set the position without
  24361. changing the size, you can use setCurrentRangeStart().
  24362. If this method call actually changes the scrollbar's position, it will trigger an
  24363. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  24364. are registered.
  24365. @param newStart the top (or left) of the thumb, in the range
  24366. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  24367. value is beyond these limits, it will be clipped.
  24368. @param newSize the size of the thumb, such that
  24369. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  24370. size is beyond these limits, it will be clipped.
  24371. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  24372. */
  24373. void setCurrentRange (double newStart,
  24374. double newSize) throw();
  24375. /** Moves the bar's thumb position.
  24376. This will move the thumb position without changing the thumb size. Note
  24377. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  24378. If this method call actually changes the scrollbar's position, it will trigger an
  24379. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  24380. are registered.
  24381. @see setCurrentRange
  24382. */
  24383. void setCurrentRangeStart (double newStart) throw();
  24384. /** Returns the position of the top of the thumb.
  24385. @see setCurrentRangeStart
  24386. */
  24387. double getCurrentRangeStart() const throw() { return rangeStart; }
  24388. /** Returns the current size of the thumb.
  24389. @see setCurrentRange
  24390. */
  24391. double getCurrentRangeSize() const throw() { return rangeSize; }
  24392. /** Sets the amount by which the up and down buttons will move the bar.
  24393. The value here is in terms of the total range, and is added or subtracted
  24394. from the thumb position when the user clicks an up/down (or left/right) button.
  24395. */
  24396. void setSingleStepSize (const double newSingleStepSize) throw();
  24397. /** Moves the scrollbar by a number of single-steps.
  24398. This will move the bar by a multiple of its single-step interval (as
  24399. specified using the setSingleStepSize() method).
  24400. A positive value here will move the bar down or to the right, a negative
  24401. value moves it up or to the left.
  24402. */
  24403. void moveScrollbarInSteps (const int howManySteps) throw();
  24404. /** Moves the scroll bar up or down in pages.
  24405. This will move the bar by a multiple of its current thumb size, effectively
  24406. doing a page-up or down.
  24407. A positive value here will move the bar down or to the right, a negative
  24408. value moves it up or to the left.
  24409. */
  24410. void moveScrollbarInPages (const int howManyPages) throw();
  24411. /** Scrolls to the top (or left).
  24412. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  24413. */
  24414. void scrollToTop() throw();
  24415. /** Scrolls to the bottom (or right).
  24416. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  24417. */
  24418. void scrollToBottom() throw();
  24419. /** Changes the delay before the up and down buttons autorepeat when they are held
  24420. down.
  24421. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  24422. @see Button::setRepeatSpeed
  24423. */
  24424. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  24425. const int repeatDelayInMillisecs,
  24426. const int minimumDelayInMillisecs = -1) throw();
  24427. /** A set of colour IDs to use to change the colour of various aspects of the component.
  24428. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24429. methods.
  24430. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24431. */
  24432. enum ColourIds
  24433. {
  24434. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  24435. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  24436. 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. */
  24437. };
  24438. /** Registers a listener that will be called when the scrollbar is moved. */
  24439. void addListener (ScrollBarListener* const listener) throw();
  24440. /** Deregisters a previously-registered listener. */
  24441. void removeListener (ScrollBarListener* const listener) throw();
  24442. /** @internal */
  24443. bool keyPressed (const KeyPress& key);
  24444. /** @internal */
  24445. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24446. /** @internal */
  24447. void lookAndFeelChanged();
  24448. /** @internal */
  24449. void handleAsyncUpdate();
  24450. /** @internal */
  24451. void mouseDown (const MouseEvent& e);
  24452. /** @internal */
  24453. void mouseDrag (const MouseEvent& e);
  24454. /** @internal */
  24455. void mouseUp (const MouseEvent& e);
  24456. /** @internal */
  24457. void paint (Graphics& g);
  24458. /** @internal */
  24459. void resized();
  24460. juce_UseDebuggingNewOperator
  24461. private:
  24462. double minimum, maximum;
  24463. double rangeStart, rangeSize;
  24464. double singleStepSize, dragStartRange;
  24465. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  24466. int dragStartMousePos, lastMousePos;
  24467. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  24468. bool vertical, isDraggingThumb, alwaysVisible;
  24469. Button* upButton;
  24470. Button* downButton;
  24471. SortedSet <void*> listeners;
  24472. void updateThumbPosition() throw();
  24473. void timerCallback();
  24474. ScrollBar (const ScrollBar&);
  24475. const ScrollBar& operator= (const ScrollBar&);
  24476. };
  24477. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  24478. /********* End of inlined file: juce_ScrollBar.h *********/
  24479. /**
  24480. A Viewport is used to contain a larger child component, and allows the child
  24481. to be automatically scrolled around.
  24482. To use a Viewport, just create one and set the component that goes inside it
  24483. using the setViewedComponent() method. When the child component changes size,
  24484. the Viewport will adjust its scrollbars accordingly.
  24485. A subclass of the viewport can be created which will receive calls to its
  24486. visibleAreaChanged() method when the subcomponent changes position or size.
  24487. */
  24488. class JUCE_API Viewport : public Component,
  24489. private ComponentListener,
  24490. private ScrollBarListener
  24491. {
  24492. public:
  24493. /** Creates a Viewport.
  24494. The viewport is initially empty - use the setViewedComponent() method to
  24495. add a child component for it to manage.
  24496. */
  24497. Viewport (const String& componentName = String::empty);
  24498. /** Destructor. */
  24499. ~Viewport();
  24500. /** Sets the component that this viewport will contain and scroll around.
  24501. This will add the given component to this Viewport and position it at
  24502. (0, 0).
  24503. (Don't add or remove any child components directly using the normal
  24504. Component::addChildComponent() methods).
  24505. @param newViewedComponent the component to add to this viewport (this pointer
  24506. may be null). The component passed in will be deleted
  24507. by the Viewport when it's no longer needed
  24508. @see getViewedComponent
  24509. */
  24510. void setViewedComponent (Component* const newViewedComponent);
  24511. /** Returns the component that's currently being used inside the Viewport.
  24512. @see setViewedComponent
  24513. */
  24514. Component* getViewedComponent() const throw() { return contentComp; }
  24515. /** Changes the position of the viewed component.
  24516. The inner component will be moved so that the pixel at the top left of
  24517. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  24518. within the inner component.
  24519. This will update the scrollbars and might cause a call to visibleAreaChanged().
  24520. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  24521. */
  24522. void setViewPosition (const int xPixelsOffset,
  24523. const int yPixelsOffset);
  24524. /** Changes the view position as a proportion of the distance it can move.
  24525. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  24526. visible area in the top-left, and (1, 1) would put it as far down and
  24527. to the right as it's possible to go whilst keeping the child component
  24528. on-screen.
  24529. */
  24530. void setViewPositionProportionately (const double proportionX,
  24531. const double proportionY);
  24532. /** If the specified position is at the edges of the viewport, this method scrolls
  24533. the viewport to bring that position nearer to the centre.
  24534. Call this if you're dragging an object inside a viewport and want to make it scroll
  24535. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  24536. useful when auto-scrolling.
  24537. @param mouseX the x position, relative to the Viewport's top-left
  24538. @param mouseY the y position, relative to the Viewport's top-left
  24539. @param distanceFromEdge specifies how close to an edge the position needs to be
  24540. before the viewport should scroll in that direction
  24541. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  24542. to scroll by.
  24543. @returns true if the viewport was scrolled
  24544. */
  24545. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  24546. /** Returns the position within the child component of the top-left of its visible area.
  24547. @see getViewWidth, setViewPosition
  24548. */
  24549. int getViewPositionX() const throw() { return lastVX; }
  24550. /** Returns the position within the child component of the top-left of its visible area.
  24551. @see getViewHeight, setViewPosition
  24552. */
  24553. int getViewPositionY() const throw() { return lastVY; }
  24554. /** Returns the width of the visible area of the child component.
  24555. This may be less than the width of this Viewport if there's a vertical scrollbar
  24556. or if the child component is itself smaller.
  24557. */
  24558. int getViewWidth() const throw() { return lastVW; }
  24559. /** Returns the height of the visible area of the child component.
  24560. This may be less than the height of this Viewport if there's a horizontal scrollbar
  24561. or if the child component is itself smaller.
  24562. */
  24563. int getViewHeight() const throw() { return lastVH; }
  24564. /** Returns the width available within this component for the contents.
  24565. This will be the width of the viewport component minus the width of a
  24566. vertical scrollbar (if visible).
  24567. */
  24568. int getMaximumVisibleWidth() const throw();
  24569. /** Returns the height available within this component for the contents.
  24570. This will be the height of the viewport component minus the space taken up
  24571. by a horizontal scrollbar (if visible).
  24572. */
  24573. int getMaximumVisibleHeight() const throw();
  24574. /** Callback method that is called when the visible area changes.
  24575. This will be called when the visible area is moved either be scrolling or
  24576. by calls to setViewPosition(), etc.
  24577. */
  24578. virtual void visibleAreaChanged (int visibleX, int visibleY,
  24579. int visibleW, int visibleH);
  24580. /** Turns scrollbars on or off.
  24581. If set to false, the scrollbars won't ever appear. When true (the default)
  24582. they will appear only when needed.
  24583. */
  24584. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  24585. const bool showHorizontalScrollbarIfNeeded);
  24586. /** True if the vertical scrollbar is enabled.
  24587. @see setScrollBarsShown
  24588. */
  24589. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  24590. /** True if the horizontal scrollbar is enabled.
  24591. @see setScrollBarsShown
  24592. */
  24593. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  24594. /** Changes the width of the scrollbars.
  24595. If this isn't specified, the default width from the LookAndFeel class will be used.
  24596. @see LookAndFeel::getDefaultScrollbarWidth
  24597. */
  24598. void setScrollBarThickness (const int thickness);
  24599. /** Returns the thickness of the scrollbars.
  24600. @see setScrollBarThickness
  24601. */
  24602. int getScrollBarThickness() const throw();
  24603. /** Changes the distance that a single-step click on a scrollbar button
  24604. will move the viewport.
  24605. */
  24606. void setSingleStepSizes (const int stepX, const int stepY);
  24607. /** Shows or hides the buttons on any scrollbars that are used.
  24608. @see ScrollBar::setButtonVisibility
  24609. */
  24610. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24611. /** Returns a pointer to the scrollbar component being used.
  24612. Handy if you need to customise the bar somehow.
  24613. */
  24614. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  24615. /** Returns a pointer to the scrollbar component being used.
  24616. Handy if you need to customise the bar somehow.
  24617. */
  24618. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  24619. juce_UseDebuggingNewOperator
  24620. /** @internal */
  24621. void resized();
  24622. /** @internal */
  24623. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  24624. /** @internal */
  24625. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24626. /** @internal */
  24627. bool keyPressed (const KeyPress& key);
  24628. /** @internal */
  24629. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24630. /** @internal */
  24631. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24632. private:
  24633. Component* contentComp;
  24634. int lastVX, lastVY, lastVW, lastVH;
  24635. int scrollBarThickness;
  24636. int singleStepX, singleStepY;
  24637. bool showHScrollbar, showVScrollbar;
  24638. Component* contentHolder;
  24639. ScrollBar* verticalScrollBar;
  24640. ScrollBar* horizontalScrollBar;
  24641. void updateVisibleRegion();
  24642. Viewport (const Viewport&);
  24643. const Viewport& operator= (const Viewport&);
  24644. };
  24645. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  24646. /********* End of inlined file: juce_Viewport.h *********/
  24647. /********* Start of inlined file: juce_PopupMenu.h *********/
  24648. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  24649. #define __JUCE_POPUPMENU_JUCEHEADER__
  24650. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  24651. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  24652. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  24653. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  24654. @see PopupMenu::addCustomItem
  24655. */
  24656. class JUCE_API PopupMenuCustomComponent : public Component
  24657. {
  24658. public:
  24659. /** Destructor. */
  24660. ~PopupMenuCustomComponent();
  24661. /** Chooses the size that this component would like to have.
  24662. Note that the size which this method returns isn't necessarily the one that
  24663. the menu will give it, as it will be stretched to fit the other items in
  24664. the menu.
  24665. */
  24666. virtual void getIdealSize (int& idealWidth,
  24667. int& idealHeight) = 0;
  24668. /** Dismisses the menu indicating that this item has been chosen.
  24669. This will cause the menu to exit from its modal state, returning
  24670. this item's id as the result.
  24671. */
  24672. void triggerMenuItem();
  24673. /** Returns true if this item should be highlighted because the mouse is
  24674. over it.
  24675. You can call this method in your paint() method to find out whether
  24676. to draw a highlight.
  24677. */
  24678. bool isItemHighlighted() const throw() { return isHighlighted; }
  24679. protected:
  24680. /** Constructor.
  24681. If isTriggeredAutomatically is true, then the menu will automatically detect
  24682. a click on this component and use that to trigger it. If it's false, then it's
  24683. up to your class to manually trigger the item if it wants to.
  24684. */
  24685. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  24686. private:
  24687. friend class MenuItemInfo;
  24688. friend class MenuItemComponent;
  24689. friend class PopupMenuWindow;
  24690. int refCount_;
  24691. bool isHighlighted, isTriggeredAutomatically;
  24692. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  24693. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  24694. };
  24695. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  24696. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  24697. /** Creates and displays a popup-menu.
  24698. To show a popup-menu, you create one of these, add some items to it, then
  24699. call its show() method, which returns the id of the item the user selects.
  24700. E.g. @code
  24701. void MyWidget::mouseDown (const MouseEvent& e)
  24702. {
  24703. PopupMenu m;
  24704. m.addItem (1, "item 1");
  24705. m.addItem (2, "item 2");
  24706. const int result = m.show();
  24707. if (result == 0)
  24708. {
  24709. // user dismissed the menu without picking anything
  24710. }
  24711. else if (result == 1)
  24712. {
  24713. // user picked item 1
  24714. }
  24715. else if (result == 2)
  24716. {
  24717. // user picked item 2
  24718. }
  24719. }
  24720. @endcode
  24721. Submenus are easy too: @code
  24722. void MyWidget::mouseDown (const MouseEvent& e)
  24723. {
  24724. PopupMenu subMenu;
  24725. subMenu.addItem (1, "item 1");
  24726. subMenu.addItem (2, "item 2");
  24727. PopupMenu mainMenu;
  24728. mainMenu.addItem (3, "item 3");
  24729. mainMenu.addSubMenu ("other choices", subMenu);
  24730. const int result = m.show();
  24731. ...etc
  24732. }
  24733. @endcode
  24734. */
  24735. class JUCE_API PopupMenu
  24736. {
  24737. public:
  24738. /** Creates an empty popup menu. */
  24739. PopupMenu();
  24740. /** Creates a copy of another menu. */
  24741. PopupMenu (const PopupMenu& other);
  24742. /** Destructor. */
  24743. ~PopupMenu();
  24744. /** Copies this menu from another one. */
  24745. const PopupMenu& operator= (const PopupMenu& other);
  24746. /** Resets the menu, removing all its items. */
  24747. void clear();
  24748. /** Appends a new text item for this menu to show.
  24749. @param itemResultId the number that will be returned from the show() method
  24750. if the user picks this item. The value should never be
  24751. zero, because that's used to indicate that the user didn't
  24752. select anything.
  24753. @param itemText the text to show.
  24754. @param isActive if false, the item will be shown 'greyed-out' and can't be
  24755. picked
  24756. @param isTicked if true, the item will be shown with a tick next to it
  24757. @param iconToUse if this is non-zero, it should be an image that will be
  24758. displayed to the left of the item. This method will take its
  24759. own copy of the image passed-in, so there's no need to keep
  24760. it hanging around.
  24761. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  24762. */
  24763. void addItem (const int itemResultId,
  24764. const String& itemText,
  24765. const bool isActive = true,
  24766. const bool isTicked = false,
  24767. const Image* const iconToUse = 0);
  24768. /** Adds an item that represents one of the commands in a command manager object.
  24769. @param commandManager the manager to use to trigger the command and get information
  24770. about it
  24771. @param commandID the ID of the command
  24772. @param displayName if this is non-empty, then this string will be used instead of
  24773. the command's registered name
  24774. */
  24775. void addCommandItem (ApplicationCommandManager* commandManager,
  24776. const int commandID,
  24777. const String& displayName = String::empty);
  24778. /** Appends a text item with a special colour.
  24779. This is the same as addItem(), but specifies a colour to use for the
  24780. text, which will override the default colours that are used by the
  24781. current look-and-feel. See addItem() for a description of the parameters.
  24782. */
  24783. void addColouredItem (const int itemResultId,
  24784. const String& itemText,
  24785. const Colour& itemTextColour,
  24786. const bool isActive = true,
  24787. const bool isTicked = false,
  24788. const Image* const iconToUse = 0);
  24789. /** Appends a custom menu item.
  24790. This will add a user-defined component to use as a menu item. The component
  24791. passed in will be deleted by this menu when it's no longer needed.
  24792. @see PopupMenuCustomComponent
  24793. */
  24794. void addCustomItem (const int itemResultId,
  24795. PopupMenuCustomComponent* const customComponent);
  24796. /** Appends a custom menu item that can't be used to trigger a result.
  24797. This will add a user-defined component to use as a menu item. Unlike the
  24798. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  24799. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  24800. delete the component when it's finished, so it's the caller's responsibility
  24801. to manage the component that is passed-in.
  24802. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  24803. detection of a mouse-click on your component, and use that to trigger the
  24804. menu ID specified in itemResultId. If this is false, the menu item can't
  24805. be triggered, so itemResultId is not used.
  24806. @see PopupMenuCustomComponent
  24807. */
  24808. void addCustomItem (const int itemResultId,
  24809. Component* customComponent,
  24810. int idealWidth, int idealHeight,
  24811. const bool triggerMenuItemAutomaticallyWhenClicked);
  24812. /** Appends a sub-menu.
  24813. If the menu that's passed in is empty, it will appear as an inactive item.
  24814. */
  24815. void addSubMenu (const String& subMenuName,
  24816. const PopupMenu& subMenu,
  24817. const bool isActive = true,
  24818. Image* const iconToUse = 0,
  24819. const bool isTicked = false);
  24820. /** Appends a separator to the menu, to help break it up into sections.
  24821. The menu class is smart enough not to display separators at the top or bottom
  24822. of the menu, and it will replace mutliple adjacent separators with a single
  24823. one, so your code can be quite free and easy about adding these, and it'll
  24824. always look ok.
  24825. */
  24826. void addSeparator();
  24827. /** Adds a non-clickable text item to the menu.
  24828. This is a bold-font items which can be used as a header to separate the items
  24829. into named groups.
  24830. */
  24831. void addSectionHeader (const String& title);
  24832. /** Returns the number of items that the menu currently contains.
  24833. (This doesn't count separators).
  24834. */
  24835. int getNumItems() const;
  24836. /** Returns true if the menu contains a command item that triggers the given command. */
  24837. bool containsCommandItem (const int commandID) const;
  24838. /** Returns true if the menu contains any items that can be used. */
  24839. bool containsAnyActiveItems() const;
  24840. /** Displays the menu and waits for the user to pick something.
  24841. This will display the menu modally, and return the ID of the item that the
  24842. user picks. If they click somewhere off the menu to get rid of it without
  24843. choosing anything, this will return 0.
  24844. The current location of the mouse will be used as the position to show the
  24845. menu - to explicitly set the menu's position, use showAt() instead. Depending
  24846. on where this point is on the screen, the menu will appear above, below or
  24847. to the side of the point.
  24848. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  24849. then when the menu first appears, it will make sure
  24850. that this item is visible. So if the menu has too many
  24851. items to fit on the screen, it will be scrolled to a
  24852. position where this item is visible.
  24853. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  24854. than this if some items are too long to fit.
  24855. @param maximumNumColumns if there are too many items to fit on-screen in a single
  24856. vertical column, the menu may be laid out as a series of
  24857. columns - this is the maximum number allowed. To use the
  24858. default value for this (probably about 7), you can pass
  24859. in zero.
  24860. @param standardItemHeight if this is non-zero, it will be used as the standard
  24861. height for menu items (apart from custom items)
  24862. @see showAt
  24863. */
  24864. int show (const int itemIdThatMustBeVisible = 0,
  24865. const int minimumWidth = 0,
  24866. const int maximumNumColumns = 0,
  24867. const int standardItemHeight = 0);
  24868. /** Displays the menu at a specific location.
  24869. This is the same as show(), but uses a specific location (in global screen
  24870. co-ordinates) rather than the current mouse position.
  24871. Note that the co-ordinates don't specify the top-left of the menu - they
  24872. indicate a point of interest, and the menu will position itself nearby to
  24873. this point, trying to keep it fully on-screen.
  24874. @see show()
  24875. */
  24876. int showAt (const int screenX,
  24877. const int screenY,
  24878. const int itemIdThatMustBeVisible = 0,
  24879. const int minimumWidth = 0,
  24880. const int maximumNumColumns = 0,
  24881. const int standardItemHeight = 0);
  24882. /** Displays the menu as if it's attached to a component such as a button.
  24883. This is similar to showAt(), but will position it next to the given component, e.g.
  24884. so that the menu's edge is aligned with that of the component. This is intended for
  24885. things like buttons that trigger a pop-up menu.
  24886. */
  24887. int showAt (Component* componentToAttachTo,
  24888. const int itemIdThatMustBeVisible = 0,
  24889. const int minimumWidth = 0,
  24890. const int maximumNumColumns = 0,
  24891. const int standardItemHeight = 0);
  24892. /** Closes any menus that are currently open.
  24893. This might be useful if you have a situation where your window is being closed
  24894. by some means other than a user action, and you'd like to make sure that menus
  24895. aren't left hanging around.
  24896. */
  24897. static void JUCE_CALLTYPE dismissAllActiveMenus();
  24898. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  24899. This can be called before show() if you need a customised menu. Be careful
  24900. not to delete the LookAndFeel object before the menu has been deleted.
  24901. */
  24902. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  24903. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  24904. These constants can be used either via the LookAndFeel::setColour()
  24905. method for the look and feel that is set for this menu with setLookAndFeel()
  24906. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  24907. */
  24908. enum ColourIds
  24909. {
  24910. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  24911. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  24912. colour is specified when the item is added). */
  24913. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  24914. addSectionHeader() method). */
  24915. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  24916. highlighted menu item. */
  24917. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  24918. highlighted item. */
  24919. };
  24920. /**
  24921. Allows you to iterate through the items in a pop-up menu, and examine
  24922. their properties.
  24923. To use this, just create one and repeatedly call its next() method. When this
  24924. returns true, all the member variables of the iterator are filled-out with
  24925. information describing the menu item. When it returns false, the end of the
  24926. list has been reached.
  24927. */
  24928. class JUCE_API MenuItemIterator
  24929. {
  24930. public:
  24931. /** Creates an iterator that will scan through the items in the specified
  24932. menu.
  24933. Be careful not to add any items to a menu while it is being iterated,
  24934. or things could get out of step.
  24935. */
  24936. MenuItemIterator (const PopupMenu& menu);
  24937. /** Destructor. */
  24938. ~MenuItemIterator();
  24939. /** Returns true if there is another item, and sets up all this object's
  24940. member variables to reflect that item's properties.
  24941. */
  24942. bool next();
  24943. String itemName;
  24944. const PopupMenu* subMenu;
  24945. int itemId;
  24946. bool isSeparator;
  24947. bool isTicked;
  24948. bool isEnabled;
  24949. bool isCustomComponent;
  24950. bool isSectionHeader;
  24951. const Colour* customColour;
  24952. const Image* customImage;
  24953. ApplicationCommandManager* commandManager;
  24954. juce_UseDebuggingNewOperator
  24955. private:
  24956. const PopupMenu& menu;
  24957. int index;
  24958. MenuItemIterator (const MenuItemIterator&);
  24959. const MenuItemIterator& operator= (const MenuItemIterator&);
  24960. };
  24961. juce_UseDebuggingNewOperator
  24962. private:
  24963. friend class PopupMenuWindow;
  24964. friend class MenuItemIterator;
  24965. VoidArray items;
  24966. LookAndFeel* lookAndFeel;
  24967. bool separatorPending;
  24968. void addSeparatorIfPending();
  24969. int showMenu (const int x, const int y, const int w, const int h,
  24970. const int itemIdThatMustBeVisible,
  24971. const int minimumWidth,
  24972. const int maximumNumColumns,
  24973. const int standardItemHeight,
  24974. const bool alignToRectangle,
  24975. Component* const componentAttachedTo);
  24976. friend class MenuBarComponent;
  24977. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  24978. const int itemIdThatMustBeVisible,
  24979. const int minimumWidth,
  24980. const int maximumNumColumns,
  24981. const int standardItemHeight,
  24982. const bool alignToRectangle,
  24983. Component* menuBarComponent,
  24984. ApplicationCommandManager** managerOfChosenCommand,
  24985. Component* const componentAttachedTo);
  24986. };
  24987. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  24988. /********* End of inlined file: juce_PopupMenu.h *********/
  24989. class TextEditor;
  24990. class TextHolderComponent;
  24991. /**
  24992. Receives callbacks from a TextEditor component when it changes.
  24993. @see TextEditor::addListener
  24994. */
  24995. class JUCE_API TextEditorListener
  24996. {
  24997. public:
  24998. /** Destructor. */
  24999. virtual ~TextEditorListener() {}
  25000. /** Called when the user changes the text in some way. */
  25001. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  25002. /** Called when the user presses the return key. */
  25003. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  25004. /** Called when the user presses the escape key. */
  25005. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  25006. /** Called when the text editor loses focus. */
  25007. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  25008. };
  25009. /**
  25010. A component containing text that can be edited.
  25011. A TextEditor can either be in single- or multi-line mode, and supports mixed
  25012. fonts and colours.
  25013. @see TextEditorListener, Label
  25014. */
  25015. class JUCE_API TextEditor : public Component,
  25016. public SettableTooltipClient
  25017. {
  25018. public:
  25019. /** Creates a new, empty text editor.
  25020. @param componentName the name to pass to the component for it to use as its name
  25021. @param passwordCharacter if this is not zero, this character will be used as a replacement
  25022. for all characters that are drawn on screen - e.g. to create
  25023. a password-style textbox containing circular blobs instead of text,
  25024. you could set this value to 0x25cf, which is the unicode character
  25025. for a black splodge (not all fonts include this, though), or 0x2022,
  25026. which is a bullet (probably the best choice for linux).
  25027. */
  25028. TextEditor (const String& componentName = String::empty,
  25029. const tchar passwordCharacter = 0);
  25030. /** Destructor. */
  25031. virtual ~TextEditor();
  25032. /** Puts the editor into either multi- or single-line mode.
  25033. By default, the editor will be in single-line mode, so use this if you need a multi-line
  25034. editor.
  25035. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  25036. on if you want a multi-line editor with line-breaks.
  25037. @see isMultiLine, setReturnKeyStartsNewLine
  25038. */
  25039. void setMultiLine (const bool shouldBeMultiLine,
  25040. const bool shouldWordWrap = true);
  25041. /** Returns true if the editor is in multi-line mode.
  25042. */
  25043. bool isMultiLine() const;
  25044. /** Changes the behaviour of the return key.
  25045. If set to true, the return key will insert a new-line into the text; if false
  25046. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  25047. method. By default this is set to false, and when true it will only insert
  25048. new-lines when in multi-line mode (see setMultiLine()).
  25049. */
  25050. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  25051. /** Returns the value set by setReturnKeyStartsNewLine().
  25052. See setReturnKeyStartsNewLine() for more info.
  25053. */
  25054. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  25055. /** Indicates whether the tab key should be accepted and used to input a tab character,
  25056. or whether it gets ignored.
  25057. By default the tab key is ignored, so that it can be used to switch keyboard focus
  25058. between components.
  25059. */
  25060. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed);
  25061. /** Returns true if the tab key is being used for input.
  25062. @see setTabKeyUsedAsCharacter
  25063. */
  25064. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  25065. /** Changes the editor to read-only mode.
  25066. By default, the text editor is not read-only. If you're making it read-only, you
  25067. might also want to call setCaretVisible (false) to get rid of the caret.
  25068. The text can still be highlighted and copied when in read-only mode.
  25069. @see isReadOnly, setCaretVisible
  25070. */
  25071. void setReadOnly (const bool shouldBeReadOnly);
  25072. /** Returns true if the editor is in read-only mode.
  25073. */
  25074. bool isReadOnly() const;
  25075. /** Makes the caret visible or invisible.
  25076. By default the caret is visible.
  25077. @see setCaretColour, setCaretPosition
  25078. */
  25079. void setCaretVisible (const bool shouldBeVisible);
  25080. /** Returns true if the caret is enabled.
  25081. @see setCaretVisible
  25082. */
  25083. bool isCaretVisible() const { return caretVisible; }
  25084. /** Enables/disables a vertical scrollbar.
  25085. (This only applies when in multi-line mode). When the text gets too long to fit
  25086. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  25087. this is enabled, the scrollbar will be hidden unless it's needed.
  25088. By default the scrollbar is enabled.
  25089. */
  25090. void setScrollbarsShown (bool shouldBeEnabled);
  25091. /** Returns true if scrollbars are enabled.
  25092. @see setScrollbarsShown
  25093. */
  25094. bool areScrollbarsShown() const { return scrollbarVisible; }
  25095. /** Changes the password character used to disguise the text.
  25096. @param passwordCharacter if this is not zero, this character will be used as a replacement
  25097. for all characters that are drawn on screen - e.g. to create
  25098. a password-style textbox containing circular blobs instead of text,
  25099. you could set this value to 0x25cf, which is the unicode character
  25100. for a black splodge (not all fonts include this, though), or 0x2022,
  25101. which is a bullet (probably the best choice for linux).
  25102. */
  25103. void setPasswordCharacter (const tchar passwordCharacter);
  25104. /** Returns the current password character.
  25105. @see setPasswordCharacter
  25106. l */
  25107. tchar getPasswordCharacter() const { return passwordCharacter; }
  25108. /** Allows a right-click menu to appear for the editor.
  25109. (This defaults to being enabled).
  25110. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  25111. of options such as cut/copy/paste, undo/redo, etc.
  25112. */
  25113. void setPopupMenuEnabled (const bool menuEnabled);
  25114. /** Returns true if the right-click menu is enabled.
  25115. @see setPopupMenuEnabled
  25116. */
  25117. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  25118. /** Returns true if a popup-menu is currently being displayed.
  25119. */
  25120. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  25121. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  25122. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25123. methods.
  25124. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25125. */
  25126. enum ColourIds
  25127. {
  25128. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  25129. transparent if necessary. */
  25130. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  25131. that because the editor can contain multiple colours, calling this
  25132. method won't change the colour of existing text - to do that, call
  25133. applyFontToAllText() after calling this method.*/
  25134. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  25135. the text - this can be transparent if you don't want to show any
  25136. highlighting.*/
  25137. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  25138. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  25139. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  25140. the edge of the component. */
  25141. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  25142. the edge of the component when it has focus. */
  25143. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  25144. around the edge of the editor. */
  25145. };
  25146. /** Sets the font to use for newly added text.
  25147. This will change the font that will be used next time any text is added or entered
  25148. into the editor. It won't change the font of any existing text - to do that, use
  25149. applyFontToAllText() instead.
  25150. @see applyFontToAllText
  25151. */
  25152. void setFont (const Font& newFont);
  25153. /** Applies a font to all the text in the editor.
  25154. This will also set the current font to use for any new text that's added.
  25155. @see setFont
  25156. */
  25157. void applyFontToAllText (const Font& newFont);
  25158. /** Returns the font that's currently being used for new text.
  25159. @see setFont
  25160. */
  25161. const Font getFont() const;
  25162. /** If set to true, focusing on the editor will highlight all its text.
  25163. (Set to false by default).
  25164. This is useful for boxes where you expect the user to re-enter all the
  25165. text when they focus on the component, rather than editing what's already there.
  25166. */
  25167. void setSelectAllWhenFocused (const bool b);
  25168. /** Sets limits on the characters that can be entered.
  25169. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  25170. limit is set
  25171. @param allowedCharacters if this is non-empty, then only characters that occur in
  25172. this string are allowed to be entered into the editor.
  25173. */
  25174. void setInputRestrictions (const int maxTextLength,
  25175. const String& allowedCharacters = String::empty);
  25176. /** When the text editor is empty, it can be set to display a message.
  25177. This is handy for things like telling the user what to type in the box - the
  25178. string is only displayed, it's not taken to actually be the contents of
  25179. the editor.
  25180. */
  25181. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  25182. /** Changes the size of the scrollbars that are used.
  25183. Handy if you need smaller scrollbars for a small text box.
  25184. */
  25185. void setScrollBarThickness (const int newThicknessPixels);
  25186. /** Shows or hides the buttons on any scrollbars that are used.
  25187. @see ScrollBar::setButtonVisibility
  25188. */
  25189. void setScrollBarButtonVisibility (const bool buttonsVisible);
  25190. /** Registers a listener to be told when things happen to the text.
  25191. @see removeListener
  25192. */
  25193. void addListener (TextEditorListener* const newListener);
  25194. /** Deregisters a listener.
  25195. @see addListener
  25196. */
  25197. void removeListener (TextEditorListener* const listenerToRemove);
  25198. /** Returns the entire contents of the editor. */
  25199. const String getText() const;
  25200. /** Returns a section of the contents of the editor. */
  25201. const String getTextSubstring (const int startCharacter, const int endCharacter) const;
  25202. /** Returns true if there are no characters in the editor.
  25203. This is more efficient than calling getText().isEmpty().
  25204. */
  25205. bool isEmpty() const;
  25206. /** Sets the entire content of the editor.
  25207. This will clear the editor and insert the given text (using the current text colour
  25208. and font). You can set the current text colour using
  25209. @code setColour (TextEditor::textColourId, ...);
  25210. @endcode
  25211. @param newText the text to add
  25212. @param sendTextChangeMessage if true, this will cause a change message to
  25213. be sent to all the listeners.
  25214. @see insertText
  25215. */
  25216. void setText (const String& newText,
  25217. const bool sendTextChangeMessage = true);
  25218. /** Returns a Value object that can be used to get or set the text.
  25219. Bear in mind that this operate quite slowly if your text box contains large
  25220. amounts of text, as it needs to dynamically build the string that's involved. It's
  25221. best used for small text boxes.
  25222. */
  25223. Value& getTextValue();
  25224. /** Inserts some text at the current cursor position.
  25225. If a section of the text is highlighted, it will be replaced by
  25226. this string, otherwise it will be inserted.
  25227. To delete a section of text, you can use setHighlightedRegion() to
  25228. highlight it, and call insertTextAtCursor (String::empty).
  25229. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  25230. */
  25231. void insertTextAtCursor (String textToInsert);
  25232. /** Deletes all the text from the editor. */
  25233. void clear();
  25234. /** Deletes the currently selected region, and puts it on the clipboard.
  25235. @see copy, paste, SystemClipboard
  25236. */
  25237. void cut();
  25238. /** Copies any currently selected region to the clipboard.
  25239. @see cut, paste, SystemClipboard
  25240. */
  25241. void copy();
  25242. /** Pastes the contents of the clipboard into the editor at the cursor position.
  25243. @see cut, copy, SystemClipboard
  25244. */
  25245. void paste();
  25246. /** Moves the caret to be in front of a given character.
  25247. @see getCaretPosition
  25248. */
  25249. void setCaretPosition (const int newIndex);
  25250. /** Returns the current index of the caret.
  25251. @see setCaretPosition
  25252. */
  25253. int getCaretPosition() const;
  25254. /** Attempts to scroll the text editor so that the caret ends up at
  25255. a specified position.
  25256. This won't affect the caret's position within the text, it tries to scroll
  25257. the entire editor vertically and horizontally so that the caret is sitting
  25258. at the given position (relative to the top-left of this component).
  25259. Depending on the amount of text available, it might not be possible to
  25260. scroll far enough for the caret to reach this exact position, but it
  25261. will go as far as it can in that direction.
  25262. */
  25263. void scrollEditorToPositionCaret (const int desiredCaretX,
  25264. const int desiredCaretY);
  25265. /** Get the graphical position of the caret.
  25266. The rectangle returned is relative to the component's top-left corner.
  25267. @see scrollEditorToPositionCaret
  25268. */
  25269. const Rectangle getCaretRectangle();
  25270. /** Selects a section of the text.
  25271. */
  25272. void setHighlightedRegion (int startIndex,
  25273. int numberOfCharactersToHighlight);
  25274. /** Returns the first character that is selected.
  25275. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  25276. will return 0.
  25277. @see setHighlightedRegion, getHighlightedRegionLength
  25278. */
  25279. int getHighlightedRegionStart() const { return selectionStart; }
  25280. /** Returns the number of characters that are selected.
  25281. @see setHighlightedRegion, getHighlightedRegionStart
  25282. */
  25283. int getHighlightedRegionLength() const { return jmax (0, selectionEnd - selectionStart); }
  25284. /** Returns the section of text that is currently selected. */
  25285. const String getHighlightedText() const;
  25286. /** Finds the index of the character at a given position.
  25287. The co-ordinates are relative to the component's top-left.
  25288. */
  25289. int getTextIndexAt (const int x, const int y);
  25290. /** Counts the number of characters in the text.
  25291. This is quicker than getting the text as a string if you just need to know
  25292. the length.
  25293. */
  25294. int getTotalNumChars() const;
  25295. /** Returns the total width of the text, as it is currently laid-out.
  25296. This may be larger than the size of the TextEditor, and can change when
  25297. the TextEditor is resized or the text changes.
  25298. */
  25299. int getTextWidth() const;
  25300. /** Returns the maximum height of the text, as it is currently laid-out.
  25301. This may be larger than the size of the TextEditor, and can change when
  25302. the TextEditor is resized or the text changes.
  25303. */
  25304. int getTextHeight() const;
  25305. /** Changes the size of the gap at the top and left-edge of the editor.
  25306. By default there's a gap of 4 pixels.
  25307. */
  25308. void setIndents (const int newLeftIndent, const int newTopIndent);
  25309. /** Changes the size of border left around the edge of the component.
  25310. @see getBorder
  25311. */
  25312. void setBorder (const BorderSize& border);
  25313. /** Returns the size of border around the edge of the component.
  25314. @see setBorder
  25315. */
  25316. const BorderSize getBorder() const;
  25317. /** Used to disable the auto-scrolling which keeps the cursor visible.
  25318. If true (the default), the editor will scroll when the cursor moves offscreen. If
  25319. set to false, it won't.
  25320. */
  25321. void setScrollToShowCursor (const bool shouldScrollToShowCursor);
  25322. /** @internal */
  25323. void paint (Graphics& g);
  25324. /** @internal */
  25325. void paintOverChildren (Graphics& g);
  25326. /** @internal */
  25327. void mouseDown (const MouseEvent& e);
  25328. /** @internal */
  25329. void mouseUp (const MouseEvent& e);
  25330. /** @internal */
  25331. void mouseDrag (const MouseEvent& e);
  25332. /** @internal */
  25333. void mouseDoubleClick (const MouseEvent& e);
  25334. /** @internal */
  25335. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25336. /** @internal */
  25337. bool keyPressed (const KeyPress& key);
  25338. /** @internal */
  25339. bool keyStateChanged (const bool isKeyDown);
  25340. /** @internal */
  25341. void focusGained (FocusChangeType cause);
  25342. /** @internal */
  25343. void focusLost (FocusChangeType cause);
  25344. /** @internal */
  25345. void resized();
  25346. /** @internal */
  25347. void enablementChanged();
  25348. /** @internal */
  25349. void colourChanged();
  25350. juce_UseDebuggingNewOperator
  25351. protected:
  25352. /** This adds the items to the popup menu.
  25353. By default it adds the cut/copy/paste items, but you can override this if
  25354. you need to replace these with your own items.
  25355. If you want to add your own items to the existing ones, you can override this,
  25356. call the base class's addPopupMenuItems() method, then append your own items.
  25357. When the menu has been shown, performPopupMenuAction() will be called to
  25358. perform the item that the user has chosen.
  25359. The default menu items will be added using item IDs in the range
  25360. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  25361. menu IDs.
  25362. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  25363. a pointer to the info about it, or may be null if the menu is being triggered
  25364. by some other means.
  25365. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  25366. */
  25367. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  25368. const MouseEvent* mouseClickEvent);
  25369. /** This is called to perform one of the items that was shown on the popup menu.
  25370. If you've overridden addPopupMenuItems(), you should also override this
  25371. to perform the actions that you've added.
  25372. If you've overridden addPopupMenuItems() but have still left the default items
  25373. on the menu, remember to call the superclass's performPopupMenuAction()
  25374. so that it can perform the default actions if that's what the user clicked on.
  25375. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  25376. */
  25377. virtual void performPopupMenuAction (const int menuItemID);
  25378. /** Scrolls the minimum distance needed to get the caret into view. */
  25379. void scrollToMakeSureCursorIsVisible();
  25380. /** @internal */
  25381. void moveCaret (int newCaretPos);
  25382. /** @internal */
  25383. void moveCursorTo (const int newPosition, const bool isSelecting);
  25384. /** Used internally to dispatch a text-change message. */
  25385. void textChanged();
  25386. /** Begins a new transaction in the UndoManager.
  25387. */
  25388. void newTransaction();
  25389. /** Used internally to trigger an undo or redo. */
  25390. void doUndoRedo (const bool isRedo);
  25391. /** Can be overridden to intercept return key presses directly */
  25392. virtual void returnPressed();
  25393. /** Can be overridden to intercept escape key presses directly */
  25394. virtual void escapePressed();
  25395. /** @internal */
  25396. void handleCommandMessage (int commandId);
  25397. private:
  25398. ScopedPointer <Viewport> viewport;
  25399. TextHolderComponent* textHolder;
  25400. BorderSize borderSize;
  25401. bool readOnly : 1;
  25402. bool multiline : 1;
  25403. bool wordWrap : 1;
  25404. bool returnKeyStartsNewLine : 1;
  25405. bool caretVisible : 1;
  25406. bool popupMenuEnabled : 1;
  25407. bool selectAllTextWhenFocused : 1;
  25408. bool scrollbarVisible : 1;
  25409. bool wasFocused : 1;
  25410. bool caretFlashState : 1;
  25411. bool keepCursorOnScreen : 1;
  25412. bool tabKeyUsed : 1;
  25413. bool menuActive : 1;
  25414. bool valueTextNeedsUpdating : 1;
  25415. UndoManager undoManager;
  25416. float cursorX, cursorY, cursorHeight;
  25417. int maxTextLength;
  25418. int selectionStart, selectionEnd;
  25419. int leftIndent, topIndent;
  25420. unsigned int lastTransactionTime;
  25421. Font currentFont;
  25422. mutable int totalNumChars;
  25423. int caretPosition;
  25424. VoidArray sections;
  25425. String textToShowWhenEmpty;
  25426. Colour colourForTextWhenEmpty;
  25427. tchar passwordCharacter;
  25428. Value textValue;
  25429. enum
  25430. {
  25431. notDragging,
  25432. draggingSelectionStart,
  25433. draggingSelectionEnd
  25434. } dragType;
  25435. String allowedCharacters;
  25436. SortedSet <void*> listeners;
  25437. friend class TextEditorInsertAction;
  25438. friend class TextEditorRemoveAction;
  25439. void coalesceSimilarSections();
  25440. void splitSection (const int sectionIndex, const int charToSplitAt);
  25441. void clearInternal (UndoManager* const um);
  25442. void insert (const String& text,
  25443. const int insertIndex,
  25444. const Font& font,
  25445. const Colour& colour,
  25446. UndoManager* const um,
  25447. const int caretPositionToMoveTo);
  25448. void reinsert (const int insertIndex,
  25449. const VoidArray& sections);
  25450. void remove (const int startIndex,
  25451. int endIndex,
  25452. UndoManager* const um,
  25453. const int caretPositionToMoveTo);
  25454. void getCharPosition (const int index,
  25455. float& x, float& y,
  25456. float& lineHeight) const;
  25457. void updateCaretPosition();
  25458. void textWasChangedByValue();
  25459. int indexAtPosition (const float x,
  25460. const float y);
  25461. int findWordBreakAfter (const int position) const;
  25462. int findWordBreakBefore (const int position) const;
  25463. friend class TextHolderComponent;
  25464. friend class TextEditorViewport;
  25465. void drawContent (Graphics& g);
  25466. void updateTextHolderSize();
  25467. float getWordWrapWidth() const;
  25468. void timerCallbackInt();
  25469. void repaintCaret();
  25470. void repaintText (int textStartIndex, int textEndIndex);
  25471. TextEditor (const TextEditor&);
  25472. const TextEditor& operator= (const TextEditor&);
  25473. };
  25474. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  25475. /********* End of inlined file: juce_TextEditor.h *********/
  25476. class Label;
  25477. /**
  25478. A class for receiving events from a Label.
  25479. You can register a LabelListener with a Label using the Label::addListener()
  25480. method, and it will be called when the text of the label changes, either because
  25481. of a call to Label::setText() or by the user editing the text (if the label is
  25482. editable).
  25483. @see Label::addListener, Label::removeListener
  25484. */
  25485. class JUCE_API LabelListener
  25486. {
  25487. public:
  25488. /** Destructor. */
  25489. virtual ~LabelListener() {}
  25490. /** Called when a Label's text has changed.
  25491. */
  25492. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  25493. };
  25494. /**
  25495. A component that displays a text string, and can optionally become a text
  25496. editor when clicked.
  25497. */
  25498. class JUCE_API Label : public Component,
  25499. public SettableTooltipClient,
  25500. protected TextEditorListener,
  25501. private ComponentListener
  25502. {
  25503. public:
  25504. /** Creates a Label.
  25505. @param componentName the name to give the component
  25506. @param labelText the text to show in the label
  25507. */
  25508. Label (const String& componentName,
  25509. const String& labelText);
  25510. /** Destructor. */
  25511. ~Label();
  25512. /** Changes the label text.
  25513. If broadcastChangeMessage is true and the new text is different to the current
  25514. text, then the class will broadcast a change message to any LabelListeners that
  25515. are registered.
  25516. */
  25517. void setText (const String& newText,
  25518. const bool broadcastChangeMessage);
  25519. /** Returns the label's current text.
  25520. @param returnActiveEditorContents if this is true and the label is currently
  25521. being edited, then this method will return the
  25522. text as it's being shown in the editor. If false,
  25523. then the value returned here won't be updated until
  25524. the user has finished typing and pressed the return
  25525. key.
  25526. */
  25527. const String getText (const bool returnActiveEditorContents = false) const throw();
  25528. /** Changes the font to use to draw the text.
  25529. @see getFont
  25530. */
  25531. void setFont (const Font& newFont) throw();
  25532. /** Returns the font currently being used.
  25533. @see setFont
  25534. */
  25535. const Font& getFont() const throw();
  25536. /** A set of colour IDs to use to change the colour of various aspects of the label.
  25537. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25538. methods.
  25539. Note that you can also use the constants from TextEditor::ColourIds to change the
  25540. colour of the text editor that is opened when a label is editable.
  25541. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25542. */
  25543. enum ColourIds
  25544. {
  25545. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  25546. textColourId = 0x1000281, /**< The colour for the text. */
  25547. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25548. Leave this transparent to not have an outline. */
  25549. };
  25550. /** Sets the style of justification to be used for positioning the text.
  25551. (The default is Justification::centredLeft)
  25552. */
  25553. void setJustificationType (const Justification& justification) throw();
  25554. /** Returns the type of justification, as set in setJustificationType(). */
  25555. const Justification getJustificationType() const throw() { return justification; }
  25556. /** Changes the gap that is left between the edge of the component and the text.
  25557. By default there's a small gap left at the sides of the component to allow for
  25558. the drawing of the border, but you can change this if necessary.
  25559. */
  25560. void setBorderSize (int horizontalBorder, int verticalBorder);
  25561. /** Returns the size of the horizontal gap being left around the text.
  25562. */
  25563. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25564. /** Returns the size of the vertical gap being left around the text.
  25565. */
  25566. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25567. /** Makes this label "stick to" another component.
  25568. This will cause the label to follow another component around, staying
  25569. either to its left or above it.
  25570. @param owner the component to follow
  25571. @param onLeft if true, the label will stay on the left of its component; if
  25572. false, it will stay above it.
  25573. */
  25574. void attachToComponent (Component* owner,
  25575. const bool onLeft);
  25576. /** If this label has been attached to another component using attachToComponent, this
  25577. returns the other component.
  25578. Returns 0 if the label is not attached.
  25579. */
  25580. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25581. /** If the label is attached to the left of another component, this returns true.
  25582. Returns false if the label is above the other component. This is only relevent if
  25583. attachToComponent() has been called.
  25584. */
  25585. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25586. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25587. using ellipsis.
  25588. @see Graphics::drawFittedText
  25589. */
  25590. void setMinimumHorizontalScale (const float newScale);
  25591. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25592. /** Registers a listener that will be called when the label's text changes. */
  25593. void addListener (LabelListener* const listener) throw();
  25594. /** Deregisters a previously-registered listener. */
  25595. void removeListener (LabelListener* const listener) throw();
  25596. /** Makes the label turn into a TextEditor when clicked.
  25597. By default this is turned off.
  25598. If turned on, then single- or double-clicking will turn the label into
  25599. an editor. If the user then changes the text, then the ChangeBroadcaster
  25600. base class will be used to send change messages to any listeners that
  25601. have registered.
  25602. If the user changes the text, the textWasEdited() method will be called
  25603. afterwards, and subclasses can override this if they need to do anything
  25604. special.
  25605. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25606. @param editOnDoubleClick if true, a double-click is needed to start editing
  25607. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25608. edited will discard any changes; if false, then this will
  25609. commit the changes.
  25610. @see showEditor, setEditorColours, TextEditor
  25611. */
  25612. void setEditable (const bool editOnSingleClick,
  25613. const bool editOnDoubleClick = false,
  25614. const bool lossOfFocusDiscardsChanges = false) throw();
  25615. /** Returns true if this option was set using setEditable(). */
  25616. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25617. /** Returns true if this option was set using setEditable(). */
  25618. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25619. /** Returns true if this option has been set in a call to setEditable(). */
  25620. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25621. /** Returns true if the user can edit this label's text. */
  25622. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25623. /** Makes the editor appear as if the label had been clicked by the user.
  25624. @see textWasEdited, setEditable
  25625. */
  25626. void showEditor();
  25627. /** Hides the editor if it was being shown.
  25628. @param discardCurrentEditorContents if true, the label's text will be
  25629. reset to whatever it was before the editor
  25630. was shown; if false, the current contents of the
  25631. editor will be used to set the label's text
  25632. before it is hidden.
  25633. */
  25634. void hideEditor (const bool discardCurrentEditorContents);
  25635. /** Returns true if the editor is currently focused and active. */
  25636. bool isBeingEdited() const throw();
  25637. juce_UseDebuggingNewOperator
  25638. protected:
  25639. /** @internal */
  25640. void paint (Graphics& g);
  25641. /** @internal */
  25642. void resized();
  25643. /** @internal */
  25644. void mouseUp (const MouseEvent& e);
  25645. /** @internal */
  25646. void mouseDoubleClick (const MouseEvent& e);
  25647. /** @internal */
  25648. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25649. /** @internal */
  25650. void componentParentHierarchyChanged (Component& component);
  25651. /** @internal */
  25652. void componentVisibilityChanged (Component& component);
  25653. /** @internal */
  25654. void inputAttemptWhenModal();
  25655. /** @internal */
  25656. void focusGained (FocusChangeType);
  25657. /** @internal */
  25658. void enablementChanged();
  25659. /** @internal */
  25660. KeyboardFocusTraverser* createFocusTraverser();
  25661. /** @internal */
  25662. void textEditorTextChanged (TextEditor& editor);
  25663. /** @internal */
  25664. void textEditorReturnKeyPressed (TextEditor& editor);
  25665. /** @internal */
  25666. void textEditorEscapeKeyPressed (TextEditor& editor);
  25667. /** @internal */
  25668. void textEditorFocusLost (TextEditor& editor);
  25669. /** @internal */
  25670. void colourChanged();
  25671. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25672. Subclasses can override this if they need to customise this component in some way.
  25673. */
  25674. virtual TextEditor* createEditorComponent();
  25675. /** Called after the user changes the text.
  25676. */
  25677. virtual void textWasEdited();
  25678. /** Called when the text has been altered.
  25679. */
  25680. virtual void textWasChanged();
  25681. /** Called when the text editor has just appeared, due to a user click or other
  25682. focus change.
  25683. */
  25684. virtual void editorShown (TextEditor* editorComponent);
  25685. /** Called when the text editor is going to be deleted, after editing has finished.
  25686. */
  25687. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  25688. private:
  25689. String text;
  25690. Font font;
  25691. Justification justification;
  25692. ScopedPointer <TextEditor> editor;
  25693. SortedSet <void*> listeners;
  25694. Component* ownerComponent;
  25695. ScopedPointer <ComponentDeletionWatcher> deletionWatcher;
  25696. int horizontalBorderSize, verticalBorderSize;
  25697. float minimumHorizontalScale;
  25698. bool editSingleClick : 1;
  25699. bool editDoubleClick : 1;
  25700. bool lossOfFocusDiscardsChanges : 1;
  25701. bool leftOfOwnerComp : 1;
  25702. bool updateFromTextEditorContents();
  25703. void callChangeListeners();
  25704. Label (const Label&);
  25705. const Label& operator= (const Label&);
  25706. };
  25707. #endif // __JUCE_LABEL_JUCEHEADER__
  25708. /********* End of inlined file: juce_Label.h *********/
  25709. class ComboBox;
  25710. /**
  25711. A class for receiving events from a ComboBox.
  25712. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25713. method, and it will be called when the selected item in the box changes.
  25714. @see ComboBox::addListener, ComboBox::removeListener
  25715. */
  25716. class JUCE_API ComboBoxListener
  25717. {
  25718. public:
  25719. /** Destructor. */
  25720. virtual ~ComboBoxListener() {}
  25721. /** Called when a ComboBox has its selected item changed.
  25722. */
  25723. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25724. };
  25725. /**
  25726. A component that lets the user choose from a drop-down list of choices.
  25727. The combo-box has a list of text strings, each with an associated id number,
  25728. that will be shown in the drop-down list when the user clicks on the component.
  25729. The currently selected choice is displayed in the combo-box, and this can
  25730. either be read-only text, or editable.
  25731. To find out when the user selects a different item or edits the text, you
  25732. can register a ComboBoxListener to receive callbacks.
  25733. @see ComboBoxListener
  25734. */
  25735. class JUCE_API ComboBox : public Component,
  25736. public SettableTooltipClient,
  25737. private LabelListener,
  25738. private AsyncUpdater
  25739. {
  25740. public:
  25741. /** Creates a combo-box.
  25742. On construction, the text field will be empty, so you should call the
  25743. setSelectedId() or setText() method to choose the initial value before
  25744. displaying it.
  25745. @param componentName the name to set for the component (see Component::setName())
  25746. */
  25747. ComboBox (const String& componentName);
  25748. /** Destructor. */
  25749. ~ComboBox();
  25750. /** Sets whether the test in the combo-box is editable.
  25751. The default state for a new ComboBox is non-editable, and can only be changed
  25752. by choosing from the drop-down list.
  25753. */
  25754. void setEditableText (const bool isEditable);
  25755. /** Returns true if the text is directly editable.
  25756. @see setEditableText
  25757. */
  25758. bool isTextEditable() const throw();
  25759. /** Sets the style of justification to be used for positioning the text.
  25760. The default is Justification::centredLeft. The text is displayed using a
  25761. Label component inside the ComboBox.
  25762. */
  25763. void setJustificationType (const Justification& justification) throw();
  25764. /** Returns the current justification for the text box.
  25765. @see setJustificationType
  25766. */
  25767. const Justification getJustificationType() const throw();
  25768. /** Adds an item to be shown in the drop-down list.
  25769. @param newItemText the text of the item to show in the list
  25770. @param newItemId an associated ID number that can be set or retrieved - see
  25771. getSelectedId() and setSelectedId()
  25772. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25773. */
  25774. void addItem (const String& newItemText,
  25775. const int newItemId) throw();
  25776. /** Adds a separator line to the drop-down list.
  25777. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25778. */
  25779. void addSeparator() throw();
  25780. /** Adds a heading to the drop-down list, so that you can group the items into
  25781. different sections.
  25782. The headings are indented slightly differently to set them apart from the
  25783. items on the list, and obviously can't be selected. You might want to add
  25784. separators between your sections too.
  25785. @see addItem, addSeparator
  25786. */
  25787. void addSectionHeading (const String& headingName) throw();
  25788. /** This allows items in the drop-down list to be selectively disabled.
  25789. When you add an item, it's enabled by default, but you can call this
  25790. method to change its status.
  25791. If you disable an item which is already selected, this won't change the
  25792. current selection - it just stops the user choosing that item from the list.
  25793. */
  25794. void setItemEnabled (const int itemId,
  25795. const bool shouldBeEnabled) throw();
  25796. /** Changes the text for an existing item.
  25797. */
  25798. void changeItemText (const int itemId,
  25799. const String& newText) throw();
  25800. /** Removes all the items from the drop-down list.
  25801. If this call causes the content to be cleared, then a change-message
  25802. will be broadcast unless dontSendChangeMessage is true.
  25803. @see addItem, removeItem, getNumItems
  25804. */
  25805. void clear (const bool dontSendChangeMessage = false);
  25806. /** Returns the number of items that have been added to the list.
  25807. Note that this doesn't include headers or separators.
  25808. */
  25809. int getNumItems() const throw();
  25810. /** Returns the text for one of the items in the list.
  25811. Note that this doesn't include headers or separators.
  25812. @param index the item's index from 0 to (getNumItems() - 1)
  25813. */
  25814. const String getItemText (const int index) const throw();
  25815. /** Returns the ID for one of the items in the list.
  25816. Note that this doesn't include headers or separators.
  25817. @param index the item's index from 0 to (getNumItems() - 1)
  25818. */
  25819. int getItemId (const int index) const throw();
  25820. /** Returns the ID of the item that's currently shown in the box.
  25821. If no item is selected, or if the text is editable and the user
  25822. has entered something which isn't one of the items in the list, then
  25823. this will return 0.
  25824. @see setSelectedId, getSelectedItemIndex, getText
  25825. */
  25826. int getSelectedId() const throw();
  25827. /** Sets one of the items to be the current selection.
  25828. This will set the ComboBox's text to that of the item that matches
  25829. this ID.
  25830. @param newItemId the new item to select
  25831. @param dontSendChangeMessage if set to true, this method won't trigger a
  25832. change notification
  25833. @see getSelectedId, setSelectedItemIndex, setText
  25834. */
  25835. void setSelectedId (const int newItemId,
  25836. const bool dontSendChangeMessage = false) throw();
  25837. /** Returns the index of the item that's currently shown in the box.
  25838. If no item is selected, or if the text is editable and the user
  25839. has entered something which isn't one of the items in the list, then
  25840. this will return -1.
  25841. @see setSelectedItemIndex, getSelectedId, getText
  25842. */
  25843. int getSelectedItemIndex() const throw();
  25844. /** Sets one of the items to be the current selection.
  25845. This will set the ComboBox's text to that of the item at the given
  25846. index in the list.
  25847. @param newItemIndex the new item to select
  25848. @param dontSendChangeMessage if set to true, this method won't trigger a
  25849. change notification
  25850. @see getSelectedItemIndex, setSelectedId, setText
  25851. */
  25852. void setSelectedItemIndex (const int newItemIndex,
  25853. const bool dontSendChangeMessage = false) throw();
  25854. /** Returns the text that is currently shown in the combo-box's text field.
  25855. If the ComboBox has editable text, then this text may have been edited
  25856. by the user; otherwise it will be one of the items from the list, or
  25857. possibly an empty string if nothing was selected.
  25858. @see setText, getSelectedId, getSelectedItemIndex
  25859. */
  25860. const String getText() const throw();
  25861. /** Sets the contents of the combo-box's text field.
  25862. The text passed-in will be set as the current text regardless of whether
  25863. it is one of the items in the list. If the current text isn't one of the
  25864. items, then getSelectedId() will return -1, otherwise it wil return
  25865. the approriate ID.
  25866. @param newText the text to select
  25867. @param dontSendChangeMessage if set to true, this method won't trigger a
  25868. change notification
  25869. @see getText
  25870. */
  25871. void setText (const String& newText,
  25872. const bool dontSendChangeMessage = false) throw();
  25873. /** Programmatically opens the text editor to allow the user to edit the current item.
  25874. This is the same effect as when the box is clicked-on.
  25875. @see Label::showEditor();
  25876. */
  25877. void showEditor();
  25878. /** Registers a listener that will be called when the box's content changes. */
  25879. void addListener (ComboBoxListener* const listener) throw();
  25880. /** Deregisters a previously-registered listener. */
  25881. void removeListener (ComboBoxListener* const listener) throw();
  25882. /** Sets a message to display when there is no item currently selected.
  25883. @see getTextWhenNothingSelected
  25884. */
  25885. void setTextWhenNothingSelected (const String& newMessage) throw();
  25886. /** Returns the text that is shown when no item is selected.
  25887. @see setTextWhenNothingSelected
  25888. */
  25889. const String getTextWhenNothingSelected() const throw();
  25890. /** Sets the message to show when there are no items in the list, and the user clicks
  25891. on the drop-down box.
  25892. By default it just says "no choices", but this lets you change it to something more
  25893. meaningful.
  25894. */
  25895. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25896. /** Returns the text shown when no items have been added to the list.
  25897. @see setTextWhenNoChoicesAvailable
  25898. */
  25899. const String getTextWhenNoChoicesAvailable() const throw();
  25900. /** Gives the ComboBox a tooltip. */
  25901. void setTooltip (const String& newTooltip);
  25902. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25903. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25904. methods.
  25905. To change the colours of the menu that pops up
  25906. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25907. */
  25908. enum ColourIds
  25909. {
  25910. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25911. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25912. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25913. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25914. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25915. };
  25916. /** @internal */
  25917. void labelTextChanged (Label*);
  25918. /** @internal */
  25919. void enablementChanged();
  25920. /** @internal */
  25921. void colourChanged();
  25922. /** @internal */
  25923. void focusGained (Component::FocusChangeType cause);
  25924. /** @internal */
  25925. void focusLost (Component::FocusChangeType cause);
  25926. /** @internal */
  25927. void handleAsyncUpdate();
  25928. /** @internal */
  25929. const String getTooltip() { return label->getTooltip(); }
  25930. /** @internal */
  25931. void mouseDown (const MouseEvent&);
  25932. /** @internal */
  25933. void mouseDrag (const MouseEvent&);
  25934. /** @internal */
  25935. void mouseUp (const MouseEvent&);
  25936. /** @internal */
  25937. void lookAndFeelChanged();
  25938. /** @internal */
  25939. void paint (Graphics&);
  25940. /** @internal */
  25941. void resized();
  25942. /** @internal */
  25943. bool keyStateChanged (const bool isKeyDown);
  25944. /** @internal */
  25945. bool keyPressed (const KeyPress&);
  25946. juce_UseDebuggingNewOperator
  25947. private:
  25948. struct ItemInfo
  25949. {
  25950. String name;
  25951. int itemId;
  25952. bool isEnabled : 1, isHeading : 1;
  25953. bool isSeparator() const throw();
  25954. bool isRealItem() const throw();
  25955. };
  25956. OwnedArray <ItemInfo> items;
  25957. int currentIndex;
  25958. bool isButtonDown;
  25959. bool separatorPending;
  25960. bool menuActive;
  25961. SortedSet <void*> listeners;
  25962. Label* label;
  25963. String textWhenNothingSelected, noChoicesMessage;
  25964. void showPopup();
  25965. ItemInfo* getItemForId (const int itemId) const throw();
  25966. ItemInfo* getItemForIndex (const int index) const throw();
  25967. ComboBox (const ComboBox&);
  25968. const ComboBox& operator= (const ComboBox&);
  25969. };
  25970. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25971. /********* End of inlined file: juce_ComboBox.h *********/
  25972. /**
  25973. Manages the state of some audio and midi i/o devices.
  25974. This class keeps tracks of a currently-selected audio device, through
  25975. with which it continuously streams data from an audio callback, as well as
  25976. one or more midi inputs.
  25977. The idea is that your application will create one global instance of this object,
  25978. and let it take care of creating and deleting specific types of audio devices
  25979. internally. So when the device is changed, your callbacks will just keep running
  25980. without having to worry about this.
  25981. The manager can save and reload all of its device settings as XML, which
  25982. makes it very easy for you to save and reload the audio setup of your
  25983. application.
  25984. And to make it easy to let the user change its settings, there's a component
  25985. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25986. device selection/sample-rate/latency controls.
  25987. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25988. call addAudioCallback() to register your audio callback with it, and use that to process
  25989. your audio data.
  25990. The manager also acts as a handy hub for incoming midi messages, allowing a
  25991. listener to register for messages from either a specific midi device, or from whatever
  25992. the current default midi input device is. The listener then doesn't have to worry about
  25993. re-registering with different midi devices if they are changed or deleted.
  25994. And yet another neat trick is that amount of CPU time being used is measured and
  25995. available with the getCpuUsage() method.
  25996. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25997. listeners whenever one of its settings is changed.
  25998. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25999. */
  26000. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  26001. {
  26002. public:
  26003. /** Creates a default AudioDeviceManager.
  26004. Initially no audio device will be selected. You should call the initialise() method
  26005. and register an audio callback with setAudioCallback() before it'll be able to
  26006. actually make any noise.
  26007. */
  26008. AudioDeviceManager();
  26009. /** Destructor. */
  26010. ~AudioDeviceManager();
  26011. /**
  26012. This structure holds a set of properties describing the current audio setup.
  26013. @see AudioDeviceManager::setAudioDeviceSetup()
  26014. */
  26015. struct JUCE_API AudioDeviceSetup
  26016. {
  26017. AudioDeviceSetup();
  26018. bool operator== (const AudioDeviceSetup& other) const;
  26019. /** The name of the audio device used for output.
  26020. The name has to be one of the ones listed by the AudioDeviceManager's currently
  26021. selected device type.
  26022. This may be the same as the input device.
  26023. */
  26024. String outputDeviceName;
  26025. /** The name of the audio device used for input.
  26026. This may be the same as the output device.
  26027. */
  26028. String inputDeviceName;
  26029. /** The current sample rate.
  26030. This rate is used for both the input and output devices.
  26031. */
  26032. double sampleRate;
  26033. /** The buffer size, in samples.
  26034. This buffer size is used for both the input and output devices.
  26035. */
  26036. int bufferSize;
  26037. /** The set of active input channels.
  26038. The bits that are set in this array indicate the channels of the
  26039. input device that are active.
  26040. */
  26041. BitArray inputChannels;
  26042. /** If this is true, it indicates that the inputChannels array
  26043. should be ignored, and instead, the device's default channels
  26044. should be used.
  26045. */
  26046. bool useDefaultInputChannels;
  26047. /** The set of active output channels.
  26048. The bits that are set in this array indicate the channels of the
  26049. input device that are active.
  26050. */
  26051. BitArray outputChannels;
  26052. /** If this is true, it indicates that the outputChannels array
  26053. should be ignored, and instead, the device's default channels
  26054. should be used.
  26055. */
  26056. bool useDefaultOutputChannels;
  26057. };
  26058. /** Opens a set of audio devices ready for use.
  26059. This will attempt to open either a default audio device, or one that was
  26060. previously saved as XML.
  26061. @param numInputChannelsNeeded a minimum number of input channels needed
  26062. by your app.
  26063. @param numOutputChannelsNeeded a minimum number of output channels to open
  26064. @param savedState either a previously-saved state that was produced
  26065. by createStateXml(), or 0 if you want the manager
  26066. to choose the best device to open.
  26067. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  26068. fails to open, then a default device will be used
  26069. instead. If false, then on failure, no device is
  26070. opened.
  26071. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  26072. name, then that will be used as the default device
  26073. (assuming that there wasn't one specified in the XML).
  26074. The string can actually be a simple wildcard, containing "*"
  26075. and "?" characters
  26076. @param preferredSetupOptions if this is non-null, the structure will be used as the
  26077. set of preferred settings when opening the device. If you
  26078. use this parameter, the preferredDefaultDeviceName
  26079. field will be ignored
  26080. @returns an error message if anything went wrong, or an empty string if it worked ok.
  26081. */
  26082. const String initialise (const int numInputChannelsNeeded,
  26083. const int numOutputChannelsNeeded,
  26084. const XmlElement* const savedState,
  26085. const bool selectDefaultDeviceOnFailure,
  26086. const String& preferredDefaultDeviceName = String::empty,
  26087. const AudioDeviceSetup* preferredSetupOptions = 0);
  26088. /** Returns some XML representing the current state of the manager.
  26089. This stores the current device, its samplerate, block size, etc, and
  26090. can be restored later with initialise().
  26091. */
  26092. XmlElement* createStateXml() const;
  26093. /** Returns the current device properties that are in use.
  26094. @see setAudioDeviceSetup
  26095. */
  26096. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  26097. /** Changes the current device or its settings.
  26098. If you want to change a device property, like the current sample rate or
  26099. block size, you can call getAudioDeviceSetup() to retrieve the current
  26100. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  26101. and pass it back into this method to apply the new settings.
  26102. @param newSetup the settings that you'd like to use
  26103. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  26104. settings will be taken as having been explicitly chosen by the
  26105. user, and the next time createStateXml() is called, these settings
  26106. will be returned. If it's false, then the device is treated as a
  26107. temporary or default device, and a call to createStateXml() will
  26108. return either the last settings that were made with treatAsChosenDevice
  26109. as true, or the last XML settings that were passed into initialise().
  26110. @returns an error message if anything went wrong, or an empty string if it worked ok.
  26111. @see getAudioDeviceSetup
  26112. */
  26113. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  26114. const bool treatAsChosenDevice);
  26115. /** Returns the currently-active audio device. */
  26116. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  26117. /** Returns the type of audio device currently in use.
  26118. @see setCurrentAudioDeviceType
  26119. */
  26120. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  26121. /** Returns the currently active audio device type object.
  26122. Don't keep a copy of this pointer - it's owned by the device manager and could
  26123. change at any time.
  26124. */
  26125. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  26126. /** Changes the class of audio device being used.
  26127. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  26128. this because there's only one type: CoreAudio.
  26129. For a list of types, see getAvailableDeviceTypes().
  26130. */
  26131. void setCurrentAudioDeviceType (const String& type,
  26132. const bool treatAsChosenDevice);
  26133. /** Closes the currently-open device.
  26134. You can call restartLastAudioDevice() later to reopen it in the same state
  26135. that it was just in.
  26136. */
  26137. void closeAudioDevice();
  26138. /** Tries to reload the last audio device that was running.
  26139. Note that this only reloads the last device that was running before
  26140. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  26141. and can only be called after a device has been opened with SetAudioDevice().
  26142. If a device is already open, this call will do nothing.
  26143. */
  26144. void restartLastAudioDevice();
  26145. /** Registers an audio callback to be used.
  26146. The manager will redirect callbacks from whatever audio device is currently
  26147. in use to all registered callback objects. If more than one callback is
  26148. active, they will all be given the same input data, and their outputs will
  26149. be summed.
  26150. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  26151. object before returning.
  26152. To remove a callback, use removeAudioCallback().
  26153. */
  26154. void addAudioCallback (AudioIODeviceCallback* newCallback);
  26155. /** Deregisters a previously added callback.
  26156. If necessary, this method will invoke audioDeviceStopped() on the callback
  26157. object before returning.
  26158. @see addAudioCallback
  26159. */
  26160. void removeAudioCallback (AudioIODeviceCallback* callback);
  26161. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  26162. Returns a value between 0 and 1.0
  26163. */
  26164. double getCpuUsage() const;
  26165. /** Enables or disables a midi input device.
  26166. The list of devices can be obtained with the MidiInput::getDevices() method.
  26167. Any incoming messages from enabled input devices will be forwarded on to all the
  26168. listeners that have been registered with the addMidiInputCallback() method. They
  26169. can either register for messages from a particular device, or from just the
  26170. "default" midi input.
  26171. Routing the midi input via an AudioDeviceManager means that when a listener
  26172. registers for the default midi input, this default device can be changed by the
  26173. manager without the listeners having to know about it or re-register.
  26174. It also means that a listener can stay registered for a midi input that is disabled
  26175. or not present, so that when the input is re-enabled, the listener will start
  26176. receiving messages again.
  26177. @see addMidiInputCallback, isMidiInputEnabled
  26178. */
  26179. void setMidiInputEnabled (const String& midiInputDeviceName,
  26180. const bool enabled);
  26181. /** Returns true if a given midi input device is being used.
  26182. @see setMidiInputEnabled
  26183. */
  26184. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  26185. /** Registers a listener for callbacks when midi events arrive from a midi input.
  26186. The device name can be empty to indicate that it wants events from whatever the
  26187. current "default" device is. Or it can be the name of one of the midi input devices
  26188. (see MidiInput::getDevices() for the names).
  26189. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  26190. events forwarded on to listeners.
  26191. */
  26192. void addMidiInputCallback (const String& midiInputDeviceName,
  26193. MidiInputCallback* callback);
  26194. /** Removes a listener that was previously registered with addMidiInputCallback().
  26195. */
  26196. void removeMidiInputCallback (const String& midiInputDeviceName,
  26197. MidiInputCallback* callback);
  26198. /** Sets a midi output device to use as the default.
  26199. The list of devices can be obtained with the MidiOutput::getDevices() method.
  26200. The specified device will be opened automatically and can be retrieved with the
  26201. getDefaultMidiOutput() method.
  26202. Pass in an empty string to deselect all devices. For the default device, you
  26203. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  26204. @see getDefaultMidiOutput, getDefaultMidiOutputName
  26205. */
  26206. void setDefaultMidiOutput (const String& deviceName);
  26207. /** Returns the name of the default midi output.
  26208. @see setDefaultMidiOutput, getDefaultMidiOutput
  26209. */
  26210. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  26211. /** Returns the current default midi output device.
  26212. If no device has been selected, or the device can't be opened, this will
  26213. return 0.
  26214. @see getDefaultMidiOutputName
  26215. */
  26216. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  26217. /** Returns a list of the types of device supported.
  26218. */
  26219. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  26220. /** Creates a list of available types.
  26221. This will add a set of new AudioIODeviceType objects to the specified list, to
  26222. represent each available types of device.
  26223. You can override this if your app needs to do something specific, like avoid
  26224. using DirectSound devices, etc.
  26225. */
  26226. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  26227. /** Plays a beep through the current audio device.
  26228. This is here to allow the audio setup UI panels to easily include a "test"
  26229. button so that the user can check where the audio is coming from.
  26230. */
  26231. void playTestSound();
  26232. /** Turns on level-measuring.
  26233. When enabled, the device manager will measure the peak input level
  26234. across all channels, and you can get this level by calling getCurrentInputLevel().
  26235. This is mainly intended for audio setup UI panels to use to create a mic
  26236. level display, so that the user can check that they've selected the right
  26237. device.
  26238. A simple filter is used to make the level decay smoothly, but this is
  26239. only intended for giving rough feedback, and not for any kind of accurate
  26240. measurement.
  26241. */
  26242. void enableInputLevelMeasurement (const bool enableMeasurement);
  26243. /** Returns the current input level.
  26244. To use this, you must first enable it by calling enableInputLevelMeasurement().
  26245. See enableInputLevelMeasurement() for more info.
  26246. */
  26247. double getCurrentInputLevel() const;
  26248. juce_UseDebuggingNewOperator
  26249. private:
  26250. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  26251. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  26252. AudioDeviceSetup currentSetup;
  26253. ScopedPointer <AudioIODevice> currentAudioDevice;
  26254. SortedSet <AudioIODeviceCallback*> callbacks;
  26255. int numInputChansNeeded, numOutputChansNeeded;
  26256. String currentDeviceType;
  26257. BitArray inputChannels, outputChannels;
  26258. ScopedPointer <XmlElement> lastExplicitSettings;
  26259. mutable bool listNeedsScanning;
  26260. bool useInputNames;
  26261. int inputLevelMeasurementEnabledCount;
  26262. double inputLevel;
  26263. ScopedPointer <AudioSampleBuffer> testSound;
  26264. int testSoundPosition;
  26265. AudioSampleBuffer tempBuffer;
  26266. StringArray midiInsFromXml;
  26267. OwnedArray <MidiInput> enabledMidiInputs;
  26268. Array <MidiInputCallback*> midiCallbacks;
  26269. Array <MidiInput*> midiCallbackDevices;
  26270. String defaultMidiOutputName;
  26271. ScopedPointer <MidiOutput> defaultMidiOutput;
  26272. CriticalSection audioCallbackLock, midiCallbackLock;
  26273. double cpuUsageMs, timeToCpuScale;
  26274. class CallbackHandler : public AudioIODeviceCallback,
  26275. public MidiInputCallback
  26276. {
  26277. public:
  26278. AudioDeviceManager* owner;
  26279. void audioDeviceIOCallback (const float** inputChannelData,
  26280. int totalNumInputChannels,
  26281. float** outputChannelData,
  26282. int totalNumOutputChannels,
  26283. int numSamples);
  26284. void audioDeviceAboutToStart (AudioIODevice*);
  26285. void audioDeviceStopped();
  26286. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26287. };
  26288. CallbackHandler callbackHandler;
  26289. friend class CallbackHandler;
  26290. void audioDeviceIOCallbackInt (const float** inputChannelData,
  26291. int totalNumInputChannels,
  26292. float** outputChannelData,
  26293. int totalNumOutputChannels,
  26294. int numSamples);
  26295. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  26296. void audioDeviceStoppedInt();
  26297. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  26298. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  26299. const BitArray& ins, const BitArray& outs);
  26300. void stopDevice();
  26301. void updateXml();
  26302. void createDeviceTypesIfNeeded();
  26303. void scanDevicesIfNeeded();
  26304. void deleteCurrentDevice();
  26305. double chooseBestSampleRate (double preferred) const;
  26306. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  26307. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  26308. AudioDeviceManager (const AudioDeviceManager&);
  26309. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  26310. };
  26311. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26312. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  26313. #endif
  26314. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26315. #endif
  26316. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26317. #endif
  26318. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26319. #endif
  26320. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  26321. #endif
  26322. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26323. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  26324. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26325. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26326. /**
  26327. A set of routines to convert buffers of 32-bit floating point data to and from
  26328. various integer formats.
  26329. */
  26330. class JUCE_API AudioDataConverters
  26331. {
  26332. public:
  26333. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  26334. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  26335. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  26336. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  26337. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26338. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26339. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26340. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26341. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  26342. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  26343. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  26344. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  26345. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26346. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26347. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26348. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26349. enum DataFormat
  26350. {
  26351. int16LE,
  26352. int16BE,
  26353. int24LE,
  26354. int24BE,
  26355. int32LE,
  26356. int32BE,
  26357. float32LE,
  26358. float32BE,
  26359. };
  26360. static void convertFloatToFormat (const DataFormat destFormat,
  26361. const float* source, void* dest, int numSamples);
  26362. static void convertFormatToFloat (const DataFormat sourceFormat,
  26363. const void* source, float* dest, int numSamples);
  26364. static void interleaveSamples (const float** source, float* dest,
  26365. const int numSamples, const int numChannels);
  26366. static void deinterleaveSamples (const float* source, float** dest,
  26367. const int numSamples, const int numChannels);
  26368. };
  26369. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26370. /********* End of inlined file: juce_AudioDataConverters.h *********/
  26371. #endif
  26372. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26373. #endif
  26374. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  26375. #endif
  26376. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  26377. #endif
  26378. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  26379. /********* Start of inlined file: juce_MidiFile.h *********/
  26380. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  26381. #define __JUCE_MIDIFILE_JUCEHEADER__
  26382. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  26383. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26384. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26385. /**
  26386. A sequence of timestamped midi messages.
  26387. This allows the sequence to be manipulated, and also to be read from and
  26388. written to a standard midi file.
  26389. @see MidiMessage, MidiFile
  26390. */
  26391. class JUCE_API MidiMessageSequence
  26392. {
  26393. public:
  26394. /** Creates an empty midi sequence object. */
  26395. MidiMessageSequence();
  26396. /** Creates a copy of another sequence. */
  26397. MidiMessageSequence (const MidiMessageSequence& other);
  26398. /** Replaces this sequence with another one. */
  26399. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  26400. /** Destructor. */
  26401. ~MidiMessageSequence();
  26402. /** Structure used to hold midi events in the sequence.
  26403. These structures act as 'handles' on the events as they are moved about in
  26404. the list, and make it quick to find the matching note-offs for note-on events.
  26405. @see MidiMessageSequence::getEventPointer
  26406. */
  26407. class MidiEventHolder
  26408. {
  26409. public:
  26410. /** Destructor. */
  26411. ~MidiEventHolder();
  26412. /** The message itself, whose timestamp is used to specify the event's time.
  26413. */
  26414. MidiMessage message;
  26415. /** The matching note-off event (if this is a note-on event).
  26416. If this isn't a note-on, this pointer will be null.
  26417. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  26418. note-offs up-to-date after events have been moved around in the sequence
  26419. or deleted.
  26420. */
  26421. MidiEventHolder* noteOffObject;
  26422. juce_UseDebuggingNewOperator
  26423. private:
  26424. friend class MidiMessageSequence;
  26425. MidiEventHolder (const MidiMessage& message);
  26426. };
  26427. /** Clears the sequence. */
  26428. void clear();
  26429. /** Returns the number of events in the sequence. */
  26430. int getNumEvents() const;
  26431. /** Returns a pointer to one of the events. */
  26432. MidiEventHolder* getEventPointer (const int index) const;
  26433. /** Returns the time of the note-up that matches the note-on at this index.
  26434. If the event at this index isn't a note-on, it'll just return 0.
  26435. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  26436. */
  26437. double getTimeOfMatchingKeyUp (const int index) const;
  26438. /** Returns the index of the note-up that matches the note-on at this index.
  26439. If the event at this index isn't a note-on, it'll just return -1.
  26440. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  26441. */
  26442. int getIndexOfMatchingKeyUp (const int index) const;
  26443. /** Returns the index of an event. */
  26444. int getIndexOf (MidiEventHolder* const event) const;
  26445. /** Returns the index of the first event on or after the given timestamp.
  26446. If the time is beyond the end of the sequence, this will return the
  26447. number of events.
  26448. */
  26449. int getNextIndexAtTime (const double timeStamp) const;
  26450. /** Returns the timestamp of the first event in the sequence.
  26451. @see getEndTime
  26452. */
  26453. double getStartTime() const;
  26454. /** Returns the timestamp of the last event in the sequence.
  26455. @see getStartTime
  26456. */
  26457. double getEndTime() const;
  26458. /** Returns the timestamp of the event at a given index.
  26459. If the index is out-of-range, this will return 0.0
  26460. */
  26461. double getEventTime (const int index) const;
  26462. /** Inserts a midi message into the sequence.
  26463. The index at which the new message gets inserted will depend on its timestamp,
  26464. because the sequence is kept sorted.
  26465. Remember to call updateMatchedPairs() after adding note-on events.
  26466. @param newMessage the new message to add (an internal copy will be made)
  26467. @param timeAdjustment an optional value to add to the timestamp of the message
  26468. that will be inserted
  26469. @see updateMatchedPairs
  26470. */
  26471. void addEvent (const MidiMessage& newMessage,
  26472. double timeAdjustment = 0);
  26473. /** Deletes one of the events in the sequence.
  26474. Remember to call updateMatchedPairs() after removing events.
  26475. @param index the index of the event to delete
  26476. @param deleteMatchingNoteUp whether to also remove the matching note-off
  26477. if the event you're removing is a note-on
  26478. */
  26479. void deleteEvent (const int index,
  26480. const bool deleteMatchingNoteUp);
  26481. /** Merges another sequence into this one.
  26482. Remember to call updateMatchedPairs() after using this method.
  26483. @param other the sequence to add from
  26484. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  26485. as they are read from the other sequence
  26486. @param firstAllowableDestTime events will not be added if their time is earlier
  26487. than this time. (This is after their time has been adjusted
  26488. by the timeAdjustmentDelta)
  26489. @param endOfAllowableDestTimes events will not be added if their time is equal to
  26490. or greater than this time. (This is after their time has
  26491. been adjusted by the timeAdjustmentDelta)
  26492. */
  26493. void addSequence (const MidiMessageSequence& other,
  26494. double timeAdjustmentDelta,
  26495. double firstAllowableDestTime,
  26496. double endOfAllowableDestTimes);
  26497. /** Makes sure all the note-on and note-off pairs are up-to-date.
  26498. Call this after moving messages about or deleting/adding messages, and it
  26499. will scan the list and make sure all the note-offs in the MidiEventHolder
  26500. structures are pointing at the correct ones.
  26501. */
  26502. void updateMatchedPairs();
  26503. /** Copies all the messages for a particular midi channel to another sequence.
  26504. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  26505. @param destSequence the sequence that the chosen events should be copied to
  26506. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  26507. channel) will also be copied across.
  26508. @see extractSysExMessages
  26509. */
  26510. void extractMidiChannelMessages (const int channelNumberToExtract,
  26511. MidiMessageSequence& destSequence,
  26512. const bool alsoIncludeMetaEvents) const;
  26513. /** Copies all midi sys-ex messages to another sequence.
  26514. @param destSequence this is the sequence to which any sys-exes in this sequence
  26515. will be added
  26516. @see extractMidiChannelMessages
  26517. */
  26518. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  26519. /** Removes any messages in this sequence that have a specific midi channel.
  26520. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  26521. */
  26522. void deleteMidiChannelMessages (const int channelNumberToRemove);
  26523. /** Removes any sys-ex messages from this sequence.
  26524. */
  26525. void deleteSysExMessages();
  26526. /** Adds an offset to the timestamps of all events in the sequence.
  26527. @param deltaTime the amount to add to each timestamp.
  26528. */
  26529. void addTimeToMessages (const double deltaTime);
  26530. /** Scans through the sequence to determine the state of any midi controllers at
  26531. a given time.
  26532. This will create a sequence of midi controller changes that can be
  26533. used to set all midi controllers to the state they would be in at the
  26534. specified time within this sequence.
  26535. As well as controllers, it will also recreate the midi program number
  26536. and pitch bend position.
  26537. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  26538. for other channels will be ignored.
  26539. @param time the time at which you want to find out the state - there are
  26540. no explicit units for this time measurement, it's the same units
  26541. as used for the timestamps of the messages
  26542. @param resultMessages an array to which midi controller-change messages will be added. This
  26543. will be the minimum number of controller changes to recreate the
  26544. state at the required time.
  26545. */
  26546. void createControllerUpdatesForTime (const int channelNumber,
  26547. const double time,
  26548. OwnedArray<MidiMessage>& resultMessages);
  26549. juce_UseDebuggingNewOperator
  26550. /** @internal */
  26551. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  26552. const MidiMessageSequence::MidiEventHolder* const second) throw();
  26553. private:
  26554. friend class MidiComparator;
  26555. friend class MidiFile;
  26556. OwnedArray <MidiEventHolder> list;
  26557. void sort();
  26558. };
  26559. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26560. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  26561. /**
  26562. Reads/writes standard midi format files.
  26563. To read a midi file, create a MidiFile object and call its readFrom() method. You
  26564. can then get the individual midi tracks from it using the getTrack() method.
  26565. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  26566. to it using the addTrack() method, and then call its writeTo() method to stream
  26567. it out.
  26568. @see MidiMessageSequence
  26569. */
  26570. class JUCE_API MidiFile
  26571. {
  26572. public:
  26573. /** Creates an empty MidiFile object.
  26574. */
  26575. MidiFile() throw();
  26576. /** Destructor. */
  26577. ~MidiFile() throw();
  26578. /** Returns the number of tracks in the file.
  26579. @see getTrack, addTrack
  26580. */
  26581. int getNumTracks() const throw();
  26582. /** Returns a pointer to one of the tracks in the file.
  26583. @returns a pointer to the track, or 0 if the index is out-of-range
  26584. @see getNumTracks, addTrack
  26585. */
  26586. const MidiMessageSequence* getTrack (const int index) const throw();
  26587. /** Adds a midi track to the file.
  26588. This will make its own internal copy of the sequence that is passed-in.
  26589. @see getNumTracks, getTrack
  26590. */
  26591. void addTrack (const MidiMessageSequence& trackSequence) throw();
  26592. /** Removes all midi tracks from the file.
  26593. @see getNumTracks
  26594. */
  26595. void clear() throw();
  26596. /** Returns the raw time format code that will be written to a stream.
  26597. After reading a midi file, this method will return the time-format that
  26598. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  26599. or setSmpteTimeFormat() methods.
  26600. If the value returned is positive, it indicates the number of midi ticks
  26601. per quarter-note - see setTicksPerQuarterNote().
  26602. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  26603. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  26604. */
  26605. short getTimeFormat() const throw();
  26606. /** Sets the time format to use when this file is written to a stream.
  26607. If this is called, the file will be written as bars/beats using the
  26608. specified resolution, rather than SMPTE absolute times, as would be
  26609. used if setSmpteTimeFormat() had been called instead.
  26610. @param ticksPerQuarterNote e.g. 96, 960
  26611. @see setSmpteTimeFormat
  26612. */
  26613. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  26614. /** Sets the time format to use when this file is written to a stream.
  26615. If this is called, the file will be written using absolute times, rather
  26616. than bars/beats as would be the case if setTicksPerBeat() had been called
  26617. instead.
  26618. @param framesPerSecond must be 24, 25, 29 or 30
  26619. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  26620. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  26621. timing, setSmpteTimeFormat (25, 40)
  26622. @see setTicksPerBeat
  26623. */
  26624. void setSmpteTimeFormat (const int framesPerSecond,
  26625. const int subframeResolution) throw();
  26626. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  26627. Useful for finding the positions of all the tempo changes in a file.
  26628. @param tempoChangeEvents a list to which all the events will be added
  26629. */
  26630. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  26631. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  26632. Useful for finding the positions of all the tempo changes in a file.
  26633. @param timeSigEvents a list to which all the events will be added
  26634. */
  26635. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  26636. /** Returns the latest timestamp in any of the tracks.
  26637. (Useful for finding the length of the file).
  26638. */
  26639. double getLastTimestamp() const;
  26640. /** Reads a midi file format stream.
  26641. After calling this, you can get the tracks that were read from the file by using the
  26642. getNumTracks() and getTrack() methods.
  26643. The timestamps of the midi events in the tracks will represent their positions in
  26644. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  26645. method.
  26646. @returns true if the stream was read successfully
  26647. */
  26648. bool readFrom (InputStream& sourceStream);
  26649. /** Writes the midi tracks as a standard midi file.
  26650. @returns true if the operation succeeded.
  26651. */
  26652. bool writeTo (OutputStream& destStream);
  26653. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  26654. This will use the midi time format and tempo/time signature info in the
  26655. tracks to convert all the timestamps to absolute values in seconds.
  26656. */
  26657. void convertTimestampTicksToSeconds();
  26658. juce_UseDebuggingNewOperator
  26659. /** @internal */
  26660. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  26661. const MidiMessageSequence::MidiEventHolder* const second) throw();
  26662. private:
  26663. OwnedArray <MidiMessageSequence> tracks;
  26664. short timeFormat;
  26665. MidiFile (const MidiFile&);
  26666. const MidiFile& operator= (const MidiFile&);
  26667. void readNextTrack (const char* data, int size);
  26668. void writeTrack (OutputStream& mainOut, const int trackNum);
  26669. };
  26670. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  26671. /********* End of inlined file: juce_MidiFile.h *********/
  26672. #endif
  26673. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26674. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  26675. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26676. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26677. class MidiKeyboardState;
  26678. /**
  26679. Receives events from a MidiKeyboardState object.
  26680. @see MidiKeyboardState
  26681. */
  26682. class JUCE_API MidiKeyboardStateListener
  26683. {
  26684. public:
  26685. MidiKeyboardStateListener() throw() {}
  26686. virtual ~MidiKeyboardStateListener() {}
  26687. /** Called when one of the MidiKeyboardState's keys is pressed.
  26688. This will be called synchronously when the state is either processing a
  26689. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  26690. when a note is being played with its MidiKeyboardState::noteOn() method.
  26691. Note that this callback could happen from an audio callback thread, so be
  26692. careful not to block, and avoid any UI activity in the callback.
  26693. */
  26694. virtual void handleNoteOn (MidiKeyboardState* source,
  26695. int midiChannel, int midiNoteNumber, float velocity) = 0;
  26696. /** Called when one of the MidiKeyboardState's keys is released.
  26697. This will be called synchronously when the state is either processing a
  26698. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  26699. when a note is being played with its MidiKeyboardState::noteOff() method.
  26700. Note that this callback could happen from an audio callback thread, so be
  26701. careful not to block, and avoid any UI activity in the callback.
  26702. */
  26703. virtual void handleNoteOff (MidiKeyboardState* source,
  26704. int midiChannel, int midiNoteNumber) = 0;
  26705. };
  26706. /**
  26707. Represents a piano keyboard, keeping track of which keys are currently pressed.
  26708. This object can parse a stream of midi events, using them to update its idea
  26709. of which keys are pressed for each individiual midi channel.
  26710. When keys go up or down, it can broadcast these events to listener objects.
  26711. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  26712. methods, and midi messages for these events will be merged into the
  26713. midi stream that gets processed by processNextMidiBuffer().
  26714. */
  26715. class JUCE_API MidiKeyboardState
  26716. {
  26717. public:
  26718. MidiKeyboardState();
  26719. ~MidiKeyboardState();
  26720. /** Resets the state of the object.
  26721. All internal data for all the channels is reset, but no events are sent as a
  26722. result.
  26723. If you want to release any keys that are currently down, and to send out note-up
  26724. midi messages for this, use the allNotesOff() method instead.
  26725. */
  26726. void reset();
  26727. /** Returns true if the given midi key is currently held down for the given midi channel.
  26728. The channel number must be between 1 and 16. If you want to see if any notes are
  26729. on for a range of channels, use the isNoteOnForChannels() method.
  26730. */
  26731. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  26732. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  26733. The channel mask has a bit set for each midi channel you want to test for - bit
  26734. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  26735. If a note is on for at least one of the specified channels, this returns true.
  26736. */
  26737. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  26738. /** Turns a specified note on.
  26739. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  26740. next call to processNextMidiBuffer().
  26741. It will also trigger a synchronous callback to the listeners to tell them that the key has
  26742. gone down.
  26743. */
  26744. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  26745. /** Turns a specified note off.
  26746. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  26747. next call to processNextMidiBuffer().
  26748. It will also trigger a synchronous callback to the listeners to tell them that the key has
  26749. gone up.
  26750. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  26751. */
  26752. void noteOff (const int midiChannel, const int midiNoteNumber);
  26753. /** This will turn off any currently-down notes for the given midi channel.
  26754. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  26755. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  26756. and events being added to the midi stream.
  26757. */
  26758. void allNotesOff (const int midiChannel);
  26759. /** Looks at a key-up/down event and uses it to update the state of this object.
  26760. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  26761. instead.
  26762. */
  26763. void processNextMidiEvent (const MidiMessage& message);
  26764. /** Scans a midi stream for up/down events and adds its own events to it.
  26765. This will look for any up/down events and use them to update the internal state,
  26766. synchronously making suitable callbacks to the listeners.
  26767. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  26768. and noteOff() calls will be added into the buffer.
  26769. Only the section of the buffer whose timestamps are between startSample and
  26770. (startSample + numSamples) will be affected, and any events added will be placed
  26771. between these times.
  26772. If you're going to use this method, you'll need to keep calling it regularly for
  26773. it to work satisfactorily.
  26774. To process a single midi event at a time, use the processNextMidiEvent() method
  26775. instead.
  26776. */
  26777. void processNextMidiBuffer (MidiBuffer& buffer,
  26778. const int startSample,
  26779. const int numSamples,
  26780. const bool injectIndirectEvents);
  26781. /** Registers a listener for callbacks when keys go up or down.
  26782. @see removeListener
  26783. */
  26784. void addListener (MidiKeyboardStateListener* const listener) throw();
  26785. /** Deregisters a listener.
  26786. @see addListener
  26787. */
  26788. void removeListener (MidiKeyboardStateListener* const listener) throw();
  26789. juce_UseDebuggingNewOperator
  26790. private:
  26791. CriticalSection lock;
  26792. uint16 noteStates [128];
  26793. MidiBuffer eventsToAdd;
  26794. VoidArray listeners;
  26795. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  26796. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  26797. MidiKeyboardState (const MidiKeyboardState&);
  26798. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  26799. };
  26800. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26801. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  26802. #endif
  26803. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  26804. #endif
  26805. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26806. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  26807. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26808. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26809. /**
  26810. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  26811. processing by a block-based audio callback.
  26812. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  26813. so it can easily use a midi input or keyboard component as its source.
  26814. @see MidiMessage, MidiInput
  26815. */
  26816. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  26817. public MidiInputCallback
  26818. {
  26819. public:
  26820. /** Creates a MidiMessageCollector. */
  26821. MidiMessageCollector();
  26822. /** Destructor. */
  26823. ~MidiMessageCollector();
  26824. /** Clears any messages from the queue.
  26825. You need to call this method before starting to use the collector, so that
  26826. it knows the correct sample rate to use.
  26827. */
  26828. void reset (const double sampleRate);
  26829. /** Takes an incoming real-time message and adds it to the queue.
  26830. The message's timestamp is taken, and it will be ready for retrieval as part
  26831. of the block returned by the next call to removeNextBlockOfMessages().
  26832. This method is fully thread-safe when overlapping calls are made with
  26833. removeNextBlockOfMessages().
  26834. */
  26835. void addMessageToQueue (const MidiMessage& message);
  26836. /** Removes all the pending messages from the queue as a buffer.
  26837. This will also correct the messages' timestamps to make sure they're in
  26838. the range 0 to numSamples - 1.
  26839. This call should be made regularly by something like an audio processing
  26840. callback, because the time that it happens is used in calculating the
  26841. midi event positions.
  26842. This method is fully thread-safe when overlapping calls are made with
  26843. addMessageToQueue().
  26844. */
  26845. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  26846. const int numSamples);
  26847. /** @internal */
  26848. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  26849. /** @internal */
  26850. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  26851. /** @internal */
  26852. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26853. juce_UseDebuggingNewOperator
  26854. private:
  26855. double lastCallbackTime;
  26856. CriticalSection midiCallbackLock;
  26857. MidiBuffer incomingMessages;
  26858. double sampleRate;
  26859. MidiMessageCollector (const MidiMessageCollector&);
  26860. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  26861. };
  26862. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26863. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  26864. #endif
  26865. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26866. #endif
  26867. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26868. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26869. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26870. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26871. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  26872. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26873. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26874. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  26875. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26876. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26877. /********* Start of inlined file: juce_AudioProcessor.h *********/
  26878. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  26879. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  26880. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  26881. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  26882. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  26883. class AudioProcessor;
  26884. /**
  26885. Base class for the component that acts as the GUI for an AudioProcessor.
  26886. Derive your editor component from this class, and create an instance of it
  26887. by overriding the AudioProcessor::createEditor() method.
  26888. @see AudioProcessor, GenericAudioProcessorEditor
  26889. */
  26890. class JUCE_API AudioProcessorEditor : public Component
  26891. {
  26892. protected:
  26893. /** Creates an editor for the specified processor.
  26894. */
  26895. AudioProcessorEditor (AudioProcessor* const owner);
  26896. public:
  26897. /** Destructor. */
  26898. ~AudioProcessorEditor();
  26899. /** Returns a pointer to the processor that this editor represents. */
  26900. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  26901. private:
  26902. AudioProcessor* const owner;
  26903. };
  26904. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  26905. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  26906. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  26907. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  26908. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  26909. class AudioProcessor;
  26910. /**
  26911. Base class for listeners that want to know about changes to an AudioProcessor.
  26912. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  26913. @see AudioProcessor
  26914. */
  26915. class JUCE_API AudioProcessorListener
  26916. {
  26917. public:
  26918. /** Destructor. */
  26919. virtual ~AudioProcessorListener() {}
  26920. /** Receives a callback when a parameter is changed.
  26921. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  26922. many audio processors will change their parameter during their audio callback.
  26923. This means that not only has your handler code got to be completely thread-safe,
  26924. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  26925. this event on your message thread, use this callback to trigger an AsyncUpdater
  26926. or ChangeBroadcaster which you can respond to on the message thread.
  26927. */
  26928. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  26929. int parameterIndex,
  26930. float newValue) = 0;
  26931. /** Called to indicate that something else in the plugin has changed, like its
  26932. program, number of parameters, etc.
  26933. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  26934. call it during their audio callback. This means that not only has your handler code
  26935. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  26936. blocking. If you need to handle this event on your message thread, use this callback
  26937. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  26938. message thread.
  26939. */
  26940. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  26941. /** Indicates that a parameter change gesture has started.
  26942. E.g. if the user is dragging a slider, this would be called when they first
  26943. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  26944. called when they release it.
  26945. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  26946. call it during their audio callback. This means that not only has your handler code
  26947. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  26948. blocking. If you need to handle this event on your message thread, use this callback
  26949. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  26950. message thread.
  26951. @see audioProcessorParameterChangeGestureEnd
  26952. */
  26953. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  26954. int parameterIndex);
  26955. /** Indicates that a parameter change gesture has finished.
  26956. E.g. if the user is dragging a slider, this would be called when they release
  26957. the mouse button.
  26958. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  26959. call it during their audio callback. This means that not only has your handler code
  26960. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  26961. blocking. If you need to handle this event on your message thread, use this callback
  26962. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  26963. message thread.
  26964. @see audioPluginParameterChangeGestureStart
  26965. */
  26966. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  26967. int parameterIndex);
  26968. };
  26969. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  26970. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  26971. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  26972. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  26973. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  26974. /**
  26975. A subclass of AudioPlayHead can supply information about the position and
  26976. status of a moving play head during audio playback.
  26977. One of these can be supplied to an AudioProcessor object so that it can find
  26978. out about the position of the audio that it is rendering.
  26979. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  26980. */
  26981. class JUCE_API AudioPlayHead
  26982. {
  26983. protected:
  26984. AudioPlayHead() {}
  26985. public:
  26986. virtual ~AudioPlayHead() {}
  26987. /** Frame rate types. */
  26988. enum FrameRateType
  26989. {
  26990. fps24 = 0,
  26991. fps25 = 1,
  26992. fps2997 = 2,
  26993. fps30 = 3,
  26994. fps2997drop = 4,
  26995. fps30drop = 5,
  26996. fpsUnknown = 99
  26997. };
  26998. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  26999. */
  27000. struct CurrentPositionInfo
  27001. {
  27002. /** The tempo in BPM */
  27003. double bpm;
  27004. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  27005. int timeSigNumerator;
  27006. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  27007. int timeSigDenominator;
  27008. /** The current play position, in seconds from the start of the edit. */
  27009. double timeInSeconds;
  27010. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  27011. double editOriginTime;
  27012. /** The current play position in pulses-per-quarter-note.
  27013. This is the number of quarter notes since the edit start.
  27014. */
  27015. double ppqPosition;
  27016. /** The position of the start of the last bar, in pulses-per-quarter-note.
  27017. This is the number of quarter notes from the start of the edit to the
  27018. start of the current bar.
  27019. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  27020. it's not available, the value will be 0.
  27021. */
  27022. double ppqPositionOfLastBarStart;
  27023. /** The video frame rate, if applicable. */
  27024. FrameRateType frameRate;
  27025. /** True if the transport is currently playing. */
  27026. bool isPlaying;
  27027. /** True if the transport is currently recording.
  27028. (When isRecording is true, then isPlaying will also be true).
  27029. */
  27030. bool isRecording;
  27031. };
  27032. /** Fills-in the given structure with details about the transport's
  27033. position at the start of the current processing block.
  27034. */
  27035. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  27036. };
  27037. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  27038. /********* End of inlined file: juce_AudioPlayHead.h *********/
  27039. /**
  27040. Base class for audio processing filters or plugins.
  27041. This is intended to act as a base class of audio filter that is general enough to
  27042. be wrapped as a VST, AU, RTAS, etc, or used internally.
  27043. It is also used by the plugin hosting code as the wrapper around an instance
  27044. of a loaded plugin.
  27045. Derive your filter class from this base class, and if you're building a plugin,
  27046. you should implement a global function called createPluginFilter() which creates
  27047. and returns a new instance of your subclass.
  27048. */
  27049. class JUCE_API AudioProcessor
  27050. {
  27051. protected:
  27052. /** Constructor.
  27053. You can also do your initialisation tasks in the initialiseFilterInfo()
  27054. call, which will be made after this object has been created.
  27055. */
  27056. AudioProcessor();
  27057. public:
  27058. /** Destructor. */
  27059. virtual ~AudioProcessor();
  27060. /** Returns the name of this processor.
  27061. */
  27062. virtual const String getName() const = 0;
  27063. /** Called before playback starts, to let the filter prepare itself.
  27064. The sample rate is the target sample rate, and will remain constant until
  27065. playback stops.
  27066. The estimatedSamplesPerBlock value is a HINT about the typical number of
  27067. samples that will be processed for each callback, but isn't any kind
  27068. of guarantee. The actual block sizes that the host uses may be different
  27069. each time the callback happens, and may be more or less than this value.
  27070. */
  27071. virtual void prepareToPlay (double sampleRate,
  27072. int estimatedSamplesPerBlock) = 0;
  27073. /** Called after playback has stopped, to let the filter free up any resources it
  27074. no longer needs.
  27075. */
  27076. virtual void releaseResources() = 0;
  27077. /** Renders the next block.
  27078. When this method is called, the buffer contains a number of channels which is
  27079. at least as great as the maximum number of input and output channels that
  27080. this filter is using. It will be filled with the filter's input data and
  27081. should be replaced with the filter's output.
  27082. So for example if your filter has 2 input channels and 4 output channels, then
  27083. the buffer will contain 4 channels, the first two being filled with the
  27084. input data. Your filter should read these, do its processing, and replace
  27085. the contents of all 4 channels with its output.
  27086. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  27087. all filled with data, and your filter should overwrite the first 2 of these
  27088. with its output. But be VERY careful not to write anything to the last 3
  27089. channels, as these might be mapped to memory that the host assumes is read-only!
  27090. Note that if you have more outputs than inputs, then only those channels that
  27091. correspond to an input channel are guaranteed to contain sensible data - e.g.
  27092. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  27093. but the last two channels may contain garbage, so you should be careful not to
  27094. let this pass through without being overwritten or cleared.
  27095. Also note that the buffer may have more channels than are strictly necessary,
  27096. but your should only read/write from the ones that your filter is supposed to
  27097. be using.
  27098. The number of samples in these buffers is NOT guaranteed to be the same for every
  27099. callback, and may be more or less than the estimated value given to prepareToPlay().
  27100. Your code must be able to cope with variable-sized blocks, or you're going to get
  27101. clicks and crashes!
  27102. If the filter is receiving a midi input, then the midiMessages array will be filled
  27103. with the midi messages for this block. Each message's timestamp will indicate the
  27104. message's time, as a number of samples from the start of the block.
  27105. Any messages left in the midi buffer when this method has finished are assumed to
  27106. be the filter's midi output. This means that your filter should be careful to
  27107. clear any incoming messages from the array if it doesn't want them to be passed-on.
  27108. Be very careful about what you do in this callback - it's going to be called by
  27109. the audio thread, so any kind of interaction with the UI is absolutely
  27110. out of the question. If you change a parameter in here and need to tell your UI to
  27111. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  27112. the UI components register as listeners, and then call sendChangeMessage() inside the
  27113. processBlock() method to send out an asynchronous message. You could also use
  27114. the AsyncUpdater class in a similar way.
  27115. */
  27116. virtual void processBlock (AudioSampleBuffer& buffer,
  27117. MidiBuffer& midiMessages) = 0;
  27118. /** Returns the current AudioPlayHead object that should be used to find
  27119. out the state and position of the playhead.
  27120. You can call this from your processBlock() method, and use the AudioPlayHead
  27121. object to get the details about the time of the start of the block currently
  27122. being processed.
  27123. If the host hasn't supplied a playhead object, this will return 0.
  27124. */
  27125. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  27126. /** Returns the current sample rate.
  27127. This can be called from your processBlock() method - it's not guaranteed
  27128. to be valid at any other time, and may return 0 if it's unknown.
  27129. */
  27130. double getSampleRate() const throw() { return sampleRate; }
  27131. /** Returns the current typical block size that is being used.
  27132. This can be called from your processBlock() method - it's not guaranteed
  27133. to be valid at any other time.
  27134. Remember it's not the ONLY block size that may be used when calling
  27135. processBlock, it's just the normal one. The actual block sizes used may be
  27136. larger or smaller than this, and will vary between successive calls.
  27137. */
  27138. int getBlockSize() const throw() { return blockSize; }
  27139. /** Returns the number of input channels that the host will be sending the filter.
  27140. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  27141. number of channels that your filter would prefer to have, and this method lets
  27142. you know how many the host is actually using.
  27143. Note that this method is only valid during or after the prepareToPlay()
  27144. method call. Until that point, the number of channels will be unknown.
  27145. */
  27146. int getNumInputChannels() const throw() { return numInputChannels; }
  27147. /** Returns the number of output channels that the host will be sending the filter.
  27148. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  27149. number of channels that your filter would prefer to have, and this method lets
  27150. you know how many the host is actually using.
  27151. Note that this method is only valid during or after the prepareToPlay()
  27152. method call. Until that point, the number of channels will be unknown.
  27153. */
  27154. int getNumOutputChannels() const throw() { return numOutputChannels; }
  27155. /** Returns the name of one of the input channels, as returned by the host.
  27156. The host might not supply very useful names for channels, and this might be
  27157. something like "1", "2", "left", "right", etc.
  27158. */
  27159. virtual const String getInputChannelName (const int channelIndex) const = 0;
  27160. /** Returns the name of one of the output channels, as returned by the host.
  27161. The host might not supply very useful names for channels, and this might be
  27162. something like "1", "2", "left", "right", etc.
  27163. */
  27164. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  27165. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  27166. virtual bool isInputChannelStereoPair (int index) const = 0;
  27167. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  27168. virtual bool isOutputChannelStereoPair (int index) const = 0;
  27169. /** This returns the number of samples delay that the filter imposes on the audio
  27170. passing through it.
  27171. The host will call this to find the latency - the filter itself should set this value
  27172. by calling setLatencySamples() as soon as it can during its initialisation.
  27173. */
  27174. int getLatencySamples() const throw() { return latencySamples; }
  27175. /** The filter should call this to set the number of samples delay that it introduces.
  27176. The filter should call this as soon as it can during initialisation, and can call it
  27177. later if the value changes.
  27178. */
  27179. void setLatencySamples (const int newLatency);
  27180. /** Returns true if the processor wants midi messages. */
  27181. virtual bool acceptsMidi() const = 0;
  27182. /** Returns true if the processor produces midi messages. */
  27183. virtual bool producesMidi() const = 0;
  27184. /** This returns a critical section that will automatically be locked while the host
  27185. is calling the processBlock() method.
  27186. Use it from your UI or other threads to lock access to variables that are used
  27187. by the process callback, but obviously be careful not to keep it locked for
  27188. too long, because that could cause stuttering playback. If you need to do something
  27189. that'll take a long time and need the processing to stop while it happens, use the
  27190. suspendProcessing() method instead.
  27191. @see suspendProcessing
  27192. */
  27193. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  27194. /** Enables and disables the processing callback.
  27195. If you need to do something time-consuming on a thread and would like to make sure
  27196. the audio processing callback doesn't happen until you've finished, use this
  27197. to disable the callback and re-enable it again afterwards.
  27198. E.g.
  27199. @code
  27200. void loadNewPatch()
  27201. {
  27202. suspendProcessing (true);
  27203. ..do something that takes ages..
  27204. suspendProcessing (false);
  27205. }
  27206. @endcode
  27207. If the host tries to make an audio callback while processing is suspended, the
  27208. filter will return an empty buffer, but won't block the audio thread like it would
  27209. do if you use the getCallbackLock() critical section to synchronise access.
  27210. If you're going to use this, your processBlock() method must call isSuspended() and
  27211. check whether it's suspended or not. If it is, then it should skip doing any real
  27212. processing, either emitting silence or passing the input through unchanged.
  27213. @see getCallbackLock
  27214. */
  27215. void suspendProcessing (const bool shouldBeSuspended);
  27216. /** Returns true if processing is currently suspended.
  27217. @see suspendProcessing
  27218. */
  27219. bool isSuspended() const throw() { return suspended; }
  27220. /** A plugin can override this to be told when it should reset any playing voices.
  27221. The default implementation does nothing, but a host may call this to tell the
  27222. plugin that it should stop any tails or sounds that have been left running.
  27223. */
  27224. virtual void reset();
  27225. /** Returns true if the processor is being run in an offline mode for rendering.
  27226. If the processor is being run live on realtime signals, this returns false.
  27227. If the mode is unknown, this will assume it's realtime and return false.
  27228. This value may be unreliable until the prepareToPlay() method has been called,
  27229. and could change each time prepareToPlay() is called.
  27230. @see setNonRealtime()
  27231. */
  27232. bool isNonRealtime() const throw() { return nonRealtime; }
  27233. /** Called by the host to tell this processor whether it's being used in a non-realime
  27234. capacity for offline rendering or bouncing.
  27235. Whatever value is passed-in will be
  27236. */
  27237. void setNonRealtime (const bool isNonRealtime) throw();
  27238. /** Creates the filter's UI.
  27239. This can return 0 if you want a UI-less filter, in which case the host may create
  27240. a generic UI that lets the user twiddle the parameters directly.
  27241. If you do want to pass back a component, the component should be created and set to
  27242. the correct size before returning it.
  27243. Remember not to do anything silly like allowing your filter to keep a pointer to
  27244. the component that gets created - it could be deleted later without any warning, which
  27245. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  27246. The correct way to handle the connection between an editor component and its
  27247. filter is to use something like a ChangeBroadcaster so that the editor can
  27248. register itself as a listener, and be told when a change occurs. This lets them
  27249. safely unregister themselves when they are deleted.
  27250. Here are a few things to bear in mind when writing an editor:
  27251. - Initially there won't be an editor, until the user opens one, or they might
  27252. not open one at all. Your filter mustn't rely on it being there.
  27253. - An editor object may be deleted and a replacement one created again at any time.
  27254. - It's safe to assume that an editor will be deleted before its filter.
  27255. */
  27256. virtual AudioProcessorEditor* createEditor() = 0;
  27257. /** Returns the active editor, if there is one.
  27258. Bear in mind this can return 0, even if an editor has previously been
  27259. opened.
  27260. */
  27261. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  27262. /** Returns the active editor, or if there isn't one, it will create one.
  27263. This may call createEditor() internally to create the component.
  27264. */
  27265. AudioProcessorEditor* createEditorIfNeeded();
  27266. /** This must return the correct value immediately after the object has been
  27267. created, and mustn't change the number of parameters later.
  27268. */
  27269. virtual int getNumParameters() = 0;
  27270. /** Returns the name of a particular parameter. */
  27271. virtual const String getParameterName (int parameterIndex) = 0;
  27272. /** Called by the host to find out the value of one of the filter's parameters.
  27273. The host will expect the value returned to be between 0 and 1.0.
  27274. This could be called quite frequently, so try to make your code efficient.
  27275. It's also likely to be called by non-UI threads, so the code in here should
  27276. be thread-aware.
  27277. */
  27278. virtual float getParameter (int parameterIndex) = 0;
  27279. /** Returns the value of a parameter as a text string. */
  27280. virtual const String getParameterText (int parameterIndex) = 0;
  27281. /** The host will call this method to change the value of one of the filter's parameters.
  27282. The host may call this at any time, including during the audio processing
  27283. callback, so the filter has to process this very fast and avoid blocking.
  27284. If you want to set the value of a parameter internally, e.g. from your
  27285. editor component, then don't call this directly - instead, use the
  27286. setParameterNotifyingHost() method, which will also send a message to
  27287. the host telling it about the change. If the message isn't sent, the host
  27288. won't be able to automate your parameters properly.
  27289. The value passed will be between 0 and 1.0.
  27290. */
  27291. virtual void setParameter (int parameterIndex,
  27292. float newValue) = 0;
  27293. /** Your filter can call this when it needs to change one of its parameters.
  27294. This could happen when the editor or some other internal operation changes
  27295. a parameter. This method will call the setParameter() method to change the
  27296. value, and will then send a message to the host telling it about the change.
  27297. Note that to make sure the host correctly handles automation, you should call
  27298. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  27299. tell the host when the user has started and stopped changing the parameter.
  27300. */
  27301. void setParameterNotifyingHost (int parameterIndex,
  27302. float newValue);
  27303. /** Returns true if the host can automate this parameter.
  27304. By default, this returns true for all parameters.
  27305. */
  27306. virtual bool isParameterAutomatable (int parameterIndex) const;
  27307. /** Should return true if this parameter is a "meta" parameter.
  27308. A meta-parameter is a parameter that changes other params. It is used
  27309. by some hosts (e.g. AudioUnit hosts).
  27310. By default this returns false.
  27311. */
  27312. virtual bool isMetaParameter (int parameterIndex) const;
  27313. /** Sends a signal to the host to tell it that the user is about to start changing this
  27314. parameter.
  27315. This allows the host to know when a parameter is actively being held by the user, and
  27316. it may use this information to help it record automation.
  27317. If you call this, it must be matched by a later call to endParameterChangeGesture().
  27318. */
  27319. void beginParameterChangeGesture (int parameterIndex);
  27320. /** Tells the host that the user has finished changing this parameter.
  27321. This allows the host to know when a parameter is actively being held by the user, and
  27322. it may use this information to help it record automation.
  27323. A call to this method must follow a call to beginParameterChangeGesture().
  27324. */
  27325. void endParameterChangeGesture (int parameterIndex);
  27326. /** The filter can call this when something (apart from a parameter value) has changed.
  27327. It sends a hint to the host that something like the program, number of parameters,
  27328. etc, has changed, and that it should update itself.
  27329. */
  27330. void updateHostDisplay();
  27331. /** Returns the number of preset programs the filter supports.
  27332. The value returned must be valid as soon as this object is created, and
  27333. must not change over its lifetime.
  27334. This value shouldn't be less than 1.
  27335. */
  27336. virtual int getNumPrograms() = 0;
  27337. /** Returns the number of the currently active program.
  27338. */
  27339. virtual int getCurrentProgram() = 0;
  27340. /** Called by the host to change the current program.
  27341. */
  27342. virtual void setCurrentProgram (int index) = 0;
  27343. /** Must return the name of a given program. */
  27344. virtual const String getProgramName (int index) = 0;
  27345. /** Called by the host to rename a program.
  27346. */
  27347. virtual void changeProgramName (int index, const String& newName) = 0;
  27348. /** The host will call this method when it wants to save the filter's internal state.
  27349. This must copy any info about the filter's state into the block of memory provided,
  27350. so that the host can store this and later restore it using setStateInformation().
  27351. Note that there's also a getCurrentProgramStateInformation() method, which only
  27352. stores the current program, not the state of the entire filter.
  27353. See also the helper function copyXmlToBinary() for storing settings as XML.
  27354. @see getCurrentProgramStateInformation
  27355. */
  27356. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  27357. /** The host will call this method if it wants to save the state of just the filter's
  27358. current program.
  27359. Unlike getStateInformation, this should only return the current program's state.
  27360. Not all hosts support this, and if you don't implement it, the base class
  27361. method just calls getStateInformation() instead. If you do implement it, be
  27362. sure to also implement getCurrentProgramStateInformation.
  27363. @see getStateInformation, setCurrentProgramStateInformation
  27364. */
  27365. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  27366. /** This must restore the filter's state from a block of data previously created
  27367. using getStateInformation().
  27368. Note that there's also a setCurrentProgramStateInformation() method, which tries
  27369. to restore just the current program, not the state of the entire filter.
  27370. See also the helper function getXmlFromBinary() for loading settings as XML.
  27371. @see setCurrentProgramStateInformation
  27372. */
  27373. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  27374. /** The host will call this method if it wants to restore the state of just the filter's
  27375. current program.
  27376. Not all hosts support this, and if you don't implement it, the base class
  27377. method just calls setStateInformation() instead. If you do implement it, be
  27378. sure to also implement getCurrentProgramStateInformation.
  27379. @see setStateInformation, getCurrentProgramStateInformation
  27380. */
  27381. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27382. /** Adds a listener that will be called when an aspect of this processor changes. */
  27383. void addListener (AudioProcessorListener* const newListener) throw();
  27384. /** Removes a previously added listener. */
  27385. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  27386. /** Not for public use - this is called before deleting an editor component. */
  27387. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  27388. /** Not for public use - this is called to initialise the processor. */
  27389. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  27390. /** Not for public use - this is called to initialise the processor before playing. */
  27391. void setPlayConfigDetails (const int numIns, const int numOuts,
  27392. const double sampleRate,
  27393. const int blockSize) throw();
  27394. juce_UseDebuggingNewOperator
  27395. protected:
  27396. /** Helper function that just converts an xml element into a binary blob.
  27397. Use this in your filter's getStateInformation() method if you want to
  27398. store its state as xml.
  27399. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  27400. from a binary blob.
  27401. */
  27402. static void copyXmlToBinary (const XmlElement& xml,
  27403. JUCE_NAMESPACE::MemoryBlock& destData);
  27404. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  27405. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  27406. an XmlElement object that the caller must delete when no longer needed.
  27407. */
  27408. static XmlElement* getXmlFromBinary (const void* data,
  27409. const int sizeInBytes);
  27410. /** @internal */
  27411. AudioPlayHead* playHead;
  27412. /** @internal */
  27413. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  27414. private:
  27415. VoidArray listeners;
  27416. AudioProcessorEditor* activeEditor;
  27417. double sampleRate;
  27418. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  27419. bool suspended, nonRealtime;
  27420. CriticalSection callbackLock, listenerLock;
  27421. #ifdef JUCE_DEBUG
  27422. BitArray changingParams;
  27423. #endif
  27424. AudioProcessor (const AudioProcessor&);
  27425. const AudioProcessor& operator= (const AudioProcessor&);
  27426. };
  27427. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  27428. /********* End of inlined file: juce_AudioProcessor.h *********/
  27429. /********* Start of inlined file: juce_PluginDescription.h *********/
  27430. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27431. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27432. /**
  27433. A small class to represent some facts about a particular type of plugin.
  27434. This class is for storing and managing the details about a plugin without
  27435. actually having to load an instance of it.
  27436. A KnownPluginList contains a list of PluginDescription objects.
  27437. @see KnownPluginList
  27438. */
  27439. class JUCE_API PluginDescription
  27440. {
  27441. public:
  27442. PluginDescription() throw();
  27443. PluginDescription (const PluginDescription& other) throw();
  27444. const PluginDescription& operator= (const PluginDescription& other) throw();
  27445. ~PluginDescription() throw();
  27446. /** The name of the plugin. */
  27447. String name;
  27448. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  27449. */
  27450. String pluginFormatName;
  27451. /** A category, such as "Dynamics", "Reverbs", etc.
  27452. */
  27453. String category;
  27454. /** The manufacturer. */
  27455. String manufacturerName;
  27456. /** The version. This string doesn't have any particular format. */
  27457. String version;
  27458. /** Either the file containing the plugin module, or some other unique way
  27459. of identifying it.
  27460. E.g. for an AU, this would be an ID string that the component manager
  27461. could use to retrieve the plugin. For a VST, it's the file path.
  27462. */
  27463. String fileOrIdentifier;
  27464. /** The last time the plugin file was changed.
  27465. This is handy when scanning for new or changed plugins.
  27466. */
  27467. Time lastFileModTime;
  27468. /** A unique ID for the plugin.
  27469. Note that this might not be unique between formats, e.g. a VST and some
  27470. other format might actually have the same id.
  27471. @see createIdentifierString
  27472. */
  27473. int uid;
  27474. /** True if the plugin identifies itself as a synthesiser. */
  27475. bool isInstrument;
  27476. /** The number of inputs. */
  27477. int numInputChannels;
  27478. /** The number of outputs. */
  27479. int numOutputChannels;
  27480. /** Returns true if the two descriptions refer the the same plugin.
  27481. This isn't quite as simple as them just having the same file (because of
  27482. shell plugins).
  27483. */
  27484. bool isDuplicateOf (const PluginDescription& other) const;
  27485. /** Returns a string that can be saved and used to uniquely identify the
  27486. plugin again.
  27487. This contains less info than the XML encoding, and is independent of the
  27488. plugin's file location, so can be used to store a plugin ID for use
  27489. across different machines.
  27490. */
  27491. const String createIdentifierString() const throw();
  27492. /** Creates an XML object containing these details.
  27493. @see loadFromXml
  27494. */
  27495. XmlElement* createXml() const;
  27496. /** Reloads the info in this structure from an XML record that was previously
  27497. saved with createXML().
  27498. Returns true if the XML was a valid plugin description.
  27499. */
  27500. bool loadFromXml (const XmlElement& xml);
  27501. juce_UseDebuggingNewOperator
  27502. };
  27503. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27504. /********* End of inlined file: juce_PluginDescription.h *********/
  27505. /**
  27506. Base class for an active instance of a plugin.
  27507. This derives from the AudioProcessor class, and adds some extra functionality
  27508. that helps when wrapping dynamically loaded plugins.
  27509. @see AudioProcessor, AudioPluginFormat
  27510. */
  27511. class JUCE_API AudioPluginInstance : public AudioProcessor
  27512. {
  27513. public:
  27514. /** Destructor.
  27515. Make sure that you delete any UI components that belong to this plugin before
  27516. deleting the plugin.
  27517. */
  27518. virtual ~AudioPluginInstance();
  27519. /** Fills-in the appropriate parts of this plugin description object.
  27520. */
  27521. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  27522. juce_UseDebuggingNewOperator
  27523. protected:
  27524. AudioPluginInstance();
  27525. AudioPluginInstance (const AudioPluginInstance&);
  27526. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  27527. };
  27528. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27529. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  27530. class PluginDescription;
  27531. /**
  27532. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  27533. Use the static getNumFormats() and getFormat() calls to find the types
  27534. of format that are available.
  27535. */
  27536. class JUCE_API AudioPluginFormat
  27537. {
  27538. public:
  27539. /** Destructor. */
  27540. virtual ~AudioPluginFormat();
  27541. /** Returns the format name.
  27542. E.g. "VST", "AudioUnit", etc.
  27543. */
  27544. virtual const String getName() const = 0;
  27545. /** This tries to create descriptions for all the plugin types available in
  27546. a binary module file.
  27547. The file will be some kind of DLL or bundle.
  27548. Normally there will only be one type returned, but some plugins
  27549. (e.g. VST shells) can use a single DLL to create a set of different plugin
  27550. subtypes, so in that case, each subtype is returned as a separate object.
  27551. */
  27552. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27553. const String& fileOrIdentifier) = 0;
  27554. /** Tries to recreate a type from a previously generated PluginDescription.
  27555. @see PluginDescription::createInstance
  27556. */
  27557. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  27558. /** Should do a quick check to see if this file or directory might be a plugin of
  27559. this format.
  27560. This is for searching for potential files, so it shouldn't actually try to
  27561. load the plugin or do anything time-consuming.
  27562. */
  27563. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  27564. /** Returns a readable version of the name of the plugin that this identifier refers to.
  27565. */
  27566. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  27567. /** Checks whether this plugin could possibly be loaded.
  27568. It doesn't actually need to load it, just to check whether the file or component
  27569. still exists.
  27570. */
  27571. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  27572. /** Searches a suggested set of directories for any plugins in this format.
  27573. The path might be ignored, e.g. by AUs, which are found by the OS rather
  27574. than manually.
  27575. */
  27576. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  27577. const bool recursive) = 0;
  27578. /** Returns the typical places to look for this kind of plugin.
  27579. Note that if this returns no paths, it means that the format can't be scanned-for
  27580. (i.e. it's an internal format that doesn't live in files)
  27581. */
  27582. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  27583. juce_UseDebuggingNewOperator
  27584. protected:
  27585. AudioPluginFormat() throw();
  27586. AudioPluginFormat (const AudioPluginFormat&);
  27587. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  27588. };
  27589. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27590. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  27591. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  27592. /**
  27593. Implements a plugin format manager for AudioUnits.
  27594. */
  27595. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  27596. {
  27597. public:
  27598. AudioUnitPluginFormat();
  27599. ~AudioUnitPluginFormat();
  27600. const String getName() const { return "AudioUnit"; }
  27601. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27602. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27603. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27604. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27605. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27606. bool doesPluginStillExist (const PluginDescription& desc);
  27607. const FileSearchPath getDefaultLocationsToSearch();
  27608. juce_UseDebuggingNewOperator
  27609. private:
  27610. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  27611. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  27612. };
  27613. #endif
  27614. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27615. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  27616. #endif
  27617. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27618. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  27619. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27620. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27621. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  27622. // Sorry, this file is just a placeholder at the moment!...
  27623. /**
  27624. Implements a plugin format manager for DirectX plugins.
  27625. */
  27626. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  27627. {
  27628. public:
  27629. DirectXPluginFormat();
  27630. ~DirectXPluginFormat();
  27631. const String getName() const { return "DirectX"; }
  27632. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27633. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27634. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27635. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  27636. const FileSearchPath getDefaultLocationsToSearch();
  27637. juce_UseDebuggingNewOperator
  27638. private:
  27639. DirectXPluginFormat (const DirectXPluginFormat&);
  27640. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  27641. };
  27642. #endif
  27643. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27644. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  27645. #endif
  27646. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27647. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  27648. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27649. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27650. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  27651. // Sorry, this file is just a placeholder at the moment!...
  27652. /**
  27653. Implements a plugin format manager for DirectX plugins.
  27654. */
  27655. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  27656. {
  27657. public:
  27658. LADSPAPluginFormat();
  27659. ~LADSPAPluginFormat();
  27660. const String getName() const { return "LADSPA"; }
  27661. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27662. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27663. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27664. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  27665. const FileSearchPath getDefaultLocationsToSearch();
  27666. juce_UseDebuggingNewOperator
  27667. private:
  27668. LADSPAPluginFormat (const LADSPAPluginFormat&);
  27669. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  27670. };
  27671. #endif
  27672. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27673. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  27674. #endif
  27675. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27676. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  27677. #ifdef __aeffect__
  27678. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27679. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27680. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  27681. events to the list.
  27682. This is used by both the VST hosting code and the plugin wrapper.
  27683. */
  27684. class VSTMidiEventList
  27685. {
  27686. public:
  27687. VSTMidiEventList()
  27688. : numEventsUsed (0), numEventsAllocated (0)
  27689. {
  27690. }
  27691. ~VSTMidiEventList()
  27692. {
  27693. freeEvents();
  27694. }
  27695. void clear()
  27696. {
  27697. numEventsUsed = 0;
  27698. if (events != 0)
  27699. events->numEvents = 0;
  27700. }
  27701. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  27702. {
  27703. ensureSize (numEventsUsed + 1);
  27704. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  27705. events->numEvents = ++numEventsUsed;
  27706. if (numBytes <= 4)
  27707. {
  27708. if (e->type == kVstSysExType)
  27709. {
  27710. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27711. e->type = kVstMidiType;
  27712. e->byteSize = sizeof (VstMidiEvent);
  27713. e->noteLength = 0;
  27714. e->noteOffset = 0;
  27715. e->detune = 0;
  27716. e->noteOffVelocity = 0;
  27717. }
  27718. e->deltaFrames = frameOffset;
  27719. memcpy (e->midiData, midiData, numBytes);
  27720. }
  27721. else
  27722. {
  27723. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  27724. if (se->type == kVstSysExType)
  27725. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  27726. else
  27727. se->sysexDump = (char*) juce_malloc (numBytes);
  27728. memcpy (se->sysexDump, midiData, numBytes);
  27729. se->type = kVstSysExType;
  27730. se->byteSize = sizeof (VstMidiSysexEvent);
  27731. se->deltaFrames = frameOffset;
  27732. se->flags = 0;
  27733. se->dumpBytes = numBytes;
  27734. se->resvd1 = 0;
  27735. se->resvd2 = 0;
  27736. }
  27737. }
  27738. // Handy method to pull the events out of an event buffer supplied by the host
  27739. // or plugin.
  27740. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  27741. {
  27742. for (int i = 0; i < events->numEvents; ++i)
  27743. {
  27744. const VstEvent* const e = events->events[i];
  27745. if (e != 0)
  27746. {
  27747. if (e->type == kVstMidiType)
  27748. {
  27749. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  27750. 4, e->deltaFrames);
  27751. }
  27752. else if (e->type == kVstSysExType)
  27753. {
  27754. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  27755. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  27756. e->deltaFrames);
  27757. }
  27758. }
  27759. }
  27760. }
  27761. void ensureSize (int numEventsNeeded)
  27762. {
  27763. if (numEventsNeeded > numEventsAllocated)
  27764. {
  27765. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  27766. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  27767. if (events == 0)
  27768. events.calloc (size, 1);
  27769. else
  27770. events.realloc (size, 1);
  27771. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  27772. {
  27773. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  27774. (int) sizeof (VstMidiSysexEvent)));
  27775. e->type = kVstMidiType;
  27776. e->byteSize = sizeof (VstMidiEvent);
  27777. events->events[i] = (VstEvent*) e;
  27778. }
  27779. numEventsAllocated = numEventsNeeded;
  27780. }
  27781. }
  27782. void freeEvents()
  27783. {
  27784. if (events != 0)
  27785. {
  27786. for (int i = numEventsAllocated; --i >= 0;)
  27787. {
  27788. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  27789. if (e->type == kVstSysExType)
  27790. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27791. juce_free (e);
  27792. }
  27793. events.free();
  27794. numEventsUsed = 0;
  27795. numEventsAllocated = 0;
  27796. }
  27797. }
  27798. HeapBlock <VstEvents> events;
  27799. private:
  27800. int numEventsUsed, numEventsAllocated;
  27801. };
  27802. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27803. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27804. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  27805. #endif
  27806. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27807. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  27808. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27809. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27810. #if JUCE_PLUGINHOST_VST
  27811. /**
  27812. Implements a plugin format manager for VSTs.
  27813. */
  27814. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  27815. {
  27816. public:
  27817. VSTPluginFormat();
  27818. ~VSTPluginFormat();
  27819. const String getName() const { return "VST"; }
  27820. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27821. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27822. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27823. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27824. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27825. bool doesPluginStillExist (const PluginDescription& desc);
  27826. const FileSearchPath getDefaultLocationsToSearch();
  27827. juce_UseDebuggingNewOperator
  27828. private:
  27829. VSTPluginFormat (const VSTPluginFormat&);
  27830. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  27831. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  27832. };
  27833. #endif
  27834. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27835. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  27836. #endif
  27837. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27838. #endif
  27839. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27840. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  27841. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27842. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27843. /**
  27844. This maintains a list of known AudioPluginFormats.
  27845. @see AudioPluginFormat
  27846. */
  27847. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  27848. {
  27849. public:
  27850. AudioPluginFormatManager() throw();
  27851. /** Destructor. */
  27852. ~AudioPluginFormatManager() throw();
  27853. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  27854. /** Adds any formats that it knows about, e.g. VST.
  27855. */
  27856. void addDefaultFormats();
  27857. /** Returns the number of types of format that are available.
  27858. Use getFormat() to get one of them.
  27859. */
  27860. int getNumFormats() throw();
  27861. /** Returns one of the available formats.
  27862. @see getNumFormats
  27863. */
  27864. AudioPluginFormat* getFormat (const int index) throw();
  27865. /** Adds a format to the list.
  27866. The object passed in will be owned and deleted by the manager.
  27867. */
  27868. void addFormat (AudioPluginFormat* const format) throw();
  27869. /** Tries to load the type for this description, by trying all the formats
  27870. that this manager knows about.
  27871. The caller is responsible for deleting the object that is returned.
  27872. If it can't load the plugin, it returns 0 and leaves a message in the
  27873. errorMessage string.
  27874. */
  27875. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  27876. String& errorMessage) const;
  27877. /** Checks that the file or component for this plugin actually still exists.
  27878. (This won't try to load the plugin)
  27879. */
  27880. bool doesPluginStillExist (const PluginDescription& description) const;
  27881. juce_UseDebuggingNewOperator
  27882. private:
  27883. OwnedArray <AudioPluginFormat> formats;
  27884. AudioPluginFormatManager (const AudioPluginFormatManager&);
  27885. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  27886. };
  27887. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27888. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  27889. #endif
  27890. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27891. #endif
  27892. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27893. /********* Start of inlined file: juce_KnownPluginList.h *********/
  27894. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27895. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27896. /**
  27897. Manages a list of plugin types.
  27898. This can be easily edited, saved and loaded, and used to create instances of
  27899. the plugin types in it.
  27900. @see PluginListComponent
  27901. */
  27902. class JUCE_API KnownPluginList : public ChangeBroadcaster
  27903. {
  27904. public:
  27905. /** Creates an empty list.
  27906. */
  27907. KnownPluginList();
  27908. /** Destructor. */
  27909. ~KnownPluginList();
  27910. /** Clears the list. */
  27911. void clear();
  27912. /** Returns the number of types currently in the list.
  27913. @see getType
  27914. */
  27915. int getNumTypes() const throw() { return types.size(); }
  27916. /** Returns one of the types.
  27917. @see getNumTypes
  27918. */
  27919. PluginDescription* getType (const int index) const throw() { return types [index]; }
  27920. /** Looks for a type in the list which comes from this file.
  27921. */
  27922. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  27923. /** Looks for a type in the list which matches a plugin type ID.
  27924. The identifierString parameter must have been created by
  27925. PluginDescription::createIdentifierString().
  27926. */
  27927. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  27928. /** Adds a type manually from its description. */
  27929. bool addType (const PluginDescription& type);
  27930. /** Removes a type. */
  27931. void removeType (const int index) throw();
  27932. /** Looks for all types that can be loaded from a given file, and adds them
  27933. to the list.
  27934. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  27935. re-tested if it's not already in the list, or if the file's modification
  27936. time has changed since the list was created. If dontRescanIfAlreadyInList is
  27937. false, the file will always be reloaded and tested.
  27938. Returns true if any new types were added, and all the types found in this
  27939. file (even if it was already known and hasn't been re-scanned) get returned
  27940. in the array.
  27941. */
  27942. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  27943. const bool dontRescanIfAlreadyInList,
  27944. OwnedArray <PluginDescription>& typesFound,
  27945. AudioPluginFormat& formatToUse);
  27946. /** Returns true if the specified file is already known about and if it
  27947. hasn't been modified since our entry was created.
  27948. */
  27949. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  27950. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  27951. If any types are found in the files, their descriptions are returned in the array.
  27952. */
  27953. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  27954. OwnedArray <PluginDescription>& typesFound);
  27955. /** Sort methods used to change the order of the plugins in the list.
  27956. */
  27957. enum SortMethod
  27958. {
  27959. defaultOrder = 0,
  27960. sortAlphabetically,
  27961. sortByCategory,
  27962. sortByManufacturer,
  27963. sortByFileSystemLocation
  27964. };
  27965. /** Adds all the plugin types to a popup menu so that the user can select one.
  27966. Depending on the sort method, it may add sub-menus for categories,
  27967. manufacturers, etc.
  27968. Use getIndexChosenByMenu() to find out the type that was chosen.
  27969. */
  27970. void addToMenu (PopupMenu& menu,
  27971. const SortMethod sortMethod) const;
  27972. /** Converts a menu item index that has been chosen into its index in this list.
  27973. Returns -1 if it's not an ID that was used.
  27974. @see addToMenu
  27975. */
  27976. int getIndexChosenByMenu (const int menuResultCode) const;
  27977. /** Sorts the list. */
  27978. void sort (const SortMethod method);
  27979. /** Creates some XML that can be used to store the state of this list.
  27980. */
  27981. XmlElement* createXml() const;
  27982. /** Recreates the state of this list from its stored XML format.
  27983. */
  27984. void recreateFromXml (const XmlElement& xml);
  27985. juce_UseDebuggingNewOperator
  27986. private:
  27987. OwnedArray <PluginDescription> types;
  27988. KnownPluginList (const KnownPluginList&);
  27989. const KnownPluginList& operator= (const KnownPluginList&);
  27990. };
  27991. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27992. /********* End of inlined file: juce_KnownPluginList.h *********/
  27993. #endif
  27994. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27995. #endif
  27996. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27997. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  27998. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27999. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  28000. /**
  28001. Scans a directory for plugins, and adds them to a KnownPluginList.
  28002. To use one of these, create it and call scanNextFile() repeatedly, until
  28003. it returns false.
  28004. */
  28005. class JUCE_API PluginDirectoryScanner
  28006. {
  28007. public:
  28008. /**
  28009. Creates a scanner.
  28010. @param listToAddResultsTo this will get the new types added to it.
  28011. @param formatToLookFor this is the type of format that you want to look for
  28012. @param directoriesToSearch the path to search
  28013. @param searchRecursively true to search recursively
  28014. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  28015. be used as a file to store the names of any plugins
  28016. that crash during initialisation. If there are
  28017. any plugins listed in it, then these will always
  28018. be scanned after all other possible files have
  28019. been tried - in this way, even if there's a few
  28020. dodgy plugins in your path, then a couple of rescans
  28021. will still manage to find all the proper plugins.
  28022. It's probably best to choose a file in the user's
  28023. application data directory (alongside your app's
  28024. settings file) for this. The file format it uses
  28025. is just a list of filenames of the modules that
  28026. failed.
  28027. */
  28028. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  28029. AudioPluginFormat& formatToLookFor,
  28030. FileSearchPath directoriesToSearch,
  28031. const bool searchRecursively,
  28032. const File& deadMansPedalFile);
  28033. /** Destructor. */
  28034. ~PluginDirectoryScanner();
  28035. /** Tries the next likely-looking file.
  28036. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  28037. re-tested if it's not already in the list, or if the file's modification
  28038. time has changed since the list was created. If dontRescanIfAlreadyInList is
  28039. false, the file will always be reloaded and tested.
  28040. Returns false when there are no more files to try.
  28041. */
  28042. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  28043. /** Returns the description of the plugin that will be scanned during the next
  28044. call to scanNextFile().
  28045. This is handy if you want to show the user which file is currently getting
  28046. scanned.
  28047. */
  28048. const String getNextPluginFileThatWillBeScanned() const throw();
  28049. /** Returns the estimated progress, between 0 and 1.
  28050. */
  28051. float getProgress() const { return progress; }
  28052. /** This returns a list of all the filenames of things that looked like being
  28053. a plugin file, but which failed to open for some reason.
  28054. */
  28055. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  28056. juce_UseDebuggingNewOperator
  28057. private:
  28058. KnownPluginList& list;
  28059. AudioPluginFormat& format;
  28060. StringArray filesOrIdentifiersToScan;
  28061. File deadMansPedalFile;
  28062. StringArray failedFiles;
  28063. int nextIndex;
  28064. float progress;
  28065. const StringArray getDeadMansPedalFile() throw();
  28066. void setDeadMansPedalFile (const StringArray& newContents) throw();
  28067. PluginDirectoryScanner (const PluginDirectoryScanner&);
  28068. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  28069. };
  28070. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  28071. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  28072. #endif
  28073. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  28074. /********* Start of inlined file: juce_PluginListComponent.h *********/
  28075. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  28076. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  28077. /********* Start of inlined file: juce_ListBox.h *********/
  28078. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  28079. #define __JUCE_LISTBOX_JUCEHEADER__
  28080. class ListViewport;
  28081. /**
  28082. A subclass of this is used to drive a ListBox.
  28083. @see ListBox
  28084. */
  28085. class JUCE_API ListBoxModel
  28086. {
  28087. public:
  28088. /** Destructor. */
  28089. virtual ~ListBoxModel() {}
  28090. /** This has to return the number of items in the list.
  28091. @see ListBox::getNumRows()
  28092. */
  28093. virtual int getNumRows() = 0;
  28094. /** This method must be implemented to draw a row of the list.
  28095. */
  28096. virtual void paintListBoxItem (int rowNumber,
  28097. Graphics& g,
  28098. int width, int height,
  28099. bool rowIsSelected) = 0;
  28100. /** This is used to create or update a custom component to go in a row of the list.
  28101. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  28102. and handle mouse clicks with listBoxItemClicked().
  28103. This method will be called whenever a custom component might need to be updated - e.g.
  28104. when the table is changed, or TableListBox::updateContent() is called.
  28105. If you don't need a custom component for the specified row, then return 0.
  28106. If you do want a custom component, and the existingComponentToUpdate is null, then
  28107. this method must create a suitable new component and return it.
  28108. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  28109. by this method. In this case, the method must either update it to make sure it's correctly representing
  28110. the given row (which may be different from the one that the component was created for), or it can
  28111. delete this component and return a new one.
  28112. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  28113. */
  28114. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  28115. Component* existingComponentToUpdate);
  28116. /** This can be overridden to react to the user clicking on a row.
  28117. @see listBoxItemDoubleClicked
  28118. */
  28119. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  28120. /** This can be overridden to react to the user double-clicking on a row.
  28121. @see listBoxItemClicked
  28122. */
  28123. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  28124. /** This can be overridden to react to the user double-clicking on a part of the list where
  28125. there are no rows.
  28126. @see listBoxItemClicked
  28127. */
  28128. virtual void backgroundClicked();
  28129. /** Override this to be informed when rows are selected or deselected.
  28130. This will be called whenever a row is selected or deselected. If a range of
  28131. rows is selected all at once, this will just be called once for that event.
  28132. @param lastRowSelected the last row that the user selected. If no
  28133. rows are currently selected, this may be -1.
  28134. */
  28135. virtual void selectedRowsChanged (int lastRowSelected);
  28136. /** Override this to be informed when the delete key is pressed.
  28137. If no rows are selected when they press the key, this won't be called.
  28138. @param lastRowSelected the last row that had been selected when they pressed the
  28139. key - if there are multiple selections, this might not be
  28140. very useful
  28141. */
  28142. virtual void deleteKeyPressed (int lastRowSelected);
  28143. /** Override this to be informed when the return key is pressed.
  28144. If no rows are selected when they press the key, this won't be called.
  28145. @param lastRowSelected the last row that had been selected when they pressed the
  28146. key - if there are multiple selections, this might not be
  28147. very useful
  28148. */
  28149. virtual void returnKeyPressed (int lastRowSelected);
  28150. /** Override this to be informed when the list is scrolled.
  28151. This might be caused by the user moving the scrollbar, or by programmatic changes
  28152. to the list position.
  28153. */
  28154. virtual void listWasScrolled();
  28155. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  28156. If this returns a non-empty name then when the user drags a row, the listbox will
  28157. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  28158. a drag-and-drop operation, using this string as the source description, with the listbox
  28159. itself as the source component.
  28160. @see DragAndDropContainer::startDragging
  28161. */
  28162. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  28163. /** You can override this to provide tool tips for specific rows.
  28164. @see TooltipClient
  28165. */
  28166. virtual const String getTooltipForRow (int row);
  28167. };
  28168. /**
  28169. A list of items that can be scrolled vertically.
  28170. To create a list, you'll need to create a subclass of ListBoxModel. This can
  28171. either paint each row of the list and respond to events via callbacks, or for
  28172. more specialised tasks, it can supply a custom component to fill each row.
  28173. @see ComboBox, TableListBox
  28174. */
  28175. class JUCE_API ListBox : public Component,
  28176. public SettableTooltipClient
  28177. {
  28178. public:
  28179. /** Creates a ListBox.
  28180. The model pointer passed-in can be null, in which case you can set it later
  28181. with setModel().
  28182. */
  28183. ListBox (const String& componentName,
  28184. ListBoxModel* const model);
  28185. /** Destructor. */
  28186. ~ListBox();
  28187. /** Changes the current data model to display. */
  28188. void setModel (ListBoxModel* const newModel);
  28189. /** Returns the current list model. */
  28190. ListBoxModel* getModel() const throw() { return model; }
  28191. /** Causes the list to refresh its content.
  28192. Call this when the number of rows in the list changes, or if you want it
  28193. to call refreshComponentForRow() on all the row components.
  28194. Be careful not to call it from a different thread, though, as it's not
  28195. thread-safe.
  28196. */
  28197. void updateContent();
  28198. /** Turns on multiple-selection of rows.
  28199. By default this is disabled.
  28200. When your row component gets clicked you'll need to call the
  28201. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  28202. clicked and to get it to do the appropriate selection based on whether
  28203. the ctrl/shift keys are held down.
  28204. */
  28205. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  28206. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  28207. This function is here primarily for the ComboBox class to use, but might be
  28208. useful for some other purpose too.
  28209. */
  28210. void setMouseMoveSelectsRows (bool shouldSelect);
  28211. /** Selects a row.
  28212. If the row is already selected, this won't do anything.
  28213. @param rowNumber the row to select
  28214. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  28215. the selected row is off-screen, it'll scroll to make
  28216. sure that row is on-screen
  28217. @param deselectOthersFirst if true and there are multiple selections, these will
  28218. first be deselected before this item is selected
  28219. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  28220. deselectAllRows, selectRangeOfRows
  28221. */
  28222. void selectRow (const int rowNumber,
  28223. bool dontScrollToShowThisRow = false,
  28224. bool deselectOthersFirst = true);
  28225. /** Selects a set of rows.
  28226. This will add these rows to the current selection, so you might need to
  28227. clear the current selection first with deselectAllRows()
  28228. @param firstRow the first row to select (inclusive)
  28229. @param lastRow the last row to select (inclusive)
  28230. */
  28231. void selectRangeOfRows (int firstRow,
  28232. int lastRow);
  28233. /** Deselects a row.
  28234. If it's not currently selected, this will do nothing.
  28235. @see selectRow, deselectAllRows
  28236. */
  28237. void deselectRow (const int rowNumber);
  28238. /** Deselects any currently selected rows.
  28239. @see deselectRow
  28240. */
  28241. void deselectAllRows();
  28242. /** Selects or deselects a row.
  28243. If the row's currently selected, this deselects it, and vice-versa.
  28244. */
  28245. void flipRowSelection (const int rowNumber);
  28246. /** Returns a sparse set indicating the rows that are currently selected.
  28247. @see setSelectedRows
  28248. */
  28249. const SparseSet<int> getSelectedRows() const;
  28250. /** Sets the rows that should be selected, based on an explicit set of ranges.
  28251. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  28252. method will be called. If it's false, no notification will be sent to the model.
  28253. @see getSelectedRows
  28254. */
  28255. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  28256. const bool sendNotificationEventToModel = true);
  28257. /** Checks whether a row is selected.
  28258. */
  28259. bool isRowSelected (const int rowNumber) const;
  28260. /** Returns the number of rows that are currently selected.
  28261. @see getSelectedRow, isRowSelected, getLastRowSelected
  28262. */
  28263. int getNumSelectedRows() const;
  28264. /** Returns the row number of a selected row.
  28265. This will return the row number of the Nth selected row. The row numbers returned will
  28266. be sorted in order from low to high.
  28267. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  28268. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  28269. selected
  28270. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  28271. */
  28272. int getSelectedRow (const int index = 0) const;
  28273. /** Returns the last row that the user selected.
  28274. This isn't the same as the highest row number that is currently selected - if the user
  28275. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  28276. If nothing is selected, it will return -1.
  28277. */
  28278. int getLastRowSelected() const;
  28279. /** Multiply-selects rows based on the modifier keys.
  28280. If no modifier keys are down, this will select the given row and
  28281. deselect any others.
  28282. If the ctrl (or command on the Mac) key is down, it'll flip the
  28283. state of the selected row.
  28284. If the shift key is down, it'll select up to the given row from the
  28285. last row selected.
  28286. @see selectRow
  28287. */
  28288. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  28289. const ModifierKeys& modifiers);
  28290. /** Scrolls the list to a particular position.
  28291. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  28292. 1.0 scrolls to the bottom.
  28293. If the total number of rows all fit onto the screen at once, then this
  28294. method won't do anything.
  28295. @see getVerticalPosition
  28296. */
  28297. void setVerticalPosition (const double newProportion);
  28298. /** Returns the current vertical position as a proportion of the total.
  28299. This can be used in conjunction with setVerticalPosition() to save and restore
  28300. the list's position. It returns a value in the range 0 to 1.
  28301. @see setVerticalPosition
  28302. */
  28303. double getVerticalPosition() const;
  28304. /** Scrolls if necessary to make sure that a particular row is visible.
  28305. */
  28306. void scrollToEnsureRowIsOnscreen (const int row);
  28307. /** Returns a pointer to the scrollbar.
  28308. (Unlikely to be useful for most people).
  28309. */
  28310. ScrollBar* getVerticalScrollBar() const throw();
  28311. /** Returns a pointer to the scrollbar.
  28312. (Unlikely to be useful for most people).
  28313. */
  28314. ScrollBar* getHorizontalScrollBar() const throw();
  28315. /** Finds the row index that contains a given x,y position.
  28316. The position is relative to the ListBox's top-left.
  28317. If no row exists at this position, the method will return -1.
  28318. @see getComponentForRowNumber
  28319. */
  28320. int getRowContainingPosition (const int x, const int y) const throw();
  28321. /** Finds a row index that would be the most suitable place to insert a new
  28322. item for a given position.
  28323. This is useful when the user is e.g. dragging and dropping onto the listbox,
  28324. because it lets you easily choose the best position to insert the item that
  28325. they drop, based on where they drop it.
  28326. If the position is out of range, this will return -1. If the position is
  28327. beyond the end of the list, it will return getNumRows() to indicate the end
  28328. of the list.
  28329. @see getComponentForRowNumber
  28330. */
  28331. int getInsertionIndexForPosition (const int x, const int y) const throw();
  28332. /** Returns the position of one of the rows, relative to the top-left of
  28333. the listbox.
  28334. This may be off-screen, and the range of the row number that is passed-in is
  28335. not checked to see if it's a valid row.
  28336. */
  28337. const Rectangle getRowPosition (const int rowNumber,
  28338. const bool relativeToComponentTopLeft) const throw();
  28339. /** Finds the row component for a given row in the list.
  28340. The component returned will have been created using createRowComponent().
  28341. If the component for this row is off-screen or if the row is out-of-range,
  28342. this will return 0.
  28343. @see getRowContainingPosition
  28344. */
  28345. Component* getComponentForRowNumber (const int rowNumber) const throw();
  28346. /** Returns the row number that the given component represents.
  28347. If the component isn't one of the list's rows, this will return -1.
  28348. */
  28349. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  28350. /** Returns the width of a row (which may be less than the width of this component
  28351. if there's a scrollbar).
  28352. */
  28353. int getVisibleRowWidth() const throw();
  28354. /** Sets the height of each row in the list.
  28355. The default height is 22 pixels.
  28356. @see getRowHeight
  28357. */
  28358. void setRowHeight (const int newHeight);
  28359. /** Returns the height of a row in the list.
  28360. @see setRowHeight
  28361. */
  28362. int getRowHeight() const throw() { return rowHeight; }
  28363. /** Returns the number of rows actually visible.
  28364. This is the number of whole rows which will fit on-screen, so the value might
  28365. be more than the actual number of rows in the list.
  28366. */
  28367. int getNumRowsOnScreen() const throw();
  28368. /** A set of colour IDs to use to change the colour of various aspects of the label.
  28369. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  28370. methods.
  28371. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  28372. */
  28373. enum ColourIds
  28374. {
  28375. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  28376. Make this transparent if you don't want the background to be filled. */
  28377. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  28378. Make this transparent to not have an outline. */
  28379. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  28380. };
  28381. /** Sets the thickness of a border that will be drawn around the box.
  28382. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  28383. @see outlineColourId
  28384. */
  28385. void setOutlineThickness (const int outlineThickness);
  28386. /** Returns the thickness of outline that will be drawn around the listbox.
  28387. @see setOutlineColour
  28388. */
  28389. int getOutlineThickness() const throw() { return outlineThickness; }
  28390. /** Sets a component that the list should use as a header.
  28391. This will position the given component at the top of the list, maintaining the
  28392. height of the component passed-in, but rescaling it horizontally to match the
  28393. width of the items in the listbox.
  28394. The component will be deleted when setHeaderComponent() is called with a
  28395. different component, or when the listbox is deleted.
  28396. */
  28397. void setHeaderComponent (Component* const newHeaderComponent);
  28398. /** Changes the width of the rows in the list.
  28399. This can be used to make the list's row components wider than the list itself - the
  28400. width of the rows will be either the width of the list or this value, whichever is
  28401. greater, and if the rows become wider than the list, a horizontal scrollbar will
  28402. appear.
  28403. The default value for this is 0, which means that the rows will always
  28404. be the same width as the list.
  28405. */
  28406. void setMinimumContentWidth (const int newMinimumWidth);
  28407. /** Returns the space currently available for the row items, taking into account
  28408. borders, scrollbars, etc.
  28409. */
  28410. int getVisibleContentWidth() const throw();
  28411. /** Repaints one of the rows.
  28412. This is a lightweight alternative to calling updateContent, and just causes a
  28413. repaint of the row's area.
  28414. */
  28415. void repaintRow (const int rowNumber) throw();
  28416. /** This fairly obscure method creates an image that just shows the currently
  28417. selected row components.
  28418. It's a handy method for doing drag-and-drop, as it can be passed to the
  28419. DragAndDropContainer for use as the drag image.
  28420. Note that it will make the row components temporarily invisible, so if you're
  28421. using custom components this could affect them if they're sensitive to that
  28422. sort of thing.
  28423. @see Component::createComponentSnapshot
  28424. */
  28425. Image* createSnapshotOfSelectedRows (int& x, int& y);
  28426. /** Returns the viewport that this ListBox uses.
  28427. You may need to use this to change parameters such as whether scrollbars
  28428. are shown, etc.
  28429. */
  28430. Viewport* getViewport() const throw();
  28431. /** @internal */
  28432. bool keyPressed (const KeyPress& key);
  28433. /** @internal */
  28434. bool keyStateChanged (const bool isKeyDown);
  28435. /** @internal */
  28436. void paint (Graphics& g);
  28437. /** @internal */
  28438. void paintOverChildren (Graphics& g);
  28439. /** @internal */
  28440. void resized();
  28441. /** @internal */
  28442. void visibilityChanged();
  28443. /** @internal */
  28444. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  28445. /** @internal */
  28446. void mouseMove (const MouseEvent&);
  28447. /** @internal */
  28448. void mouseExit (const MouseEvent&);
  28449. /** @internal */
  28450. void mouseUp (const MouseEvent&);
  28451. /** @internal */
  28452. void colourChanged();
  28453. /** @internal */
  28454. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  28455. juce_UseDebuggingNewOperator
  28456. private:
  28457. friend class ListViewport;
  28458. friend class TableListBox;
  28459. ListBoxModel* model;
  28460. ListViewport* viewport;
  28461. Component* headerComponent;
  28462. int totalItems, rowHeight, minimumRowWidth;
  28463. int outlineThickness;
  28464. int lastMouseX, lastMouseY, lastRowSelected;
  28465. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  28466. SparseSet <int> selected;
  28467. void selectRowInternal (const int rowNumber,
  28468. bool dontScrollToShowThisRow,
  28469. bool deselectOthersFirst,
  28470. bool isMouseClick);
  28471. ListBox (const ListBox&);
  28472. const ListBox& operator= (const ListBox&);
  28473. };
  28474. #endif // __JUCE_LISTBOX_JUCEHEADER__
  28475. /********* End of inlined file: juce_ListBox.h *********/
  28476. /********* Start of inlined file: juce_TextButton.h *********/
  28477. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  28478. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  28479. /**
  28480. A button that uses the standard lozenge-shaped background with a line of
  28481. text on it.
  28482. @see Button, DrawableButton
  28483. */
  28484. class JUCE_API TextButton : public Button
  28485. {
  28486. public:
  28487. /** Creates a TextButton.
  28488. @param buttonName the text to put in the button (the component's name is also
  28489. initially set to this string, but these can be changed later
  28490. using the setName() and setButtonText() methods)
  28491. @param toolTip an optional string to use as a toolip
  28492. @see Button
  28493. */
  28494. TextButton (const String& buttonName,
  28495. const String& toolTip = String::empty);
  28496. /** Destructor. */
  28497. ~TextButton();
  28498. /** A set of colour IDs to use to change the colour of various aspects of the button.
  28499. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  28500. methods.
  28501. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  28502. */
  28503. enum ColourIds
  28504. {
  28505. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  28506. 'off'). The look-and-feel class might re-interpret this to add
  28507. effects, etc. */
  28508. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  28509. 'on'). The look-and-feel class might re-interpret this to add
  28510. effects, etc. */
  28511. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  28512. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  28513. };
  28514. /** Resizes the button to fit neatly around its current text.
  28515. If newHeight is >= 0, the button's height will be changed to this
  28516. value. If it's less than zero, its height will be unaffected.
  28517. */
  28518. void changeWidthToFitText (const int newHeight = -1);
  28519. /** This can be overridden to use different fonts than the default one.
  28520. Note that you'll need to set the font's size appropriately, too.
  28521. */
  28522. virtual const Font getFont();
  28523. juce_UseDebuggingNewOperator
  28524. protected:
  28525. /** @internal */
  28526. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  28527. /** @internal */
  28528. void colourChanged();
  28529. private:
  28530. TextButton (const TextButton&);
  28531. const TextButton& operator= (const TextButton&);
  28532. };
  28533. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  28534. /********* End of inlined file: juce_TextButton.h *********/
  28535. /**
  28536. A component displaying a list of plugins, with options to scan for them,
  28537. add, remove and sort them.
  28538. */
  28539. class JUCE_API PluginListComponent : public Component,
  28540. public ListBoxModel,
  28541. public ChangeListener,
  28542. public ButtonListener,
  28543. public Timer
  28544. {
  28545. public:
  28546. /**
  28547. Creates the list component.
  28548. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  28549. The properties file, if supplied, is used to store the user's last search paths.
  28550. */
  28551. PluginListComponent (KnownPluginList& listToRepresent,
  28552. const File& deadMansPedalFile,
  28553. PropertiesFile* const propertiesToUse);
  28554. /** Destructor. */
  28555. ~PluginListComponent();
  28556. /** @internal */
  28557. void resized();
  28558. /** @internal */
  28559. bool isInterestedInFileDrag (const StringArray& files);
  28560. /** @internal */
  28561. void filesDropped (const StringArray& files, int, int);
  28562. /** @internal */
  28563. int getNumRows();
  28564. /** @internal */
  28565. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  28566. /** @internal */
  28567. void deleteKeyPressed (int lastRowSelected);
  28568. /** @internal */
  28569. void buttonClicked (Button* b);
  28570. /** @internal */
  28571. void changeListenerCallback (void*);
  28572. /** @internal */
  28573. void timerCallback();
  28574. juce_UseDebuggingNewOperator
  28575. private:
  28576. KnownPluginList& list;
  28577. File deadMansPedalFile;
  28578. ListBox* listBox;
  28579. TextButton* optionsButton;
  28580. PropertiesFile* propertiesToUse;
  28581. int typeToScan;
  28582. void scanFor (AudioPluginFormat* format);
  28583. PluginListComponent (const PluginListComponent&);
  28584. const PluginListComponent& operator= (const PluginListComponent&);
  28585. };
  28586. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  28587. /********* End of inlined file: juce_PluginListComponent.h *********/
  28588. #endif
  28589. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28590. #endif
  28591. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28592. #endif
  28593. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28594. #endif
  28595. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28596. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  28597. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28598. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28599. /**
  28600. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  28601. Use one of these objects if you want to wire-up a set of AudioProcessors
  28602. and play back the result.
  28603. Processors can be added to the graph as "nodes" using addNode(), and once
  28604. added, you can connect any of their input or output channels to other
  28605. nodes using addConnection().
  28606. To play back a graph through an audio device, you might want to use an
  28607. AudioProcessorPlayer object.
  28608. */
  28609. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  28610. public AsyncUpdater
  28611. {
  28612. public:
  28613. /** Creates an empty graph.
  28614. */
  28615. AudioProcessorGraph();
  28616. /** Destructor.
  28617. Any processor objects that have been added to the graph will also be deleted.
  28618. */
  28619. ~AudioProcessorGraph();
  28620. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  28621. To create a node, call AudioProcessorGraph::addNode().
  28622. */
  28623. class JUCE_API Node : public ReferenceCountedObject
  28624. {
  28625. public:
  28626. /** Destructor.
  28627. */
  28628. ~Node();
  28629. /** The ID number assigned to this node.
  28630. This is assigned by the graph that owns it, and can't be changed.
  28631. */
  28632. const uint32 id;
  28633. /** The actual processor object that this node represents.
  28634. */
  28635. AudioProcessor* const processor;
  28636. /** A set of user-definable properties that are associated with this node.
  28637. This can be used to attach values to the node for whatever purpose seems
  28638. useful. For example, you might store an x and y position if your application
  28639. is displaying the nodes on-screen.
  28640. */
  28641. PropertySet properties;
  28642. /** A convenient typedef for referring to a pointer to a node object.
  28643. */
  28644. typedef ReferenceCountedObjectPtr <Node> Ptr;
  28645. juce_UseDebuggingNewOperator
  28646. private:
  28647. friend class AudioProcessorGraph;
  28648. bool isPrepared;
  28649. Node (const uint32 id, AudioProcessor* const processor);
  28650. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  28651. void unprepare();
  28652. Node (const Node&);
  28653. const Node& operator= (const Node&);
  28654. };
  28655. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  28656. To create a connection, use AudioProcessorGraph::addConnection().
  28657. */
  28658. struct JUCE_API Connection
  28659. {
  28660. public:
  28661. /** The ID number of the node which is the input source for this connection.
  28662. @see AudioProcessorGraph::getNodeForId
  28663. */
  28664. uint32 sourceNodeId;
  28665. /** The index of the output channel of the source node from which this
  28666. connection takes its data.
  28667. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  28668. it is referring to the source node's midi output. Otherwise, it is the zero-based
  28669. index of an audio output channel in the source node.
  28670. */
  28671. int sourceChannelIndex;
  28672. /** The ID number of the node which is the destination for this connection.
  28673. @see AudioProcessorGraph::getNodeForId
  28674. */
  28675. uint32 destNodeId;
  28676. /** The index of the input channel of the destination node to which this
  28677. connection delivers its data.
  28678. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  28679. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  28680. index of an audio input channel in the destination node.
  28681. */
  28682. int destChannelIndex;
  28683. juce_UseDebuggingNewOperator
  28684. private:
  28685. };
  28686. /** Deletes all nodes and connections from this graph.
  28687. Any processor objects in the graph will be deleted.
  28688. */
  28689. void clear();
  28690. /** Returns the number of nodes in the graph. */
  28691. int getNumNodes() const { return nodes.size(); }
  28692. /** Returns a pointer to one of the nodes in the graph.
  28693. This will return 0 if the index is out of range.
  28694. @see getNodeForId
  28695. */
  28696. Node* getNode (const int index) const { return nodes [index]; }
  28697. /** Searches the graph for a node with the given ID number and returns it.
  28698. If no such node was found, this returns 0.
  28699. @see getNode
  28700. */
  28701. Node* getNodeForId (const uint32 nodeId) const;
  28702. /** Adds a node to the graph.
  28703. This creates a new node in the graph, for the specified processor. Once you have
  28704. added a processor to the graph, the graph owns it and will delete it later when
  28705. it is no longer needed.
  28706. The optional nodeId parameter lets you specify an ID to use for the node, but
  28707. if the value is already in use, this new node will overwrite the old one.
  28708. If this succeeds, it returns a pointer to the newly-created node.
  28709. */
  28710. Node* addNode (AudioProcessor* const newProcessor,
  28711. uint32 nodeId = 0);
  28712. /** Deletes a node within the graph which has the specified ID.
  28713. This will also delete any connections that are attached to this node.
  28714. */
  28715. bool removeNode (const uint32 nodeId);
  28716. /** Returns the number of connections in the graph. */
  28717. int getNumConnections() const { return connections.size(); }
  28718. /** Returns a pointer to one of the connections in the graph. */
  28719. const Connection* getConnection (const int index) const { return connections [index]; }
  28720. /** Searches for a connection between some specified channels.
  28721. If no such connection is found, this returns 0.
  28722. */
  28723. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  28724. const int sourceChannelIndex,
  28725. const uint32 destNodeId,
  28726. const int destChannelIndex) const;
  28727. /** Returns true if there is a connection between any of the channels of
  28728. two specified nodes.
  28729. */
  28730. bool isConnected (const uint32 possibleSourceNodeId,
  28731. const uint32 possibleDestNodeId) const;
  28732. /** Returns true if it would be legal to connect the specified points.
  28733. */
  28734. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  28735. const uint32 destNodeId, const int destChannelIndex) const;
  28736. /** Attempts to connect two specified channels of two nodes.
  28737. If this isn't allowed (e.g. because you're trying to connect a midi channel
  28738. to an audio one or other such nonsense), then it'll return false.
  28739. */
  28740. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28741. const uint32 destNodeId, const int destChannelIndex);
  28742. /** Deletes the connection with the specified index.
  28743. Returns true if a connection was actually deleted.
  28744. */
  28745. void removeConnection (const int index);
  28746. /** Deletes any connection between two specified points.
  28747. Returns true if a connection was actually deleted.
  28748. */
  28749. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28750. const uint32 destNodeId, const int destChannelIndex);
  28751. /** Removes all connections from the specified node.
  28752. */
  28753. bool disconnectNode (const uint32 nodeId);
  28754. /** Performs a sanity checks of all the connections.
  28755. This might be useful if some of the processors are doing things like changing
  28756. their channel counts, which could render some connections obsolete.
  28757. */
  28758. bool removeIllegalConnections();
  28759. /** A special number that represents the midi channel of a node.
  28760. This is used as a channel index value if you want to refer to the midi input
  28761. or output instead of an audio channel.
  28762. */
  28763. static const int midiChannelIndex;
  28764. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  28765. in order to use the audio that comes into and out of the graph itself.
  28766. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  28767. node in the graph which delivers the audio that is coming into the parent
  28768. graph. This allows you to stream the data to other nodes and process the
  28769. incoming audio.
  28770. Likewise, one of these in "output" mode can be sent data which it will add to
  28771. the sum of data being sent to the graph's output.
  28772. @see AudioProcessorGraph
  28773. */
  28774. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  28775. {
  28776. public:
  28777. /** Specifies the mode in which this processor will operate.
  28778. */
  28779. enum IODeviceType
  28780. {
  28781. audioInputNode, /**< In this mode, the processor has output channels
  28782. representing all the audio input channels that are
  28783. coming into its parent audio graph. */
  28784. audioOutputNode, /**< In this mode, the processor has input channels
  28785. representing all the audio output channels that are
  28786. going out of its parent audio graph. */
  28787. midiInputNode, /**< In this mode, the processor has a midi output which
  28788. delivers the same midi data that is arriving at its
  28789. parent graph. */
  28790. midiOutputNode /**< In this mode, the processor has a midi input and
  28791. any data sent to it will be passed out of the parent
  28792. graph. */
  28793. };
  28794. /** Returns the mode of this processor. */
  28795. IODeviceType getType() const { return type; }
  28796. /** Returns the parent graph to which this processor belongs, or 0 if it
  28797. hasn't yet been added to one. */
  28798. AudioProcessorGraph* getParentGraph() const { return graph; }
  28799. /** True if this is an audio or midi input. */
  28800. bool isInput() const;
  28801. /** True if this is an audio or midi output. */
  28802. bool isOutput() const;
  28803. AudioGraphIOProcessor (const IODeviceType type);
  28804. ~AudioGraphIOProcessor();
  28805. const String getName() const;
  28806. void fillInPluginDescription (PluginDescription& d) const;
  28807. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  28808. void releaseResources();
  28809. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  28810. const String getInputChannelName (const int channelIndex) const;
  28811. const String getOutputChannelName (const int channelIndex) const;
  28812. bool isInputChannelStereoPair (int index) const;
  28813. bool isOutputChannelStereoPair (int index) const;
  28814. bool acceptsMidi() const;
  28815. bool producesMidi() const;
  28816. AudioProcessorEditor* createEditor();
  28817. int getNumParameters();
  28818. const String getParameterName (int);
  28819. float getParameter (int);
  28820. const String getParameterText (int);
  28821. void setParameter (int, float);
  28822. int getNumPrograms();
  28823. int getCurrentProgram();
  28824. void setCurrentProgram (int);
  28825. const String getProgramName (int);
  28826. void changeProgramName (int, const String&);
  28827. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28828. void setStateInformation (const void* data, int sizeInBytes);
  28829. /** @internal */
  28830. void setParentGraph (AudioProcessorGraph* const graph);
  28831. juce_UseDebuggingNewOperator
  28832. private:
  28833. const IODeviceType type;
  28834. AudioProcessorGraph* graph;
  28835. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  28836. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  28837. };
  28838. // AudioProcessor methods:
  28839. const String getName() const;
  28840. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  28841. void releaseResources();
  28842. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  28843. const String getInputChannelName (const int channelIndex) const;
  28844. const String getOutputChannelName (const int channelIndex) const;
  28845. bool isInputChannelStereoPair (int index) const;
  28846. bool isOutputChannelStereoPair (int index) const;
  28847. bool acceptsMidi() const;
  28848. bool producesMidi() const;
  28849. AudioProcessorEditor* createEditor() { return 0; }
  28850. int getNumParameters() { return 0; }
  28851. const String getParameterName (int) { return String::empty; }
  28852. float getParameter (int) { return 0; }
  28853. const String getParameterText (int) { return String::empty; }
  28854. void setParameter (int, float) { }
  28855. int getNumPrograms() { return 0; }
  28856. int getCurrentProgram() { return 0; }
  28857. void setCurrentProgram (int) { }
  28858. const String getProgramName (int) { return String::empty; }
  28859. void changeProgramName (int, const String&) { }
  28860. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28861. void setStateInformation (const void* data, int sizeInBytes);
  28862. /** @internal */
  28863. void handleAsyncUpdate();
  28864. juce_UseDebuggingNewOperator
  28865. private:
  28866. ReferenceCountedArray <Node> nodes;
  28867. OwnedArray <Connection> connections;
  28868. int lastNodeId;
  28869. AudioSampleBuffer renderingBuffers;
  28870. OwnedArray <MidiBuffer> midiBuffers;
  28871. CriticalSection renderLock;
  28872. VoidArray renderingOps;
  28873. friend class AudioGraphIOProcessor;
  28874. AudioSampleBuffer* currentAudioInputBuffer;
  28875. AudioSampleBuffer currentAudioOutputBuffer;
  28876. MidiBuffer* currentMidiInputBuffer;
  28877. MidiBuffer currentMidiOutputBuffer;
  28878. void clearRenderingSequence();
  28879. void buildRenderingSequence();
  28880. bool isAnInputTo (const uint32 possibleInputId,
  28881. const uint32 possibleDestinationId,
  28882. const int recursionCheck) const;
  28883. AudioProcessorGraph (const AudioProcessorGraph&);
  28884. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  28885. };
  28886. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28887. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  28888. #endif
  28889. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28890. #endif
  28891. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28892. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  28893. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28894. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28895. /**
  28896. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  28897. To use one of these, just make it the callback used by your AudioIODevice, and
  28898. give it a processor to use by calling setProcessor().
  28899. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  28900. input to send both streams through the processor.
  28901. @see AudioProcessor, AudioProcessorGraph
  28902. */
  28903. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  28904. public MidiInputCallback
  28905. {
  28906. public:
  28907. /**
  28908. */
  28909. AudioProcessorPlayer();
  28910. /** Destructor. */
  28911. virtual ~AudioProcessorPlayer();
  28912. /** Sets the processor that should be played.
  28913. The processor that is passed in will not be deleted or owned by this object.
  28914. To stop anything playing, pass in 0 to this method.
  28915. */
  28916. void setProcessor (AudioProcessor* const processorToPlay);
  28917. /** Returns the current audio processor that is being played.
  28918. */
  28919. AudioProcessor* getCurrentProcessor() const { return processor; }
  28920. /** Returns a midi message collector that you can pass midi messages to if you
  28921. want them to be injected into the midi stream that is being sent to the
  28922. processor.
  28923. */
  28924. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  28925. /** @internal */
  28926. void audioDeviceIOCallback (const float** inputChannelData,
  28927. int totalNumInputChannels,
  28928. float** outputChannelData,
  28929. int totalNumOutputChannels,
  28930. int numSamples);
  28931. /** @internal */
  28932. void audioDeviceAboutToStart (AudioIODevice* device);
  28933. /** @internal */
  28934. void audioDeviceStopped();
  28935. /** @internal */
  28936. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28937. juce_UseDebuggingNewOperator
  28938. private:
  28939. AudioProcessor* processor;
  28940. CriticalSection lock;
  28941. double sampleRate;
  28942. int blockSize;
  28943. bool isPrepared;
  28944. int numInputChans, numOutputChans;
  28945. float* channels [128];
  28946. AudioSampleBuffer tempBuffer;
  28947. MidiBuffer incomingMidi;
  28948. MidiMessageCollector messageCollector;
  28949. AudioProcessorPlayer (const AudioProcessorPlayer&);
  28950. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  28951. };
  28952. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28953. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  28954. #endif
  28955. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28956. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  28957. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28958. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28959. /********* Start of inlined file: juce_PropertyPanel.h *********/
  28960. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  28961. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  28962. /********* Start of inlined file: juce_PropertyComponent.h *********/
  28963. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  28964. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  28965. class EditableProperty;
  28966. /**
  28967. A base class for a component that goes in a PropertyPanel and displays one of
  28968. an item's properties.
  28969. Subclasses of this are used to display a property in various forms, e.g. a
  28970. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  28971. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  28972. A subclass must implement the refresh() method which will be called to tell the
  28973. component to update itself, and is also responsible for calling this it when the
  28974. item that it refers to is changed.
  28975. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  28976. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  28977. */
  28978. class JUCE_API PropertyComponent : public Component,
  28979. public SettableTooltipClient
  28980. {
  28981. public:
  28982. /** Creates a PropertyComponent.
  28983. @param propertyName the name is stored as this component's name, and is
  28984. used as the name displayed next to this component in
  28985. a property panel
  28986. @param preferredHeight the height that the component should be given - some
  28987. items may need to be larger than a normal row height.
  28988. This value can also be set if a subclass changes the
  28989. preferredHeight member variable.
  28990. */
  28991. PropertyComponent (const String& propertyName,
  28992. const int preferredHeight = 25);
  28993. /** Destructor. */
  28994. ~PropertyComponent();
  28995. /** Returns this item's preferred height.
  28996. This value is specified either in the constructor or by a subclass changing the
  28997. preferredHeight member variable.
  28998. */
  28999. int getPreferredHeight() const throw() { return preferredHeight; }
  29000. /** Updates the property component if the item it refers to has changed.
  29001. A subclass must implement this method, and other objects may call it to
  29002. force it to refresh itself.
  29003. The subclass should be economical in the amount of work is done, so for
  29004. example it should check whether it really needs to do a repaint rather than
  29005. just doing one every time this method is called, as it may be called when
  29006. the value being displayed hasn't actually changed.
  29007. */
  29008. virtual void refresh() = 0;
  29009. /** The default paint method fills the background and draws a label for the
  29010. item's name.
  29011. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  29012. */
  29013. void paint (Graphics& g);
  29014. /** The default resize method positions any child component to the right of this
  29015. one, based on the look and feel's default label size.
  29016. */
  29017. void resized();
  29018. /** By default, this just repaints the component. */
  29019. void enablementChanged();
  29020. juce_UseDebuggingNewOperator
  29021. protected:
  29022. /** Used by the PropertyPanel to determine how high this component needs to be.
  29023. A subclass can update this value in its constructor but shouldn't alter it later
  29024. as changes won't necessarily be picked up.
  29025. */
  29026. int preferredHeight;
  29027. };
  29028. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  29029. /********* End of inlined file: juce_PropertyComponent.h *********/
  29030. /**
  29031. A panel that holds a list of PropertyComponent objects.
  29032. This panel displays a list of PropertyComponents, and allows them to be organised
  29033. into collapsible sections.
  29034. To use, simply create one of these and add your properties to it with addProperties()
  29035. or addSection().
  29036. @see PropertyComponent
  29037. */
  29038. class JUCE_API PropertyPanel : public Component
  29039. {
  29040. public:
  29041. /** Creates an empty property panel. */
  29042. PropertyPanel();
  29043. /** Destructor. */
  29044. ~PropertyPanel();
  29045. /** Deletes all property components from the panel.
  29046. */
  29047. void clear();
  29048. /** Adds a set of properties to the panel.
  29049. The components in the list will be owned by this object and will be automatically
  29050. deleted later on when no longer needed.
  29051. These properties are added without them being inside a named section. If you
  29052. want them to be kept together in a collapsible section, use addSection() instead.
  29053. */
  29054. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  29055. /** Adds a set of properties to the panel.
  29056. These properties are added at the bottom of the list, under a section heading with
  29057. a plus/minus button that allows it to be opened and closed.
  29058. The components in the list will be owned by this object and will be automatically
  29059. deleted later on when no longer needed.
  29060. To add properies without them being in a section, use addProperties().
  29061. */
  29062. void addSection (const String& sectionTitle,
  29063. const Array <PropertyComponent*>& newPropertyComponents,
  29064. const bool shouldSectionInitiallyBeOpen = true);
  29065. /** Calls the refresh() method of all PropertyComponents in the panel */
  29066. void refreshAll() const;
  29067. /** Returns a list of all the names of sections in the panel.
  29068. These are the sections that have been added with addSection().
  29069. */
  29070. const StringArray getSectionNames() const;
  29071. /** Returns true if the section at this index is currently open.
  29072. The index is from 0 up to the number of items returned by getSectionNames().
  29073. */
  29074. bool isSectionOpen (const int sectionIndex) const;
  29075. /** Opens or closes one of the sections.
  29076. The index is from 0 up to the number of items returned by getSectionNames().
  29077. */
  29078. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  29079. /** Enables or disables one of the sections.
  29080. The index is from 0 up to the number of items returned by getSectionNames().
  29081. */
  29082. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  29083. /** Saves the current state of open/closed sections so it can be restored later.
  29084. The caller is responsible for deleting the object that is returned.
  29085. To restore this state, use restoreOpennessState().
  29086. @see restoreOpennessState
  29087. */
  29088. XmlElement* getOpennessState() const;
  29089. /** Restores a previously saved arrangement of open/closed sections.
  29090. This will try to restore a snapshot of the panel's state that was created by
  29091. the getOpennessState() method. If any of the sections named in the original
  29092. XML aren't present, they will be ignored.
  29093. @see getOpennessState
  29094. */
  29095. void restoreOpennessState (const XmlElement& newState);
  29096. /** Sets a message to be displayed when there are no properties in the panel.
  29097. The default message is "nothing selected".
  29098. */
  29099. void setMessageWhenEmpty (const String& newMessage);
  29100. /** Returns the message that is displayed when there are no properties.
  29101. @see setMessageWhenEmpty
  29102. */
  29103. const String& getMessageWhenEmpty() const;
  29104. /** @internal */
  29105. void paint (Graphics& g);
  29106. /** @internal */
  29107. void resized();
  29108. juce_UseDebuggingNewOperator
  29109. private:
  29110. Viewport* viewport;
  29111. Component* propertyHolderComponent;
  29112. String messageWhenEmpty;
  29113. void updatePropHolderLayout() const;
  29114. void updatePropHolderLayout (const int width) const;
  29115. };
  29116. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  29117. /********* End of inlined file: juce_PropertyPanel.h *********/
  29118. /**
  29119. A type of UI component that displays the parameters of an AudioProcessor as
  29120. a simple list of sliders.
  29121. This can be used for showing an editor for a processor that doesn't supply
  29122. its own custom editor.
  29123. @see AudioProcessor
  29124. */
  29125. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  29126. {
  29127. public:
  29128. GenericAudioProcessorEditor (AudioProcessor* const owner);
  29129. ~GenericAudioProcessorEditor();
  29130. void paint (Graphics& g);
  29131. void resized();
  29132. juce_UseDebuggingNewOperator
  29133. private:
  29134. PropertyPanel* panel;
  29135. };
  29136. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  29137. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  29138. #endif
  29139. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  29140. /********* Start of inlined file: juce_Sampler.h *********/
  29141. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  29142. #define __JUCE_SAMPLER_JUCEHEADER__
  29143. /********* Start of inlined file: juce_Synthesiser.h *********/
  29144. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  29145. #define __JUCE_SYNTHESISER_JUCEHEADER__
  29146. /**
  29147. Describes one of the sounds that a Synthesiser can play.
  29148. A synthesiser can contain one or more sounds, and a sound can choose which
  29149. midi notes and channels can trigger it.
  29150. The SynthesiserSound is a passive class that just describes what the sound is -
  29151. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  29152. more than one SynthesiserVoice to play the same sound at the same time.
  29153. @see Synthesiser, SynthesiserVoice
  29154. */
  29155. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  29156. {
  29157. protected:
  29158. SynthesiserSound();
  29159. public:
  29160. /** Destructor. */
  29161. virtual ~SynthesiserSound();
  29162. /** Returns true if this sound should be played when a given midi note is pressed.
  29163. The Synthesiser will use this information when deciding which sounds to trigger
  29164. for a given note.
  29165. */
  29166. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  29167. /** Returns true if the sound should be triggered by midi events on a given channel.
  29168. The Synthesiser will use this information when deciding which sounds to trigger
  29169. for a given note.
  29170. */
  29171. virtual bool appliesToChannel (const int midiChannel) = 0;
  29172. /**
  29173. */
  29174. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  29175. juce_UseDebuggingNewOperator
  29176. };
  29177. /**
  29178. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  29179. A voice plays a single sound at a time, and a synthesiser holds an array of
  29180. voices so that it can play polyphonically.
  29181. @see Synthesiser, SynthesiserSound
  29182. */
  29183. class JUCE_API SynthesiserVoice
  29184. {
  29185. public:
  29186. /** Creates a voice. */
  29187. SynthesiserVoice();
  29188. /** Destructor. */
  29189. virtual ~SynthesiserVoice();
  29190. /** Returns the midi note that this voice is currently playing.
  29191. Returns a value less than 0 if no note is playing.
  29192. */
  29193. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  29194. /** Returns the sound that this voice is currently playing.
  29195. Returns 0 if it's not playing.
  29196. */
  29197. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  29198. /** Must return true if this voice object is capable of playing the given sound.
  29199. If there are different classes of sound, and different classes of voice, a voice can
  29200. choose which ones it wants to take on.
  29201. A typical implementation of this method may just return true if there's only one type
  29202. of voice and sound, or it might check the type of the sound object passed-in and
  29203. see if it's one that it understands.
  29204. */
  29205. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  29206. /** Called to start a new note.
  29207. This will be called during the rendering callback, so must be fast and thread-safe.
  29208. */
  29209. virtual void startNote (const int midiNoteNumber,
  29210. const float velocity,
  29211. SynthesiserSound* sound,
  29212. const int currentPitchWheelPosition) = 0;
  29213. /** Called to stop a note.
  29214. This will be called during the rendering callback, so must be fast and thread-safe.
  29215. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  29216. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  29217. and allow the synth to reassign it another sound.
  29218. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  29219. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  29220. finishes playing (during the rendering callback), it must make sure that it calls
  29221. clearCurrentNote().
  29222. */
  29223. virtual void stopNote (const bool allowTailOff) = 0;
  29224. /** Called to let the voice know that the pitch wheel has been moved.
  29225. This will be called during the rendering callback, so must be fast and thread-safe.
  29226. */
  29227. virtual void pitchWheelMoved (const int newValue) = 0;
  29228. /** Called to let the voice know that a midi controller has been moved.
  29229. This will be called during the rendering callback, so must be fast and thread-safe.
  29230. */
  29231. virtual void controllerMoved (const int controllerNumber,
  29232. const int newValue) = 0;
  29233. /** Renders the next block of data for this voice.
  29234. The output audio data must be added to the current contents of the buffer provided.
  29235. Only the region of the buffer between startSample and (startSample + numSamples)
  29236. should be altered by this method.
  29237. If the voice is currently silent, it should just return without doing anything.
  29238. If the sound that the voice is playing finishes during the course of this rendered
  29239. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  29240. The size of the blocks that are rendered can change each time it is called, and may
  29241. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  29242. the voice's methods will be called to tell it about note and controller events.
  29243. */
  29244. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  29245. int startSample,
  29246. int numSamples) = 0;
  29247. /** Returns true if the voice is currently playing a sound which is mapped to the given
  29248. midi channel.
  29249. If it's not currently playing, this will return false.
  29250. */
  29251. bool isPlayingChannel (const int midiChannel) const;
  29252. /** Changes the voice's reference sample rate.
  29253. The rate is set so that subclasses know the output rate and can set their pitch
  29254. accordingly.
  29255. This method is called by the synth, and subclasses can access the current rate with
  29256. the currentSampleRate member.
  29257. */
  29258. void setCurrentPlaybackSampleRate (const double newRate);
  29259. juce_UseDebuggingNewOperator
  29260. protected:
  29261. /** Returns the current target sample rate at which rendering is being done.
  29262. This is available for subclasses so they can pitch things correctly.
  29263. */
  29264. double getSampleRate() const { return currentSampleRate; }
  29265. /** Resets the state of this voice after a sound has finished playing.
  29266. The subclass must call this when it finishes playing a note and becomes available
  29267. to play new ones.
  29268. It must either call it in the stopNote() method, or if the voice is tailing off,
  29269. then it should call it later during the renderNextBlock method, as soon as it
  29270. finishes its tail-off.
  29271. It can also be called at any time during the render callback if the sound happens
  29272. to have finished, e.g. if it's playing a sample and the sample finishes.
  29273. */
  29274. void clearCurrentNote();
  29275. private:
  29276. friend class Synthesiser;
  29277. double currentSampleRate;
  29278. int currentlyPlayingNote;
  29279. uint32 noteOnTime;
  29280. SynthesiserSound::Ptr currentlyPlayingSound;
  29281. };
  29282. /**
  29283. Base class for a musical device that can play sounds.
  29284. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  29285. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  29286. which can play back one of these sounds.
  29287. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  29288. set of sounds, and a set of voices it can use to play them. If you only give it
  29289. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  29290. have available.
  29291. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  29292. events that go in will be scanned for note on/off messages, and these are used to
  29293. start and stop the voices playing the appropriate sounds.
  29294. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  29295. noteOff() and other controller methods.
  29296. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  29297. what the target playback rate is. This value is passed on to the voices so that
  29298. they can pitch their output correctly.
  29299. */
  29300. class JUCE_API Synthesiser
  29301. {
  29302. public:
  29303. /** Creates a new synthesiser.
  29304. You'll need to add some sounds and voices before it'll make any sound..
  29305. */
  29306. Synthesiser();
  29307. /** Destructor. */
  29308. virtual ~Synthesiser();
  29309. /** Deletes all voices. */
  29310. void clearVoices();
  29311. /** Returns the number of voices that have been added. */
  29312. int getNumVoices() const { return voices.size(); }
  29313. /** Returns one of the voices that have been added. */
  29314. SynthesiserVoice* getVoice (const int index) const;
  29315. /** Adds a new voice to the synth.
  29316. All the voices should be the same class of object and are treated equally.
  29317. The object passed in will be managed by the synthesiser, which will delete
  29318. it later on when no longer needed. The caller should not retain a pointer to the
  29319. voice.
  29320. */
  29321. void addVoice (SynthesiserVoice* const newVoice);
  29322. /** Deletes one of the voices. */
  29323. void removeVoice (const int index);
  29324. /** Deletes all sounds. */
  29325. void clearSounds();
  29326. /** Returns the number of sounds that have been added to the synth. */
  29327. int getNumSounds() const { return sounds.size(); }
  29328. /** Returns one of the sounds. */
  29329. SynthesiserSound* getSound (const int index) const { return sounds [index]; }
  29330. /** Adds a new sound to the synthesiser.
  29331. The object passed in is reference counted, so will be deleted when it is removed
  29332. from the synthesiser, and when no voices are still using it.
  29333. */
  29334. void addSound (const SynthesiserSound::Ptr& newSound);
  29335. /** Removes and deletes one of the sounds. */
  29336. void removeSound (const int index);
  29337. /** If set to true, then the synth will try to take over an existing voice if
  29338. it runs out and needs to play another note.
  29339. The value of this boolean is passed into findFreeVoice(), so the result will
  29340. depend on the implementation of this method.
  29341. */
  29342. void setNoteStealingEnabled (const bool shouldStealNotes);
  29343. /** Returns true if note-stealing is enabled.
  29344. @see setNoteStealingEnabled
  29345. */
  29346. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  29347. /** Triggers a note-on event.
  29348. The default method here will find all the sounds that want to be triggered by
  29349. this note/channel. For each sound, it'll try to find a free voice, and use the
  29350. voice to start playing the sound.
  29351. Subclasses might want to override this if they need a more complex algorithm.
  29352. This method will be called automatically according to the midi data passed into
  29353. renderNextBlock(), but may be called explicitly too.
  29354. */
  29355. virtual void noteOn (const int midiChannel,
  29356. const int midiNoteNumber,
  29357. const float velocity);
  29358. /** Triggers a note-off event.
  29359. This will turn off any voices that are playing a sound for the given note/channel.
  29360. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  29361. (if they can do). If this is false, the notes will all be cut off immediately.
  29362. This method will be called automatically according to the midi data passed into
  29363. renderNextBlock(), but may be called explicitly too.
  29364. */
  29365. virtual void noteOff (const int midiChannel,
  29366. const int midiNoteNumber,
  29367. const bool allowTailOff);
  29368. /** Turns off all notes.
  29369. This will turn off any voices that are playing a sound on the given midi channel.
  29370. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  29371. which channel they're playing.
  29372. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  29373. (if they can do). If this is false, the notes will all be cut off immediately.
  29374. This method will be called automatically according to the midi data passed into
  29375. renderNextBlock(), but may be called explicitly too.
  29376. */
  29377. virtual void allNotesOff (const int midiChannel,
  29378. const bool allowTailOff);
  29379. /** Sends a pitch-wheel message.
  29380. This will send a pitch-wheel message to any voices that are playing sounds on
  29381. the given midi channel.
  29382. This method will be called automatically according to the midi data passed into
  29383. renderNextBlock(), but may be called explicitly too.
  29384. @param midiChannel the midi channel for the event
  29385. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  29386. */
  29387. virtual void handlePitchWheel (const int midiChannel,
  29388. const int wheelValue);
  29389. /** Sends a midi controller message.
  29390. This will send a midi controller message to any voices that are playing sounds on
  29391. the given midi channel.
  29392. This method will be called automatically according to the midi data passed into
  29393. renderNextBlock(), but may be called explicitly too.
  29394. @param midiChannel the midi channel for the event
  29395. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  29396. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  29397. */
  29398. virtual void handleController (const int midiChannel,
  29399. const int controllerNumber,
  29400. const int controllerValue);
  29401. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  29402. render.
  29403. This value is propagated to the voices so that they can use it to render the correct
  29404. pitches.
  29405. */
  29406. void setCurrentPlaybackSampleRate (const double sampleRate);
  29407. /** Creates the next block of audio output.
  29408. This will process the next numSamples of data from all the voices, and add that output
  29409. to the audio block supplied, starting from the offset specified. Note that the
  29410. data will be added to the current contents of the buffer, so you should clear it
  29411. before calling this method if necessary.
  29412. The midi events in the inputMidi buffer are parsed for note and controller events,
  29413. and these are used to trigger the voices. Note that the startSample offset applies
  29414. both to the audio output buffer and the midi input buffer, so any midi events
  29415. with timestamps outside the specified region will be ignored.
  29416. */
  29417. void renderNextBlock (AudioSampleBuffer& outputAudio,
  29418. const MidiBuffer& inputMidi,
  29419. int startSample,
  29420. int numSamples);
  29421. juce_UseDebuggingNewOperator
  29422. protected:
  29423. /** This is used to control access to the rendering callback and the note trigger methods. */
  29424. CriticalSection lock;
  29425. OwnedArray <SynthesiserVoice> voices;
  29426. ReferenceCountedArray <SynthesiserSound> sounds;
  29427. /** The last pitch-wheel values for each midi channel. */
  29428. int lastPitchWheelValues [16];
  29429. /** Searches through the voices to find one that's not currently playing, and which
  29430. can play the given sound.
  29431. Returns 0 if all voices are busy and stealing isn't enabled.
  29432. This can be overridden to implement custom voice-stealing algorithms.
  29433. */
  29434. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  29435. const bool stealIfNoneAvailable) const;
  29436. /** Starts a specified voice playing a particular sound.
  29437. You'll probably never need to call this, it's used internally by noteOn(), but
  29438. may be needed by subclasses for custom behaviours.
  29439. */
  29440. void startVoice (SynthesiserVoice* const voice,
  29441. SynthesiserSound* const sound,
  29442. const int midiChannel,
  29443. const int midiNoteNumber,
  29444. const float velocity);
  29445. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  29446. int findFreeVoice (const bool) const { return 0; }
  29447. private:
  29448. double sampleRate;
  29449. uint32 lastNoteOnCounter;
  29450. bool shouldStealNotes;
  29451. Synthesiser (const Synthesiser&);
  29452. const Synthesiser& operator= (const Synthesiser&);
  29453. };
  29454. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  29455. /********* End of inlined file: juce_Synthesiser.h *********/
  29456. /**
  29457. A subclass of SynthesiserSound that represents a sampled audio clip.
  29458. This is a pretty basic sampler, and just attempts to load the whole audio stream
  29459. into memory.
  29460. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  29461. give it some SampledSound objects to play.
  29462. @see SamplerVoice, Synthesiser, SynthesiserSound
  29463. */
  29464. class JUCE_API SamplerSound : public SynthesiserSound
  29465. {
  29466. public:
  29467. /** Creates a sampled sound from an audio reader.
  29468. This will attempt to load the audio from the source into memory and store
  29469. it in this object.
  29470. @param name a name for the sample
  29471. @param source the audio to load. This object can be safely deleted by the
  29472. caller after this constructor returns
  29473. @param midiNotes the set of midi keys that this sound should be played on. This
  29474. is used by the SynthesiserSound::appliesToNote() method
  29475. @param midiNoteForNormalPitch the midi note at which the sample should be played
  29476. with its natural rate. All other notes will be pitched
  29477. up or down relative to this one
  29478. @param attackTimeSecs the attack (fade-in) time, in seconds
  29479. @param releaseTimeSecs the decay (fade-out) time, in seconds
  29480. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  29481. source, in seconds
  29482. */
  29483. SamplerSound (const String& name,
  29484. AudioFormatReader& source,
  29485. const BitArray& midiNotes,
  29486. const int midiNoteForNormalPitch,
  29487. const double attackTimeSecs,
  29488. const double releaseTimeSecs,
  29489. const double maxSampleLengthSeconds);
  29490. /** Destructor. */
  29491. ~SamplerSound();
  29492. /** Returns the sample's name */
  29493. const String& getName() const { return name; }
  29494. /** Returns the audio sample data.
  29495. This could be 0 if there was a problem loading it.
  29496. */
  29497. AudioSampleBuffer* getAudioData() const { return data; }
  29498. bool appliesToNote (const int midiNoteNumber);
  29499. bool appliesToChannel (const int midiChannel);
  29500. juce_UseDebuggingNewOperator
  29501. private:
  29502. friend class SamplerVoice;
  29503. String name;
  29504. ScopedPointer <AudioSampleBuffer> data;
  29505. double sourceSampleRate;
  29506. BitArray midiNotes;
  29507. int length, attackSamples, releaseSamples;
  29508. int midiRootNote;
  29509. };
  29510. /**
  29511. A subclass of SynthesiserVoice that can play a SamplerSound.
  29512. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  29513. give it some SampledSound objects to play.
  29514. @see SamplerSound, Synthesiser, SynthesiserVoice
  29515. */
  29516. class JUCE_API SamplerVoice : public SynthesiserVoice
  29517. {
  29518. public:
  29519. /** Creates a SamplerVoice.
  29520. */
  29521. SamplerVoice();
  29522. /** Destructor. */
  29523. ~SamplerVoice();
  29524. bool canPlaySound (SynthesiserSound* sound);
  29525. void startNote (const int midiNoteNumber,
  29526. const float velocity,
  29527. SynthesiserSound* sound,
  29528. const int currentPitchWheelPosition);
  29529. void stopNote (const bool allowTailOff);
  29530. void pitchWheelMoved (const int newValue);
  29531. void controllerMoved (const int controllerNumber,
  29532. const int newValue);
  29533. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  29534. juce_UseDebuggingNewOperator
  29535. private:
  29536. double pitchRatio;
  29537. double sourceSamplePosition;
  29538. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  29539. bool isInAttack, isInRelease;
  29540. };
  29541. #endif // __JUCE_SAMPLER_JUCEHEADER__
  29542. /********* End of inlined file: juce_Sampler.h *********/
  29543. #endif
  29544. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  29545. #endif
  29546. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29547. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  29548. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29549. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29550. /********* Start of inlined file: juce_ActionListenerList.h *********/
  29551. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29552. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29553. /**
  29554. A set of ActionListeners.
  29555. Listeners can be added and removed from the list, and messages can be
  29556. broadcast to all the listeners.
  29557. @see ActionListener, ActionBroadcaster
  29558. */
  29559. class JUCE_API ActionListenerList : public MessageListener
  29560. {
  29561. public:
  29562. /** Creates an empty list. */
  29563. ActionListenerList() throw();
  29564. /** Destructor. */
  29565. ~ActionListenerList() throw();
  29566. /** Adds a listener to the list.
  29567. (Trying to add a listener that's already on the list will have no effect).
  29568. */
  29569. void addActionListener (ActionListener* const listener) throw();
  29570. /** Removes a listener from the list.
  29571. If the listener isn't on the list, this won't have any effect.
  29572. */
  29573. void removeActionListener (ActionListener* const listener) throw();
  29574. /** Removes all listeners from the list. */
  29575. void removeAllActionListeners() throw();
  29576. /** Broadcasts a message to all the registered listeners.
  29577. This sends the message asynchronously.
  29578. If a listener is on the list when this method is called but is removed from
  29579. the list before the message arrives, it won't receive the message. Similarly
  29580. listeners that are added to the list after the message is sent but before it
  29581. arrives won't get the message either.
  29582. */
  29583. void sendActionMessage (const String& message) const;
  29584. /** @internal */
  29585. void handleMessage (const Message&);
  29586. juce_UseDebuggingNewOperator
  29587. private:
  29588. SortedSet <void*> actionListeners_;
  29589. CriticalSection actionListenerLock_;
  29590. ActionListenerList (const ActionListenerList&);
  29591. const ActionListenerList& operator= (const ActionListenerList&);
  29592. };
  29593. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29594. /********* End of inlined file: juce_ActionListenerList.h *********/
  29595. /** Manages a list of ActionListeners, and can send them messages.
  29596. To quickly add methods to your class that can add/remove action
  29597. listeners and broadcast to them, you can derive from this.
  29598. @see ActionListenerList, ActionListener
  29599. */
  29600. class JUCE_API ActionBroadcaster
  29601. {
  29602. public:
  29603. /** Creates an ActionBroadcaster. */
  29604. ActionBroadcaster() throw();
  29605. /** Destructor. */
  29606. virtual ~ActionBroadcaster();
  29607. /** Adds a listener to the list.
  29608. (Trying to add a listener that's already on the list will have no effect).
  29609. */
  29610. void addActionListener (ActionListener* const listener);
  29611. /** Removes a listener from the list.
  29612. If the listener isn't on the list, this won't have any effect.
  29613. */
  29614. void removeActionListener (ActionListener* const listener);
  29615. /** Removes all listeners from the list. */
  29616. void removeAllActionListeners();
  29617. /** Broadcasts a message to all the registered listeners.
  29618. @see ActionListenerList::sendActionMessage
  29619. */
  29620. void sendActionMessage (const String& message) const;
  29621. private:
  29622. ActionListenerList actionListenerList;
  29623. ActionBroadcaster (const ActionBroadcaster&);
  29624. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  29625. };
  29626. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29627. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  29628. #endif
  29629. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  29630. #endif
  29631. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29632. #endif
  29633. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  29634. #endif
  29635. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29636. /********* Start of inlined file: juce_CallbackMessage.h *********/
  29637. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29638. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29639. /**
  29640. A message that calls a custom function when it gets delivered.
  29641. You can use this class to fire off actions that you want to be performed later
  29642. on the message thread.
  29643. Unlike other Message objects, these don't get sent to a MessageListener, you
  29644. just call the post() method to send them, and when they arrive, your
  29645. messageCallback() method will automatically be invoked.
  29646. @see MessageListener, MessageManager, ActionListener, ChangeListener
  29647. */
  29648. class JUCE_API CallbackMessage : public Message
  29649. {
  29650. public:
  29651. CallbackMessage() throw();
  29652. /** Destructor. */
  29653. ~CallbackMessage() throw();
  29654. /** Called when the message is delivered.
  29655. You should implement this method and make it do whatever action you want
  29656. to perform.
  29657. Note that like all other messages, this object will be deleted immediately
  29658. after this method has been invoked.
  29659. */
  29660. virtual void messageCallback() = 0;
  29661. /** Instead of sending this message to a MessageListener, just call this method
  29662. to post it to the event queue.
  29663. After you've called this, this object will belong to the MessageManager,
  29664. which will delete it later. So make sure you don't delete the object yourself,
  29665. call post() more than once, or call post() on a stack-based obect!
  29666. */
  29667. void post();
  29668. juce_UseDebuggingNewOperator
  29669. private:
  29670. CallbackMessage (const CallbackMessage&);
  29671. const CallbackMessage& operator= (const CallbackMessage&);
  29672. };
  29673. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29674. /********* End of inlined file: juce_CallbackMessage.h *********/
  29675. #endif
  29676. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  29677. #endif
  29678. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  29679. #endif
  29680. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  29681. #endif
  29682. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29683. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  29684. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29685. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29686. class InterprocessConnectionServer;
  29687. /**
  29688. Manages a simple two-way messaging connection to another process, using either
  29689. a socket or a named pipe as the transport medium.
  29690. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  29691. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  29692. and incoming messages will result in a callback via the messageReceived()
  29693. method.
  29694. To open a pipe and wait for another client to connect to it, use the createPipe()
  29695. method.
  29696. To act as a socket server and create connections for one or more client, see the
  29697. InterprocessConnectionServer class.
  29698. @see InterprocessConnectionServer, Socket, NamedPipe
  29699. */
  29700. class JUCE_API InterprocessConnection : public Thread,
  29701. private MessageListener
  29702. {
  29703. public:
  29704. /** Creates a connection.
  29705. Connections are created manually, connecting them with the connectToSocket()
  29706. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  29707. when a client wants to connect.
  29708. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  29709. connectionLost() and messageReceived() methods will
  29710. always be made using the message thread; if false,
  29711. these will be called immediately on the connection's
  29712. own thread.
  29713. @param magicMessageHeaderNumber a magic number to use in the header to check the
  29714. validity of the data blocks being sent and received. This
  29715. can be any number, but the sender and receiver must obviously
  29716. use matching values or they won't recognise each other.
  29717. */
  29718. InterprocessConnection (const bool callbacksOnMessageThread = true,
  29719. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  29720. /** Destructor. */
  29721. ~InterprocessConnection();
  29722. /** Tries to connect this object to a socket.
  29723. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  29724. object waiting to receive client connections on this port number.
  29725. @param hostName the host computer, either a network address or name
  29726. @param portNumber the socket port number to try to connect to
  29727. @param timeOutMillisecs how long to keep trying before giving up
  29728. @returns true if the connection is established successfully
  29729. @see Socket
  29730. */
  29731. bool connectToSocket (const String& hostName,
  29732. const int portNumber,
  29733. const int timeOutMillisecs);
  29734. /** Tries to connect the object to an existing named pipe.
  29735. For this to work, another process on the same computer must already have opened
  29736. an InterprocessConnection object and used createPipe() to create a pipe for this
  29737. to connect to.
  29738. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  29739. @returns true if it connects successfully.
  29740. @see createPipe, NamedPipe
  29741. */
  29742. bool connectToPipe (const String& pipeName,
  29743. const int pipeReceiveMessageTimeoutMs = -1);
  29744. /** Tries to create a new pipe for other processes to connect to.
  29745. This creates a pipe with the given name, so that other processes can use
  29746. connectToPipe() to connect to the other end.
  29747. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  29748. If another process is already using this pipe, this will fail and return false.
  29749. */
  29750. bool createPipe (const String& pipeName,
  29751. const int pipeReceiveMessageTimeoutMs = -1);
  29752. /** Disconnects and closes any currently-open sockets or pipes. */
  29753. void disconnect();
  29754. /** True if a socket or pipe is currently active. */
  29755. bool isConnected() const;
  29756. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  29757. StreamingSocket* getSocket() const throw() { return socket; }
  29758. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  29759. NamedPipe* getPipe() const throw() { return pipe; }
  29760. /** Returns the name of the machine at the other end of this connection.
  29761. This will return an empty string if the other machine isn't known for
  29762. some reason.
  29763. */
  29764. const String getConnectedHostName() const;
  29765. /** Tries to send a message to the other end of this connection.
  29766. This will fail if it's not connected, or if there's some kind of write error. If
  29767. it succeeds, the connection object at the other end will receive the message by
  29768. a callback to its messageReceived() method.
  29769. @see messageReceived
  29770. */
  29771. bool sendMessage (const MemoryBlock& message);
  29772. /** Called when the connection is first connected.
  29773. If the connection was created with the callbacksOnMessageThread flag set, then
  29774. this will be called on the message thread; otherwise it will be called on a server
  29775. thread.
  29776. */
  29777. virtual void connectionMade() = 0;
  29778. /** Called when the connection is broken.
  29779. If the connection was created with the callbacksOnMessageThread flag set, then
  29780. this will be called on the message thread; otherwise it will be called on a server
  29781. thread.
  29782. */
  29783. virtual void connectionLost() = 0;
  29784. /** Called when a message arrives.
  29785. When the object at the other end of this connection sends us a message with sendMessage(),
  29786. this callback is used to deliver it to us.
  29787. If the connection was created with the callbacksOnMessageThread flag set, then
  29788. this will be called on the message thread; otherwise it will be called on a server
  29789. thread.
  29790. @see sendMessage
  29791. */
  29792. virtual void messageReceived (const MemoryBlock& message) = 0;
  29793. juce_UseDebuggingNewOperator
  29794. private:
  29795. CriticalSection pipeAndSocketLock;
  29796. ScopedPointer <StreamingSocket> socket;
  29797. ScopedPointer <NamedPipe> pipe;
  29798. bool callbackConnectionState;
  29799. const bool useMessageThread;
  29800. const uint32 magicMessageHeader;
  29801. int pipeReceiveMessageTimeout;
  29802. friend class InterprocessConnectionServer;
  29803. void initialiseWithSocket (StreamingSocket* const socket_);
  29804. void initialiseWithPipe (NamedPipe* const pipe_);
  29805. void handleMessage (const Message& message);
  29806. void connectionMadeInt();
  29807. void connectionLostInt();
  29808. void deliverDataInt (const MemoryBlock& data);
  29809. bool readNextMessageInt();
  29810. void run();
  29811. InterprocessConnection (const InterprocessConnection&);
  29812. const InterprocessConnection& operator= (const InterprocessConnection&);
  29813. };
  29814. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29815. /********* End of inlined file: juce_InterprocessConnection.h *********/
  29816. #endif
  29817. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29818. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  29819. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29820. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29821. /**
  29822. An object that waits for client sockets to connect to a port on this host, and
  29823. creates InterprocessConnection objects for each one.
  29824. To use this, create a class derived from it which implements the createConnectionObject()
  29825. method, so that it creates suitable connection objects for each client that tries
  29826. to connect.
  29827. @see InterprocessConnection
  29828. */
  29829. class JUCE_API InterprocessConnectionServer : private Thread
  29830. {
  29831. public:
  29832. /** Creates an uninitialised server object.
  29833. */
  29834. InterprocessConnectionServer();
  29835. /** Destructor. */
  29836. ~InterprocessConnectionServer();
  29837. /** Starts an internal thread which listens on the given port number.
  29838. While this is running, in another process tries to connect with the
  29839. InterprocessConnection::connectToSocket() method, this object will call
  29840. createConnectionObject() to create a connection to that client.
  29841. Use stop() to stop the thread running.
  29842. @see createConnectionObject, stop
  29843. */
  29844. bool beginWaitingForSocket (const int portNumber);
  29845. /** Terminates the listener thread, if it's active.
  29846. @see beginWaitingForSocket
  29847. */
  29848. void stop();
  29849. protected:
  29850. /** Creates a suitable connection object for a client process that wants to
  29851. connect to this one.
  29852. This will be called by the listener thread when a client process tries
  29853. to connect, and must return a new InterprocessConnection object that will
  29854. then run as this end of the connection.
  29855. @see InterprocessConnection
  29856. */
  29857. virtual InterprocessConnection* createConnectionObject() = 0;
  29858. public:
  29859. juce_UseDebuggingNewOperator
  29860. private:
  29861. ScopedPointer <StreamingSocket> socket;
  29862. void run();
  29863. InterprocessConnectionServer (const InterprocessConnectionServer&);
  29864. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  29865. };
  29866. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29867. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  29868. #endif
  29869. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  29870. #endif
  29871. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  29872. #endif
  29873. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29874. /********* Start of inlined file: juce_MessageManager.h *********/
  29875. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29876. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29877. class Component;
  29878. class MessageManagerLock;
  29879. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  29880. */
  29881. typedef void* (MessageCallbackFunction) (void* userData);
  29882. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  29883. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  29884. */
  29885. class JUCE_API MessageManager
  29886. {
  29887. public:
  29888. /** Returns the global instance of the MessageManager. */
  29889. static MessageManager* getInstance() throw();
  29890. /** Runs the event dispatch loop until a stop message is posted.
  29891. This method is only intended to be run by the application's startup routine,
  29892. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  29893. @see stopDispatchLoop
  29894. */
  29895. void runDispatchLoop();
  29896. /** Sends a signal that the dispatch loop should terminate.
  29897. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  29898. will be interrupted and will return.
  29899. @see runDispatchLoop
  29900. */
  29901. void stopDispatchLoop();
  29902. /** Returns true if the stopDispatchLoop() method has been called.
  29903. */
  29904. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  29905. /** Synchronously dispatches messages until a given time has elapsed.
  29906. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  29907. otherwise returns true.
  29908. */
  29909. bool runDispatchLoopUntil (int millisecondsToRunFor);
  29910. /** Calls a function using the message-thread.
  29911. This can be used by any thread to cause this function to be called-back
  29912. by the message thread. If it's the message-thread that's calling this method,
  29913. then the function will just be called; if another thread is calling, a message
  29914. will be posted to the queue, and this method will block until that message
  29915. is delivered, the function is called, and the result is returned.
  29916. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  29917. thread has a critical section locked, which an unrelated message callback then tries to lock
  29918. before the message thread gets round to processing this callback.
  29919. @param callback the function to call - its signature must be @code
  29920. void* myCallbackFunction (void*) @endcode
  29921. @param userData a user-defined pointer that will be passed to the function that gets called
  29922. @returns the value that the callback function returns.
  29923. @see MessageManagerLock
  29924. */
  29925. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  29926. void* userData);
  29927. /** Returns true if the caller-thread is the message thread. */
  29928. bool isThisTheMessageThread() const throw();
  29929. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  29930. (Best to ignore this method unless you really know what you're doing..)
  29931. @see getCurrentMessageThread
  29932. */
  29933. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  29934. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  29935. (Best to ignore this method unless you really know what you're doing..)
  29936. @see setCurrentMessageThread
  29937. */
  29938. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  29939. /** Returns true if the caller thread has currenltly got the message manager locked.
  29940. see the MessageManagerLock class for more info about this.
  29941. This will be true if the caller is the message thread, because that automatically
  29942. gains a lock while a message is being dispatched.
  29943. */
  29944. bool currentThreadHasLockedMessageManager() const throw();
  29945. /** Sends a message to all other JUCE applications that are running.
  29946. @param messageText the string that will be passed to the actionListenerCallback()
  29947. method of the broadcast listeners in the other app.
  29948. @see registerBroadcastListener, ActionListener
  29949. */
  29950. static void broadcastMessage (const String& messageText) throw();
  29951. /** Registers a listener to get told about broadcast messages.
  29952. The actionListenerCallback() callback's string parameter
  29953. is the message passed into broadcastMessage().
  29954. @see broadcastMessage
  29955. */
  29956. void registerBroadcastListener (ActionListener* listener) throw();
  29957. /** Deregisters a broadcast listener. */
  29958. void deregisterBroadcastListener (ActionListener* listener) throw();
  29959. /** @internal */
  29960. void deliverMessage (void*);
  29961. /** @internal */
  29962. void deliverBroadcastMessage (const String&);
  29963. /** @internal */
  29964. ~MessageManager() throw();
  29965. juce_UseDebuggingNewOperator
  29966. private:
  29967. MessageManager() throw();
  29968. friend class MessageListener;
  29969. friend class ChangeBroadcaster;
  29970. friend class ActionBroadcaster;
  29971. friend class CallbackMessage;
  29972. static MessageManager* instance;
  29973. SortedSet <const MessageListener*> messageListeners;
  29974. ScopedPointer <ActionListenerList> broadcastListeners;
  29975. friend class JUCEApplication;
  29976. bool quitMessagePosted, quitMessageReceived;
  29977. Thread::ThreadID messageThreadId;
  29978. VoidArray modalComponents;
  29979. static void* exitModalLoopCallback (void*);
  29980. void postMessageToQueue (Message* const message);
  29981. void postCallbackMessage (Message* const message);
  29982. static void doPlatformSpecificInitialisation();
  29983. static void doPlatformSpecificShutdown();
  29984. friend class MessageManagerLock;
  29985. Thread::ThreadID volatile threadWithLock;
  29986. CriticalSection lockingLock;
  29987. MessageManager (const MessageManager&);
  29988. const MessageManager& operator= (const MessageManager&);
  29989. };
  29990. /** Used to make sure that the calling thread has exclusive access to the message loop.
  29991. Because it's not thread-safe to call any of the Component or other UI classes
  29992. from threads other than the message thread, one of these objects can be used to
  29993. lock the message loop and allow this to be done. The message thread will be
  29994. suspended for the lifetime of the MessageManagerLock object, so create one on
  29995. the stack like this: @code
  29996. void MyThread::run()
  29997. {
  29998. someData = 1234;
  29999. const MessageManagerLock mmLock;
  30000. // the event loop will now be locked so it's safe to make a few calls..
  30001. myComponent->setBounds (newBounds);
  30002. myComponent->repaint();
  30003. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  30004. }
  30005. @endcode
  30006. Obviously be careful not to create one of these and leave it lying around, or
  30007. your app will grind to a halt!
  30008. Another caveat is that using this in conjunction with other CriticalSections
  30009. can create lots of interesting ways of producing a deadlock! In particular, if
  30010. your message thread calls stopThread() for a thread that uses these locks,
  30011. you'll get an (occasional) deadlock..
  30012. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  30013. */
  30014. class JUCE_API MessageManagerLock
  30015. {
  30016. public:
  30017. /** Tries to acquire a lock on the message manager.
  30018. The constructor attempts to gain a lock on the message loop, and the lock will be
  30019. kept for the lifetime of this object.
  30020. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  30021. this method will keep checking whether the thread has been given the
  30022. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  30023. without gaining the lock. If you pass a thread, you must check whether the lock was
  30024. successful by calling lockWasGained(). If this is false, your thread is being told to
  30025. die, so you should take evasive action.
  30026. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  30027. careful when doing this, because it's very easy to deadlock if your message thread
  30028. attempts to call stopThread() on a thread just as that thread attempts to get the
  30029. message lock.
  30030. If the calling thread already has the lock, nothing will be done, so it's safe and
  30031. quick to use these locks recursively.
  30032. E.g.
  30033. @code
  30034. void run()
  30035. {
  30036. ...
  30037. while (! threadShouldExit())
  30038. {
  30039. MessageManagerLock mml (Thread::getCurrentThread());
  30040. if (! mml.lockWasGained())
  30041. return; // another thread is trying to kill us!
  30042. ..do some locked stuff here..
  30043. }
  30044. ..and now the MM is now unlocked..
  30045. }
  30046. @endcode
  30047. */
  30048. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  30049. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  30050. instead of a thread.
  30051. See the MessageManagerLock (Thread*) constructor for details on how this works.
  30052. */
  30053. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  30054. /** Releases the current thread's lock on the message manager.
  30055. Make sure this object is created and deleted by the same thread,
  30056. otherwise there are no guarantees what will happen!
  30057. */
  30058. ~MessageManagerLock() throw();
  30059. /** Returns true if the lock was successfully acquired.
  30060. (See the constructor that takes a Thread for more info).
  30061. */
  30062. bool lockWasGained() const throw() { return locked; }
  30063. private:
  30064. bool locked, needsUnlocking;
  30065. void* sharedEvents;
  30066. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  30067. MessageManagerLock (const MessageManagerLock&);
  30068. const MessageManagerLock& operator= (const MessageManagerLock&);
  30069. };
  30070. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  30071. /********* End of inlined file: juce_MessageManager.h *********/
  30072. #endif
  30073. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  30074. /********* Start of inlined file: juce_MultiTimer.h *********/
  30075. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  30076. #define __JUCE_MULTITIMER_JUCEHEADER__
  30077. /**
  30078. A type of timer class that can run multiple timers with different frequencies,
  30079. all of which share a single callback.
  30080. This class is very similar to the Timer class, but allows you run multiple
  30081. separate timers, where each one has a unique ID number. The methods in this
  30082. class are exactly equivalent to those in Timer, but with the addition of
  30083. this ID number.
  30084. To use it, you need to create a subclass of MultiTimer, implementing the
  30085. timerCallback() method. Then you can start timers with startTimer(), and
  30086. each time the callback is triggered, it passes in the ID of the timer that
  30087. caused it.
  30088. @see Timer
  30089. */
  30090. class JUCE_API MultiTimer
  30091. {
  30092. protected:
  30093. /** Creates a MultiTimer.
  30094. When created, no timers are running, so use startTimer() to start things off.
  30095. */
  30096. MultiTimer() throw();
  30097. /** Creates a copy of another timer.
  30098. Note that this timer will not contain any running timers, even if the one you're
  30099. copying from was running.
  30100. */
  30101. MultiTimer (const MultiTimer& other) throw();
  30102. public:
  30103. /** Destructor. */
  30104. virtual ~MultiTimer();
  30105. /** The user-defined callback routine that actually gets called by each of the
  30106. timers that are running.
  30107. It's perfectly ok to call startTimer() or stopTimer() from within this
  30108. callback to change the subsequent intervals.
  30109. */
  30110. virtual void timerCallback (const int timerId) = 0;
  30111. /** Starts a timer and sets the length of interval required.
  30112. If the timer is already started, this will reset it, so the
  30113. time between calling this method and the next timer callback
  30114. will not be less than the interval length passed in.
  30115. @param timerId a unique Id number that identifies the timer to
  30116. start. This is the id that will be passed back
  30117. to the timerCallback() method when this timer is
  30118. triggered
  30119. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  30120. rounded up to 1)
  30121. */
  30122. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  30123. /** Stops a timer.
  30124. If a timer has been started with the given ID number, it will be cancelled.
  30125. No more callbacks will be made for the specified timer after this method returns.
  30126. If this is called from a different thread, any callbacks that may
  30127. be currently executing may be allowed to finish before the method
  30128. returns.
  30129. */
  30130. void stopTimer (const int timerId) throw();
  30131. /** Checks whether a timer has been started for a specified ID.
  30132. @returns true if a timer with the given ID is running.
  30133. */
  30134. bool isTimerRunning (const int timerId) const throw();
  30135. /** Returns the interval for a specified timer ID.
  30136. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  30137. is running for the ID number specified.
  30138. */
  30139. int getTimerInterval (const int timerId) const throw();
  30140. private:
  30141. CriticalSection timerListLock;
  30142. VoidArray timers;
  30143. const MultiTimer& operator= (const MultiTimer&);
  30144. };
  30145. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  30146. /********* End of inlined file: juce_MultiTimer.h *********/
  30147. #endif
  30148. #ifndef __JUCE_TIMER_JUCEHEADER__
  30149. #endif
  30150. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30151. /********* Start of inlined file: juce_ArrowButton.h *********/
  30152. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30153. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30154. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30155. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30156. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30157. /**
  30158. An effect filter that adds a drop-shadow behind the image's content.
  30159. (This will only work on images/components that aren't opaque, of course).
  30160. When added to a component, this effect will draw a soft-edged
  30161. shadow based on what gets drawn inside it. The shadow will also
  30162. be applied to the component's children.
  30163. For speed, this doesn't use a proper gaussian blur, but cheats by
  30164. using a simple bilinear filter. If you need a really high-quality
  30165. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30166. @see Component::setComponentEffect
  30167. */
  30168. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30169. {
  30170. public:
  30171. /** Creates a default drop-shadow effect.
  30172. To customise the shadow's appearance, use the setShadowProperties()
  30173. method.
  30174. */
  30175. DropShadowEffect();
  30176. /** Destructor. */
  30177. ~DropShadowEffect();
  30178. /** Sets up parameters affecting the shadow's appearance.
  30179. @param newRadius the (approximate) radius of the blur used
  30180. @param newOpacity the opacity with which the shadow is rendered
  30181. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30182. component's contents
  30183. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30184. component's contents
  30185. */
  30186. void setShadowProperties (const float newRadius,
  30187. const float newOpacity,
  30188. const int newShadowOffsetX,
  30189. const int newShadowOffsetY);
  30190. /** @internal */
  30191. void applyEffect (Image& sourceImage, Graphics& destContext);
  30192. juce_UseDebuggingNewOperator
  30193. private:
  30194. int offsetX, offsetY;
  30195. float radius, opacity;
  30196. };
  30197. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30198. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30199. /**
  30200. A button with an arrow in it.
  30201. @see Button
  30202. */
  30203. class JUCE_API ArrowButton : public Button
  30204. {
  30205. public:
  30206. /** Creates an ArrowButton.
  30207. @param buttonName the name to give the button
  30208. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30209. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30210. @param arrowColour the colour to use for the arrow
  30211. */
  30212. ArrowButton (const String& buttonName,
  30213. float arrowDirection,
  30214. const Colour& arrowColour);
  30215. /** Destructor. */
  30216. ~ArrowButton();
  30217. juce_UseDebuggingNewOperator
  30218. protected:
  30219. /** @internal */
  30220. void paintButton (Graphics& g,
  30221. bool isMouseOverButton,
  30222. bool isButtonDown);
  30223. /** @internal */
  30224. void buttonStateChanged();
  30225. private:
  30226. Colour colour;
  30227. DropShadowEffect shadow;
  30228. Path path;
  30229. int offset;
  30230. ArrowButton (const ArrowButton&);
  30231. const ArrowButton& operator= (const ArrowButton&);
  30232. };
  30233. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30234. /********* End of inlined file: juce_ArrowButton.h *********/
  30235. #endif
  30236. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30237. #endif
  30238. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30239. /********* Start of inlined file: juce_DrawableButton.h *********/
  30240. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30241. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30242. /********* Start of inlined file: juce_Drawable.h *********/
  30243. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30244. #define __JUCE_DRAWABLE_JUCEHEADER__
  30245. /**
  30246. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30247. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30248. */
  30249. class JUCE_API Drawable
  30250. {
  30251. protected:
  30252. /** The base class can't be instantiated directly.
  30253. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30254. */
  30255. Drawable();
  30256. public:
  30257. /** Destructor. */
  30258. virtual ~Drawable();
  30259. /** Creates a deep copy of this Drawable object.
  30260. Use this to create a new copy of this and any sub-objects in the tree.
  30261. */
  30262. virtual Drawable* createCopy() const = 0;
  30263. /** Renders this Drawable object.
  30264. @see drawWithin
  30265. */
  30266. void draw (Graphics& g, const float opacity,
  30267. const AffineTransform& transform = AffineTransform::identity) const;
  30268. /** Renders the Drawable at a given offset within the Graphics context.
  30269. The co-ordinates passed-in are used to translate the object relative to its own
  30270. origin before drawing it - this is basically a quick way of saying:
  30271. @code
  30272. draw (g, AffineTransform::translation (x, y)).
  30273. @endcode
  30274. */
  30275. void drawAt (Graphics& g,
  30276. const float x,
  30277. const float y,
  30278. const float opacity) const;
  30279. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30280. changing its aspect-ratio.
  30281. The object can placed arbitrarily within the rectangle based on a Justification type,
  30282. and can either be made as big as possible, or just reduced to fit.
  30283. @param g the graphics context to render onto
  30284. @param destX top-left of the target rectangle to fit it into
  30285. @param destY top-left of the target rectangle to fit it into
  30286. @param destWidth size of the target rectangle to fit the image into
  30287. @param destHeight size of the target rectangle to fit the image into
  30288. @param placement defines the alignment and rescaling to use to fit
  30289. this object within the target rectangle.
  30290. @param opacity the opacity to use, in the range 0 to 1.0
  30291. */
  30292. void drawWithin (Graphics& g,
  30293. const int destX,
  30294. const int destY,
  30295. const int destWidth,
  30296. const int destHeight,
  30297. const RectanglePlacement& placement,
  30298. const float opacity) const;
  30299. /** Holds the information needed when telling a drawable to render itself.
  30300. @see Drawable::draw
  30301. */
  30302. class RenderingContext
  30303. {
  30304. public:
  30305. RenderingContext (Graphics& g, const AffineTransform& transform, const float opacity) throw();
  30306. Graphics& g;
  30307. AffineTransform transform;
  30308. float opacity;
  30309. private:
  30310. const RenderingContext& operator= (const RenderingContext&);
  30311. };
  30312. /** Renders this Drawable object.
  30313. @see draw
  30314. */
  30315. virtual void render (const RenderingContext& context) const = 0;
  30316. /** Returns the smallest rectangle that can contain this Drawable object.
  30317. Co-ordinates are relative to the object's own origin.
  30318. */
  30319. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30320. /** Returns true if the given point is somewhere inside this Drawable.
  30321. Co-ordinates are relative to the object's own origin.
  30322. */
  30323. virtual bool hitTest (float x, float y) const = 0;
  30324. /** Returns the name given to this drawable.
  30325. @see setName
  30326. */
  30327. const String& getName() const throw() { return name; }
  30328. /** Assigns a name to this drawable. */
  30329. void setName (const String& newName) throw() { name = newName; }
  30330. /** Tries to turn some kind of image file into a drawable.
  30331. The data could be an image that the ImageFileFormat class understands, or it
  30332. could be SVG.
  30333. */
  30334. static Drawable* createFromImageData (const void* data, const int numBytes);
  30335. /** Tries to turn a stream containing some kind of image data into a drawable.
  30336. The data could be an image that the ImageFileFormat class understands, or it
  30337. could be SVG.
  30338. */
  30339. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30340. /** Tries to turn a file containing some kind of image data into a drawable.
  30341. The data could be an image that the ImageFileFormat class understands, or it
  30342. could be SVG.
  30343. */
  30344. static Drawable* createFromImageFile (const File& file);
  30345. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30346. into a Drawable tree.
  30347. The object returned must be deleted by the caller. If something goes wrong
  30348. while parsing, it may return 0.
  30349. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30350. implementation, but it can return the basic vector objects.
  30351. */
  30352. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30353. /** Tries to create a Drawable from a previously-saved ValueTree.
  30354. The ValueTree must have been created by the createValueTree() method.
  30355. */
  30356. static Drawable* createFromValueTree (const ValueTree& tree) throw();
  30357. /** Creates a ValueTree to represent this Drawable.
  30358. The VarTree that is returned can be turned back into a Drawable with
  30359. createFromValueTree().
  30360. */
  30361. virtual ValueTree createValueTree() const throw() = 0;
  30362. juce_UseDebuggingNewOperator
  30363. private:
  30364. Drawable (const Drawable&);
  30365. const Drawable& operator= (const Drawable&);
  30366. String name;
  30367. };
  30368. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30369. /********* End of inlined file: juce_Drawable.h *********/
  30370. /**
  30371. A button that displays a Drawable.
  30372. Up to three Drawable objects can be given to this button, to represent the
  30373. 'normal', 'over' and 'down' states.
  30374. @see Button
  30375. */
  30376. class JUCE_API DrawableButton : public Button
  30377. {
  30378. public:
  30379. enum ButtonStyle
  30380. {
  30381. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30382. ImageRaw, /**< The button will just display the images in their normal size and position.
  30383. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30384. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30385. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30386. };
  30387. /** Creates a DrawableButton.
  30388. After creating one of these, use setImages() to specify the drawables to use.
  30389. @param buttonName the name to give the component
  30390. @param buttonStyle the layout to use
  30391. @see ButtonStyle, setButtonStyle, setImages
  30392. */
  30393. DrawableButton (const String& buttonName,
  30394. const ButtonStyle buttonStyle);
  30395. /** Destructor. */
  30396. ~DrawableButton();
  30397. /** Sets up the images to draw for the various button states.
  30398. The button will keep its own internal copies of these drawables.
  30399. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30400. will be made of the object passed-in if it is non-zero.
  30401. @param overImage the thing to draw for the button's 'over' state - if this is
  30402. zero, the button's normal image will be used when the mouse is
  30403. over it. An internal copy will be made of the object passed-in
  30404. if it is non-zero.
  30405. @param downImage the thing to draw for the button's 'down' state - if this is
  30406. zero, the 'over' image will be used instead (or the normal image
  30407. as a last resort). An internal copy will be made of the object
  30408. passed-in if it is non-zero.
  30409. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30410. the normal image will be drawn with a reduced opacity instead.
  30411. An internal copy will be made of the object passed-in if it is
  30412. non-zero.
  30413. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30414. state is 'on'. If this is 0, the normal image is used instead
  30415. @param overImageOn same as the overImage, but this is used when the button's toggle
  30416. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30417. @param downImageOn same as the downImage, but this is used when the button's toggle
  30418. state is 'on'. If this is 0, the overImageOn is drawn instead
  30419. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30420. state is 'on'. If this is 0, the normal image will be drawn instead
  30421. with a reduced opacity
  30422. */
  30423. void setImages (const Drawable* normalImage,
  30424. const Drawable* overImage = 0,
  30425. const Drawable* downImage = 0,
  30426. const Drawable* disabledImage = 0,
  30427. const Drawable* normalImageOn = 0,
  30428. const Drawable* overImageOn = 0,
  30429. const Drawable* downImageOn = 0,
  30430. const Drawable* disabledImageOn = 0);
  30431. /** Changes the button's style.
  30432. @see ButtonStyle
  30433. */
  30434. void setButtonStyle (const ButtonStyle newStyle);
  30435. /** Changes the button's background colours.
  30436. The toggledOffColour is the colour to use when the button's toggle state
  30437. is off, and toggledOnColour when it's on.
  30438. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30439. used to fill the background of the component.
  30440. For an ImageOnButtonBackground style, the colour is used to draw the
  30441. button's lozenge shape and exactly how the colour's used will depend
  30442. on the LookAndFeel.
  30443. */
  30444. void setBackgroundColours (const Colour& toggledOffColour,
  30445. const Colour& toggledOnColour);
  30446. /** Returns the current background colour being used.
  30447. @see setBackgroundColour
  30448. */
  30449. const Colour& getBackgroundColour() const throw();
  30450. /** Gives the button an optional amount of space around the edge of the drawable.
  30451. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30452. ones on a button background. If the button is too small for the given gap, a
  30453. smaller gap will be used.
  30454. By default there's a gap of about 3 pixels.
  30455. */
  30456. void setEdgeIndent (const int numPixelsIndent);
  30457. /** Returns the image that the button is currently displaying. */
  30458. const Drawable* getCurrentImage() const throw();
  30459. const Drawable* getNormalImage() const throw();
  30460. const Drawable* getOverImage() const throw();
  30461. const Drawable* getDownImage() const throw();
  30462. juce_UseDebuggingNewOperator
  30463. protected:
  30464. /** @internal */
  30465. void paintButton (Graphics& g,
  30466. bool isMouseOverButton,
  30467. bool isButtonDown);
  30468. private:
  30469. ButtonStyle style;
  30470. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  30471. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  30472. Colour backgroundOff, backgroundOn;
  30473. int edgeIndent;
  30474. void deleteImages();
  30475. DrawableButton (const DrawableButton&);
  30476. const DrawableButton& operator= (const DrawableButton&);
  30477. };
  30478. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30479. /********* End of inlined file: juce_DrawableButton.h *********/
  30480. #endif
  30481. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30482. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30483. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30484. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30485. /**
  30486. A button showing an underlined weblink, that will launch the link
  30487. when it's clicked.
  30488. @see Button
  30489. */
  30490. class JUCE_API HyperlinkButton : public Button
  30491. {
  30492. public:
  30493. /** Creates a HyperlinkButton.
  30494. @param linkText the text that will be displayed in the button - this is
  30495. also set as the Component's name, but the text can be
  30496. changed later with the Button::getButtonText() method
  30497. @param linkURL the URL to launch when the user clicks the button
  30498. */
  30499. HyperlinkButton (const String& linkText,
  30500. const URL& linkURL);
  30501. /** Destructor. */
  30502. ~HyperlinkButton();
  30503. /** Changes the font to use for the text.
  30504. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30505. to match the size of the component.
  30506. */
  30507. void setFont (const Font& newFont,
  30508. const bool resizeToMatchComponentHeight,
  30509. const Justification& justificationType = Justification::horizontallyCentred);
  30510. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30511. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30512. methods.
  30513. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30514. */
  30515. enum ColourIds
  30516. {
  30517. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30518. };
  30519. /** Changes the URL that the button will trigger. */
  30520. void setURL (const URL& newURL) throw();
  30521. /** Returns the URL that the button will trigger. */
  30522. const URL& getURL() const throw() { return url; }
  30523. /** Resizes the button horizontally to fit snugly around the text.
  30524. This won't affect the button's height.
  30525. */
  30526. void changeWidthToFitText();
  30527. juce_UseDebuggingNewOperator
  30528. protected:
  30529. /** @internal */
  30530. void clicked();
  30531. /** @internal */
  30532. void colourChanged();
  30533. /** @internal */
  30534. void paintButton (Graphics& g,
  30535. bool isMouseOverButton,
  30536. bool isButtonDown);
  30537. private:
  30538. URL url;
  30539. Font font;
  30540. bool resizeFont;
  30541. Justification justification;
  30542. const Font getFontToUse() const;
  30543. HyperlinkButton (const HyperlinkButton&);
  30544. const HyperlinkButton& operator= (const HyperlinkButton&);
  30545. };
  30546. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30547. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30548. #endif
  30549. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30550. /********* Start of inlined file: juce_ImageButton.h *********/
  30551. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30552. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30553. /**
  30554. As the title suggests, this is a button containing an image.
  30555. The colour and transparency of the image can be set to vary when the
  30556. button state changes.
  30557. @see Button, ShapeButton, TextButton
  30558. */
  30559. class JUCE_API ImageButton : public Button
  30560. {
  30561. public:
  30562. /** Creates an ImageButton.
  30563. Use setImage() to specify the image to use. The colours and opacities that
  30564. are specified here can be changed later using setDrawingOptions().
  30565. @param name the name to give the component
  30566. */
  30567. ImageButton (const String& name);
  30568. /** Destructor. */
  30569. ~ImageButton();
  30570. /** Sets up the images to draw in various states.
  30571. Important! Bear in mind that if you pass the same image in for more than one of
  30572. these parameters, this button will delete it (or release from the ImageCache)
  30573. multiple times!
  30574. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30575. resized to the same dimensions as the normal image
  30576. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30577. button when the button's size changes
  30578. @param preserveImageProportions if true then any rescaling of the image to fit
  30579. the button will keep the image's x and y proportions
  30580. correct - i.e. it won't distort its shape, although
  30581. this might create gaps around the edges
  30582. @param normalImage the image to use when the button is in its normal state. The
  30583. image passed in will be deleted (or released if it
  30584. was created by the ImageCache class) when the
  30585. button no longer needs it.
  30586. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30587. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30588. normal image - if this colour is transparent, no overlay
  30589. will be drawn. The overlay will be drawn over the top of the
  30590. image, so you can basically add a solid or semi-transparent
  30591. colour to the image to brighten or darken it
  30592. @param overImage the image to use when the mouse is over the button. If
  30593. you want to use the same image as was set in the normalImage
  30594. parameter, this value can be 0. As for normalImage, it
  30595. will be deleted or released by the button when no longer
  30596. needed
  30597. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30598. is over the button
  30599. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30600. image when the mouse is over - if this colour is transparent,
  30601. no overlay will be drawn
  30602. @param downImage an image to use when the button is pressed down. If set
  30603. to zero, the 'over' image will be drawn instead (or the
  30604. normal image if there isn't an 'over' image either). This
  30605. image will be deleted or released by the button when no
  30606. longer needed
  30607. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30608. is pressed
  30609. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30610. image when the button is pressed down - if this colour is
  30611. transparent, no overlay will be drawn
  30612. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30613. whenever it's inside the button's bounding rectangle. If
  30614. set to values higher than 0, the mouse will only be
  30615. considered to be over the image when the value of the
  30616. image's alpha channel at that position is greater than
  30617. this level.
  30618. */
  30619. void setImages (const bool resizeButtonNowToFitThisImage,
  30620. const bool rescaleImagesWhenButtonSizeChanges,
  30621. const bool preserveImageProportions,
  30622. Image* const normalImage,
  30623. const float imageOpacityWhenNormal,
  30624. const Colour& overlayColourWhenNormal,
  30625. Image* const overImage,
  30626. const float imageOpacityWhenOver,
  30627. const Colour& overlayColourWhenOver,
  30628. Image* const downImage,
  30629. const float imageOpacityWhenDown,
  30630. const Colour& overlayColourWhenDown,
  30631. const float hitTestAlphaThreshold = 0.0f);
  30632. /** Returns the currently set 'normal' image. */
  30633. Image* getNormalImage() const throw();
  30634. /** Returns the image that's drawn when the mouse is over the button.
  30635. If an 'over' image has been set, this will return it; otherwise it'll
  30636. just return the normal image.
  30637. */
  30638. Image* getOverImage() const throw();
  30639. /** Returns the image that's drawn when the button is held down.
  30640. If a 'down' image has been set, this will return it; otherwise it'll
  30641. return the 'over' image or normal image, depending on what's available.
  30642. */
  30643. Image* getDownImage() const throw();
  30644. juce_UseDebuggingNewOperator
  30645. protected:
  30646. /** @internal */
  30647. bool hitTest (int x, int y);
  30648. /** @internal */
  30649. void paintButton (Graphics& g,
  30650. bool isMouseOverButton,
  30651. bool isButtonDown);
  30652. private:
  30653. bool scaleImageToFit, preserveProportions;
  30654. unsigned char alphaThreshold;
  30655. int imageX, imageY, imageW, imageH;
  30656. Image* normalImage;
  30657. Image* overImage;
  30658. Image* downImage;
  30659. float normalOpacity, overOpacity, downOpacity;
  30660. Colour normalOverlay, overOverlay, downOverlay;
  30661. Image* getCurrentImage() const;
  30662. void deleteImages();
  30663. ImageButton (const ImageButton&);
  30664. const ImageButton& operator= (const ImageButton&);
  30665. };
  30666. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30667. /********* End of inlined file: juce_ImageButton.h *********/
  30668. #endif
  30669. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30670. /********* Start of inlined file: juce_ShapeButton.h *********/
  30671. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30672. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30673. /**
  30674. A button that contains a filled shape.
  30675. @see Button, ImageButton, TextButton, ArrowButton
  30676. */
  30677. class JUCE_API ShapeButton : public Button
  30678. {
  30679. public:
  30680. /** Creates a ShapeButton.
  30681. @param name a name to give the component - see Component::setName()
  30682. @param normalColour the colour to fill the shape with when the mouse isn't over
  30683. @param overColour the colour to use when the mouse is over the shape
  30684. @param downColour the colour to use when the button is in the pressed-down state
  30685. */
  30686. ShapeButton (const String& name,
  30687. const Colour& normalColour,
  30688. const Colour& overColour,
  30689. const Colour& downColour);
  30690. /** Destructor. */
  30691. ~ShapeButton();
  30692. /** Sets the shape to use.
  30693. @param newShape the shape to use
  30694. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30695. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30696. the button is resized
  30697. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30698. */
  30699. void setShape (const Path& newShape,
  30700. const bool resizeNowToFitThisShape,
  30701. const bool maintainShapeProportions,
  30702. const bool hasDropShadow);
  30703. /** Set the colours to use for drawing the shape.
  30704. @param normalColour the colour to fill the shape with when the mouse isn't over
  30705. @param overColour the colour to use when the mouse is over the shape
  30706. @param downColour the colour to use when the button is in the pressed-down state
  30707. */
  30708. void setColours (const Colour& normalColour,
  30709. const Colour& overColour,
  30710. const Colour& downColour);
  30711. /** Sets up an outline to draw around the shape.
  30712. @param outlineColour the colour to use
  30713. @param outlineStrokeWidth the thickness of line to draw
  30714. */
  30715. void setOutline (const Colour& outlineColour,
  30716. const float outlineStrokeWidth);
  30717. juce_UseDebuggingNewOperator
  30718. protected:
  30719. /** @internal */
  30720. void paintButton (Graphics& g,
  30721. bool isMouseOverButton,
  30722. bool isButtonDown);
  30723. private:
  30724. Colour normalColour, overColour, downColour, outlineColour;
  30725. DropShadowEffect shadow;
  30726. Path shape;
  30727. bool maintainShapeProportions;
  30728. float outlineWidth;
  30729. ShapeButton (const ShapeButton&);
  30730. const ShapeButton& operator= (const ShapeButton&);
  30731. };
  30732. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  30733. /********* End of inlined file: juce_ShapeButton.h *********/
  30734. #endif
  30735. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30736. #endif
  30737. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30738. /********* Start of inlined file: juce_ToggleButton.h *********/
  30739. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30740. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30741. /**
  30742. A button that can be toggled on/off.
  30743. All buttons can be toggle buttons, but this lets you create one of the
  30744. standard ones which has a tick-box and a text label next to it.
  30745. @see Button, DrawableButton, TextButton
  30746. */
  30747. class JUCE_API ToggleButton : public Button
  30748. {
  30749. public:
  30750. /** Creates a ToggleButton.
  30751. @param buttonText the text to put in the button (the component's name is also
  30752. initially set to this string, but these can be changed later
  30753. using the setName() and setButtonText() methods)
  30754. */
  30755. ToggleButton (const String& buttonText);
  30756. /** Destructor. */
  30757. ~ToggleButton();
  30758. /** Resizes the button to fit neatly around its current text.
  30759. The button's height won't be affected, only its width.
  30760. */
  30761. void changeWidthToFitText();
  30762. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30763. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30764. methods.
  30765. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30766. */
  30767. enum ColourIds
  30768. {
  30769. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  30770. };
  30771. juce_UseDebuggingNewOperator
  30772. protected:
  30773. /** @internal */
  30774. void paintButton (Graphics& g,
  30775. bool isMouseOverButton,
  30776. bool isButtonDown);
  30777. /** @internal */
  30778. void colourChanged();
  30779. private:
  30780. ToggleButton (const ToggleButton&);
  30781. const ToggleButton& operator= (const ToggleButton&);
  30782. };
  30783. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30784. /********* End of inlined file: juce_ToggleButton.h *********/
  30785. #endif
  30786. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30787. /********* Start of inlined file: juce_ToolbarButton.h *********/
  30788. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30789. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30790. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  30791. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30792. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30793. /********* Start of inlined file: juce_Toolbar.h *********/
  30794. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  30795. #define __JUCE_TOOLBAR_JUCEHEADER__
  30796. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  30797. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30798. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30799. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  30800. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30801. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30802. /**
  30803. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  30804. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  30805. derive your component from this class, and make sure that it is somewhere inside a
  30806. DragAndDropContainer component.
  30807. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30808. the operating system onto your component, you don't need any of these classes: instead
  30809. see the FileDragAndDropTarget class.
  30810. @see DragAndDropContainer, FileDragAndDropTarget
  30811. */
  30812. class JUCE_API DragAndDropTarget
  30813. {
  30814. public:
  30815. /** Destructor. */
  30816. virtual ~DragAndDropTarget() {}
  30817. /** Callback to check whether this target is interested in the type of object being
  30818. dragged.
  30819. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30820. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30821. @returns true if this component wants to receive the other callbacks regarging this
  30822. type of object; if it returns false, no other callbacks will be made.
  30823. */
  30824. virtual bool isInterestedInDragSource (const String& sourceDescription,
  30825. Component* sourceComponent) = 0;
  30826. /** Callback to indicate that something is being dragged over this component.
  30827. This gets called when the user moves the mouse into this component while dragging
  30828. something.
  30829. Use this callback as a trigger to make your component repaint itself to give the
  30830. user feedback about whether the item can be dropped here or not.
  30831. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30832. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30833. @param x the mouse x position, relative to this component
  30834. @param y the mouse y position, relative to this component
  30835. @see itemDragExit
  30836. */
  30837. virtual void itemDragEnter (const String& sourceDescription,
  30838. Component* sourceComponent,
  30839. int x,
  30840. int y);
  30841. /** Callback to indicate that the user is dragging something over this component.
  30842. This gets called when the user moves the mouse over this component while dragging
  30843. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  30844. this lets you know what happens in-between.
  30845. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30846. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30847. @param x the mouse x position, relative to this component
  30848. @param y the mouse y position, relative to this component
  30849. */
  30850. virtual void itemDragMove (const String& sourceDescription,
  30851. Component* sourceComponent,
  30852. int x,
  30853. int y);
  30854. /** Callback to indicate that something has been dragged off the edge of this component.
  30855. This gets called when the user moves the mouse out of this component while dragging
  30856. something.
  30857. If you've used itemDragEnter() to repaint your component and give feedback, use this
  30858. as a signal to repaint it in its normal state.
  30859. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30860. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30861. @see itemDragEnter
  30862. */
  30863. virtual void itemDragExit (const String& sourceDescription,
  30864. Component* sourceComponent);
  30865. /** Callback to indicate that the user has dropped something onto this component.
  30866. When the user drops an item this get called, and you can use the description to
  30867. work out whether your object wants to deal with it or not.
  30868. Note that after this is called, the itemDragExit method may not be called, so you should
  30869. clean up in here if there's anything you need to do when the drag finishes.
  30870. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30871. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30872. @param x the mouse x position, relative to this component
  30873. @param y the mouse y position, relative to this component
  30874. */
  30875. virtual void itemDropped (const String& sourceDescription,
  30876. Component* sourceComponent,
  30877. int x,
  30878. int y) = 0;
  30879. /** Overriding this allows the target to tell the drag container whether to
  30880. draw the drag image while the cursor is over it.
  30881. By default it returns true, but if you return false, then the normal drag
  30882. image will not be shown when the cursor is over this target.
  30883. */
  30884. virtual bool shouldDrawDragImageWhenOver();
  30885. };
  30886. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30887. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  30888. /**
  30889. Enables drag-and-drop behaviour for a component and all its sub-components.
  30890. For a component to be able to make or receive drag-and-drop events, one of its parent
  30891. components must derive from this class. It's probably best for the top-level
  30892. component to implement it.
  30893. Then to start a drag operation, any sub-component can just call the startDragging()
  30894. method, and this object will take over, tracking the mouse and sending appropriate
  30895. callbacks to any child components derived from DragAndDropTarget which the mouse
  30896. moves over.
  30897. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30898. the operating system onto your component, you don't need any of these classes: you can do this
  30899. simply by overriding Component::filesDropped().
  30900. @see DragAndDropTarget
  30901. */
  30902. class JUCE_API DragAndDropContainer
  30903. {
  30904. public:
  30905. /** Creates a DragAndDropContainer.
  30906. The object that derives from this class must also be a Component.
  30907. */
  30908. DragAndDropContainer();
  30909. /** Destructor. */
  30910. virtual ~DragAndDropContainer();
  30911. /** Begins a drag-and-drop operation.
  30912. This starts a drag-and-drop operation - call it when the user drags the
  30913. mouse in your drag-source component, and this object will track mouse
  30914. movements until the user lets go of the mouse button, and will send
  30915. appropriate messages to DragAndDropTarget objects that the mouse moves
  30916. over.
  30917. findParentDragContainerFor() is a handy method to call to find the
  30918. drag container to use for a component.
  30919. @param sourceDescription a string to use as the description of the thing being
  30920. dragged - this will be passed to the objects that might be
  30921. dropped-onto so they can decide if they want to handle it or
  30922. not
  30923. @param sourceComponent the component that is being dragged
  30924. @param dragImage the image to drag around underneath the mouse. If this is
  30925. zero, a snapshot of the sourceComponent will be used instead. An
  30926. image passed-in will be deleted by this object when no longer
  30927. needed.
  30928. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  30929. window, and can be dragged to DragAndDropTargets that are the
  30930. children of components other than this one.
  30931. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  30932. at which the image should be drawn from the mouse. If it isn't
  30933. specified, then the image will be centred around the mouse. If
  30934. an image hasn't been passed-in, this will be ignored.
  30935. */
  30936. void startDragging (const String& sourceDescription,
  30937. Component* sourceComponent,
  30938. Image* dragImage = 0,
  30939. const bool allowDraggingToOtherJuceWindows = false,
  30940. const Point* imageOffsetFromMouse = 0);
  30941. /** Returns true if something is currently being dragged. */
  30942. bool isDragAndDropActive() const;
  30943. /** Returns the description of the thing that's currently being dragged.
  30944. If nothing's being dragged, this will return an empty string, otherwise it's the
  30945. string that was passed into startDragging().
  30946. @see startDragging
  30947. */
  30948. const String getCurrentDragDescription() const;
  30949. /** Utility to find the DragAndDropContainer for a given Component.
  30950. This will search up this component's parent hierarchy looking for the first
  30951. parent component which is a DragAndDropContainer.
  30952. It's useful when a component wants to call startDragging but doesn't know
  30953. the DragAndDropContainer it should to use.
  30954. Obviously this may return 0 if it doesn't find a suitable component.
  30955. */
  30956. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  30957. /** This performs a synchronous drag-and-drop of a set of files to some external
  30958. application.
  30959. You can call this function in response to a mouseDrag callback, and it will
  30960. block, running its own internal message loop and tracking the mouse, while it
  30961. uses a native operating system drag-and-drop operation to move or copy some
  30962. files to another application.
  30963. @param files a list of filenames to drag
  30964. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  30965. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  30966. @returns true if the files were successfully dropped somewhere, or false if it
  30967. was interrupted
  30968. @see performExternalDragDropOfText
  30969. */
  30970. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  30971. /** This performs a synchronous drag-and-drop of a block of text to some external
  30972. application.
  30973. You can call this function in response to a mouseDrag callback, and it will
  30974. block, running its own internal message loop and tracking the mouse, while it
  30975. uses a native operating system drag-and-drop operation to move or copy some
  30976. text to another application.
  30977. @param text the text to copy
  30978. @returns true if the text was successfully dropped somewhere, or false if it
  30979. was interrupted
  30980. @see performExternalDragDropOfFiles
  30981. */
  30982. static bool performExternalDragDropOfText (const String& text);
  30983. juce_UseDebuggingNewOperator
  30984. protected:
  30985. /** Override this if you want to be able to perform an external drag a set of files
  30986. when the user drags outside of this container component.
  30987. This method will be called when a drag operation moves outside the Juce-based window,
  30988. and if you want it to then perform a file drag-and-drop, add the filenames you want
  30989. to the array passed in, and return true.
  30990. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  30991. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  30992. @param files on return, the filenames you want to drag
  30993. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  30994. it must make a copy of them (see the performExternalDragDropOfFiles()
  30995. method)
  30996. @see performExternalDragDropOfFiles
  30997. */
  30998. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  30999. Component* dragSourceComponent,
  31000. StringArray& files,
  31001. bool& canMoveFiles);
  31002. private:
  31003. friend class DragImageComponent;
  31004. ScopedPointer <Component> dragImageComponent;
  31005. String currentDragDesc;
  31006. };
  31007. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31008. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31009. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31010. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31011. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31012. /**
  31013. Animates a set of components, moving it to a new position.
  31014. To use this, create a ComponentAnimator, and use its animateComponent() method
  31015. to tell it to move components to destination positions. Any number of
  31016. components can be animated by one ComponentAnimator object (if you've got a
  31017. lot of components to move, it's much more efficient to share a single animator
  31018. than to have many animators running at once).
  31019. You'll need to make sure the animator object isn't deleted before it finishes
  31020. moving the components.
  31021. The class is a ChangeBroadcaster and sends a notification when any components
  31022. start or finish being animated.
  31023. */
  31024. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  31025. private Timer
  31026. {
  31027. public:
  31028. /** Creates a ComponentAnimator. */
  31029. ComponentAnimator();
  31030. /** Destructor. */
  31031. ~ComponentAnimator();
  31032. /** Starts a component moving from its current position to a specified position.
  31033. If the component is already in the middle of an animation, that will be abandoned,
  31034. and a new animation will begin, moving the component from its current location.
  31035. The start and end speed parameters let you apply some acceleration to the component's
  31036. movement.
  31037. @param component the component to move
  31038. @param finalPosition the destination position and size to move it to
  31039. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31040. to arrive at its destination
  31041. @param startSpeed a value to indicate the relative start speed of the
  31042. animation. If this is 0, the component will start
  31043. by accelerating from rest; higher values mean that it
  31044. will have an initial speed greater than zero. If the
  31045. value if greater than 1, it will decelerate towards the
  31046. middle of its journey. To move the component at a constant
  31047. rate for its entire animation, set both the start and
  31048. end speeds to 1.0
  31049. @param endSpeed a relative speed at which the component should be moving
  31050. when the animation finishes. If this is 0, the component
  31051. will decelerate to a standstill at its final position; higher
  31052. values mean the component will still be moving when it stops.
  31053. To move the component at a constant rate for its entire
  31054. animation, set both the start and end speeds to 1.0
  31055. */
  31056. void animateComponent (Component* const component,
  31057. const Rectangle& finalPosition,
  31058. const int millisecondsToSpendMoving,
  31059. const double startSpeed = 1.0,
  31060. const double endSpeed = 1.0);
  31061. /** Stops a component if it's currently being animated.
  31062. If moveComponentToItsFinalPosition is true, then the component will
  31063. be immediately moved to its destination position and size. If false, it will be
  31064. left in whatever location it currently occupies.
  31065. */
  31066. void cancelAnimation (Component* const component,
  31067. const bool moveComponentToItsFinalPosition);
  31068. /** Clears all of the active animations.
  31069. If moveComponentsToTheirFinalPositions is true, all the components will
  31070. be immediately set to their final positions. If false, they will be
  31071. left in whatever locations they currently occupy.
  31072. */
  31073. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31074. /** Returns the destination position for a component.
  31075. If the component is being animated, this will return the target position that
  31076. was specified when animateComponent() was called.
  31077. If the specified component isn't currently being animated, this method will just
  31078. return its current position.
  31079. */
  31080. const Rectangle getComponentDestination (Component* const component);
  31081. /** Returns true if the specified component is currently being animated.
  31082. */
  31083. bool isAnimating (Component* component) const;
  31084. juce_UseDebuggingNewOperator
  31085. private:
  31086. VoidArray tasks;
  31087. uint32 lastTime;
  31088. void* findTaskFor (Component* const component) const;
  31089. void timerCallback();
  31090. };
  31091. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31092. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31093. class ToolbarItemComponent;
  31094. class ToolbarItemFactory;
  31095. class MissingItemsComponent;
  31096. /**
  31097. A toolbar component.
  31098. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31099. and looks after their order and layout.
  31100. Items (icon buttons or other custom components) are added to a toolbar using a
  31101. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31102. toolbar might contain more than one instance of a particular item type.
  31103. Toolbars can be interactively customised, allowing the user to drag the items
  31104. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31105. component as a source of new items.
  31106. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31107. */
  31108. class JUCE_API Toolbar : public Component,
  31109. public DragAndDropContainer,
  31110. public DragAndDropTarget,
  31111. private ButtonListener
  31112. {
  31113. public:
  31114. /** Creates an empty toolbar component.
  31115. To add some icons or other components to your toolbar, you'll need to
  31116. create a ToolbarItemFactory class that can create a suitable set of
  31117. ToolbarItemComponents.
  31118. @see ToolbarItemFactory, ToolbarItemComponents
  31119. */
  31120. Toolbar();
  31121. /** Destructor.
  31122. Any items on the bar will be deleted when the toolbar is deleted.
  31123. */
  31124. ~Toolbar();
  31125. /** Changes the bar's orientation.
  31126. @see isVertical
  31127. */
  31128. void setVertical (const bool shouldBeVertical);
  31129. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31130. You can change the bar's orientation with setVertical().
  31131. */
  31132. bool isVertical() const throw() { return vertical; }
  31133. /** Returns the depth of the bar.
  31134. If the bar is horizontal, this will return its height; if it's vertical, it
  31135. will return its width.
  31136. @see getLength
  31137. */
  31138. int getThickness() const throw();
  31139. /** Returns the length of the bar.
  31140. If the bar is horizontal, this will return its width; if it's vertical, it
  31141. will return its height.
  31142. @see getThickness
  31143. */
  31144. int getLength() const throw();
  31145. /** Deletes all items from the bar.
  31146. */
  31147. void clear();
  31148. /** Adds an item to the toolbar.
  31149. The factory's ToolbarItemFactory::createItem() will be called by this method
  31150. to create the component that will actually be added to the bar.
  31151. The new item will be inserted at the specified index (if the index is -1, it
  31152. will be added to the right-hand or bottom end of the bar).
  31153. Once added, the component will be automatically deleted by this object when it
  31154. is no longer needed.
  31155. @see ToolbarItemFactory
  31156. */
  31157. void addItem (ToolbarItemFactory& factory,
  31158. const int itemId,
  31159. const int insertIndex = -1);
  31160. /** Deletes one of the items from the bar.
  31161. */
  31162. void removeToolbarItem (const int itemIndex);
  31163. /** Returns the number of items currently on the toolbar.
  31164. @see getItemId, getItemComponent
  31165. */
  31166. int getNumItems() const throw();
  31167. /** Returns the ID of the item with the given index.
  31168. If the index is less than zero or greater than the number of items,
  31169. this will return 0.
  31170. @see getNumItems
  31171. */
  31172. int getItemId (const int itemIndex) const throw();
  31173. /** Returns the component being used for the item with the given index.
  31174. If the index is less than zero or greater than the number of items,
  31175. this will return 0.
  31176. @see getNumItems
  31177. */
  31178. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31179. /** Clears this toolbar and adds to it the default set of items that the specified
  31180. factory creates.
  31181. @see ToolbarItemFactory::getDefaultItemSet
  31182. */
  31183. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31184. /** Options for the way items should be displayed.
  31185. @see setStyle, getStyle
  31186. */
  31187. enum ToolbarItemStyle
  31188. {
  31189. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31190. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31191. textOnly /**< Means that the toolbar only display text labels for each item. */
  31192. };
  31193. /** Returns the toolbar's current style.
  31194. @see ToolbarItemStyle, setStyle
  31195. */
  31196. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31197. /** Changes the toolbar's current style.
  31198. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31199. */
  31200. void setStyle (const ToolbarItemStyle& newStyle);
  31201. /** Flags used by the showCustomisationDialog() method. */
  31202. enum CustomisationFlags
  31203. {
  31204. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31205. show the "icons only" option on its choice of toolbar styles. */
  31206. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31207. show the "icons with text" option on its choice of toolbar styles. */
  31208. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31209. show the "text only" option on its choice of toolbar styles. */
  31210. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31211. show a button to reset the toolbar to its default set of items. */
  31212. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31213. };
  31214. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31215. The dialog contains a ToolbarItemPalette and various controls for editing other
  31216. aspects of the toolbar. This method will block and run the dialog box modally,
  31217. returning when the user closes it.
  31218. The factory is used to determine the set of items that will be shown on the
  31219. palette.
  31220. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31221. enum.
  31222. @see ToolbarItemPalette
  31223. */
  31224. void showCustomisationDialog (ToolbarItemFactory& factory,
  31225. const int optionFlags = allCustomisationOptionsEnabled);
  31226. /** Turns on or off the toolbar's editing mode, in which its items can be
  31227. rearranged by the user.
  31228. (In most cases it's easier just to use showCustomisationDialog() instead of
  31229. trying to enable editing directly).
  31230. @see ToolbarItemPalette
  31231. */
  31232. void setEditingActive (const bool editingEnabled);
  31233. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31234. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31235. methods.
  31236. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31237. */
  31238. enum ColourIds
  31239. {
  31240. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31241. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31242. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31243. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31244. over them. */
  31245. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31246. held down on them. */
  31247. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31248. when the style is set to iconsWithText or textOnly. */
  31249. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31250. the customisation dialog is active and the mouse moves over them. */
  31251. };
  31252. /** Returns a string that represents the toolbar's current set of items.
  31253. This lets you later restore the same item layout using restoreFromString().
  31254. @see restoreFromString
  31255. */
  31256. const String toString() const;
  31257. /** Restores a set of items that was previously stored in a string by the toString()
  31258. method.
  31259. The factory object is used to create any item components that are needed.
  31260. @see toString
  31261. */
  31262. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31263. const String& savedVersion);
  31264. /** @internal */
  31265. void paint (Graphics& g);
  31266. /** @internal */
  31267. void resized();
  31268. /** @internal */
  31269. void buttonClicked (Button*);
  31270. /** @internal */
  31271. void mouseDown (const MouseEvent&);
  31272. /** @internal */
  31273. bool isInterestedInDragSource (const String&, Component*);
  31274. /** @internal */
  31275. void itemDragMove (const String&, Component*, int, int);
  31276. /** @internal */
  31277. void itemDragExit (const String&, Component*);
  31278. /** @internal */
  31279. void itemDropped (const String&, Component*, int, int);
  31280. /** @internal */
  31281. void updateAllItemPositions (const bool animate);
  31282. /** @internal */
  31283. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31284. juce_UseDebuggingNewOperator
  31285. private:
  31286. Button* missingItemsButton;
  31287. bool vertical, isEditingActive;
  31288. ToolbarItemStyle toolbarStyle;
  31289. ComponentAnimator animator;
  31290. friend class MissingItemsComponent;
  31291. Array <ToolbarItemComponent*> items;
  31292. friend class ItemDragAndDropOverlayComponent;
  31293. static const tchar* const toolbarDragDescriptor;
  31294. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31295. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31296. Toolbar (const Toolbar&);
  31297. const Toolbar& operator= (const Toolbar&);
  31298. };
  31299. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31300. /********* End of inlined file: juce_Toolbar.h *********/
  31301. class ItemDragAndDropOverlayComponent;
  31302. /**
  31303. A component that can be used as one of the items in a Toolbar.
  31304. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31305. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31306. class for further info about creating them.
  31307. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31308. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31309. calling the constructor, and override contentAreaChanged(), in which you can position
  31310. any sub-components you need to add.
  31311. To add basic buttons without writing a special subclass, have a look at the
  31312. ToolbarButton class.
  31313. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31314. */
  31315. class JUCE_API ToolbarItemComponent : public Button
  31316. {
  31317. public:
  31318. /** Constructor.
  31319. @param itemId the ID of the type of toolbar item which this represents
  31320. @param labelText the text to display if the toolbar's style is set to
  31321. Toolbar::iconsWithText or Toolbar::textOnly
  31322. @param isBeingUsedAsAButton set this to false if you don't want the button
  31323. to draw itself with button over/down states when the mouse
  31324. moves over it or clicks
  31325. */
  31326. ToolbarItemComponent (const int itemId,
  31327. const String& labelText,
  31328. const bool isBeingUsedAsAButton);
  31329. /** Destructor. */
  31330. ~ToolbarItemComponent();
  31331. /** Returns the item type ID that this component represents.
  31332. This value is in the constructor.
  31333. */
  31334. int getItemId() const throw() { return itemId; }
  31335. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31336. inside one.
  31337. */
  31338. Toolbar* getToolbar() const;
  31339. /** Returns true if this component is currently inside a toolbar which is vertical.
  31340. @see Toolbar::isVertical
  31341. */
  31342. bool isToolbarVertical() const;
  31343. /** Returns the current style setting of this item.
  31344. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31345. @see setStyle, Toolbar::getStyle
  31346. */
  31347. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31348. /** Changes the current style setting of this item.
  31349. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31350. by the toolbar that holds this item.
  31351. @see setStyle, Toolbar::setStyle
  31352. */
  31353. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31354. /** Returns the area of the component that should be used to display the button image or
  31355. other contents of the item.
  31356. This content area may change when the item's style changes, and may leave a space around the
  31357. edge of the component where the text label can be shown.
  31358. @see contentAreaChanged
  31359. */
  31360. const Rectangle getContentArea() const throw() { return contentArea; }
  31361. /** This method must return the size criteria for this item, based on a given toolbar
  31362. size and orientation.
  31363. The preferredSize, minSize and maxSize values must all be set by your implementation
  31364. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31365. toolbar, they refer to the item's height.
  31366. The preferredSize is the size that the component would like to be, and this must be
  31367. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31368. the same value.
  31369. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31370. Toolbar::getThickness().
  31371. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31372. vertically.
  31373. */
  31374. virtual bool getToolbarItemSizes (int toolbarThickness,
  31375. bool isToolbarVertical,
  31376. int& preferredSize,
  31377. int& minSize,
  31378. int& maxSize) = 0;
  31379. /** Your subclass should use this method to draw its content area.
  31380. The graphics object that is passed-in will have been clipped and had its origin
  31381. moved to fit the content area as specified get getContentArea(). The width and height
  31382. parameters are the width and height of the content area.
  31383. If the component you're writing isn't a button, you can just do nothing in this method.
  31384. */
  31385. virtual void paintButtonArea (Graphics& g,
  31386. int width, int height,
  31387. bool isMouseOver, bool isMouseDown) = 0;
  31388. /** Callback to indicate that the content area of this item has changed.
  31389. This might be because the component was resized, or because the style changed and
  31390. the space needed for the text label is different.
  31391. See getContentArea() for a description of what the area is.
  31392. */
  31393. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31394. /** Editing modes.
  31395. These are used by setEditingMode(), but will be rarely needed in user code.
  31396. */
  31397. enum ToolbarEditingMode
  31398. {
  31399. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31400. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31401. customisation mode, and the items can be dragged around. */
  31402. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31403. dragged onto a toolbar to add it to that bar.*/
  31404. };
  31405. /** Changes the editing mode of this component.
  31406. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31407. and is unlikely to be of much use in end-user-code.
  31408. */
  31409. void setEditingMode (const ToolbarEditingMode newMode);
  31410. /** Returns the current editing mode of this component.
  31411. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31412. and is unlikely to be of much use in end-user-code.
  31413. */
  31414. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31415. /** @internal */
  31416. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31417. /** @internal */
  31418. void resized();
  31419. juce_UseDebuggingNewOperator
  31420. private:
  31421. friend class Toolbar;
  31422. friend class ItemDragAndDropOverlayComponent;
  31423. const int itemId;
  31424. ToolbarEditingMode mode;
  31425. Toolbar::ToolbarItemStyle toolbarStyle;
  31426. ScopedPointer <Component> overlayComp;
  31427. int dragOffsetX, dragOffsetY;
  31428. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31429. Rectangle contentArea;
  31430. ToolbarItemComponent (const ToolbarItemComponent&);
  31431. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31432. };
  31433. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31434. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31435. /**
  31436. A type of button designed to go on a toolbar.
  31437. This simple button can have two Drawable objects specified - one for normal
  31438. use and another one (optionally) for the button's "on" state if it's a
  31439. toggle button.
  31440. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31441. */
  31442. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31443. {
  31444. public:
  31445. /** Creates a ToolbarButton.
  31446. @param itemId the ID for this toolbar item type. This is passed through to the
  31447. ToolbarItemComponent constructor
  31448. @param labelText the text to display on the button (if the toolbar is using a style
  31449. that shows text labels). This is passed through to the
  31450. ToolbarItemComponent constructor
  31451. @param normalImage a drawable object that the button should use as its icon. The object
  31452. that is passed-in here will be kept by this object and will be
  31453. deleted when no longer needed or when this button is deleted.
  31454. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31455. is in a toggled-on state (see the Button::getToggleState() method). If
  31456. 0 is passed-in here, then the normal image will be used instead, regardless
  31457. of the toggle state. The object that is passed-in here will be kept by
  31458. this object and will be deleted when no longer needed or when this button
  31459. is deleted.
  31460. */
  31461. ToolbarButton (const int itemId,
  31462. const String& labelText,
  31463. Drawable* const normalImage,
  31464. Drawable* const toggledOnImage);
  31465. /** Destructor. */
  31466. ~ToolbarButton();
  31467. /** @internal */
  31468. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31469. int& minSize, int& maxSize);
  31470. /** @internal */
  31471. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31472. /** @internal */
  31473. void contentAreaChanged (const Rectangle& newBounds);
  31474. juce_UseDebuggingNewOperator
  31475. private:
  31476. ScopedPointer <Drawable> normalImage, toggledOnImage;
  31477. ToolbarButton (const ToolbarButton&);
  31478. const ToolbarButton& operator= (const ToolbarButton&);
  31479. };
  31480. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31481. /********* End of inlined file: juce_ToolbarButton.h *********/
  31482. #endif
  31483. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  31484. /********* Start of inlined file: juce_CodeDocument.h *********/
  31485. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  31486. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  31487. class CodeDocumentLine;
  31488. /**
  31489. A class for storing and manipulating a source code file.
  31490. When using a CodeEditorComponent, it takes one of these as its source object.
  31491. The CodeDocument stores its content as an array of lines, which makes it
  31492. quick to insert and delete.
  31493. @see CodeEditorComponent
  31494. */
  31495. class JUCE_API CodeDocument
  31496. {
  31497. public:
  31498. /** Creates a new, empty document.
  31499. */
  31500. CodeDocument();
  31501. /** Destructor. */
  31502. ~CodeDocument();
  31503. /** A position in a code document.
  31504. Using this class you can find a position in a code document and quickly get its
  31505. character position, line, and index. By calling setPositionMaintained (true), the
  31506. position is automatically updated when text is inserted or deleted in the document,
  31507. so that it maintains its original place in the text.
  31508. */
  31509. class JUCE_API Position
  31510. {
  31511. public:
  31512. /** Creates an uninitialised postion.
  31513. Don't attempt to call any methods on this until you've given it an owner document
  31514. to refer to!
  31515. */
  31516. Position() throw();
  31517. /** Creates a position based on a line and index in a document.
  31518. Note that this index is NOT the column number, it's the number of characters from the
  31519. start of the line. The "column" number isn't quite the same, because if the line
  31520. contains any tab characters, the relationship of the index to its visual column depends on
  31521. the number of spaces per tab being used!
  31522. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  31523. they will be adjusted to keep them within its limits.
  31524. */
  31525. Position (const CodeDocument* const ownerDocument,
  31526. const int line, const int indexInLine) throw();
  31527. /** Creates a position based on a character index in a document.
  31528. This position is placed at the specified number of characters from the start of the
  31529. document. The line and column are auto-calculated.
  31530. If the position is beyond the range of the document, it'll be adjusted to keep it
  31531. inside.
  31532. */
  31533. Position (const CodeDocument* const ownerDocument,
  31534. const int charactersFromStartOfDocument) throw();
  31535. /** Creates a copy of another position.
  31536. This will copy the position, but the new object will not be set to maintain its position,
  31537. even if the source object was set to do so.
  31538. */
  31539. Position (const Position& other) throw();
  31540. /** Destructor. */
  31541. ~Position() throw();
  31542. const Position& operator= (const Position& other) throw();
  31543. bool operator== (const Position& other) const throw();
  31544. bool operator!= (const Position& other) const throw();
  31545. /** Points this object at a new position within the document.
  31546. If the position is beyond the range of the document, it'll be adjusted to keep it
  31547. inside.
  31548. @see getPosition, setLineAndIndex
  31549. */
  31550. void setPosition (const int charactersFromStartOfDocument) throw();
  31551. /** Returns the position as the number of characters from the start of the document.
  31552. @see setPosition, getLineNumber, getIndexInLine
  31553. */
  31554. int getPosition() const throw() { return characterPos; }
  31555. /** Moves the position to a new line and index within the line.
  31556. Note that the index is NOT the column at which the position appears in an editor.
  31557. If the line contains any tab characters, the relationship of the index to its
  31558. visual position depends on the number of spaces per tab being used!
  31559. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  31560. they will be adjusted to keep them within its limits.
  31561. */
  31562. void setLineAndIndex (const int newLine, const int newIndexInLine) throw();
  31563. /** Returns the line number of this position.
  31564. The first line in the document is numbered zero, not one!
  31565. */
  31566. int getLineNumber() const throw() { return line; }
  31567. /** Returns the number of characters from the start of the line.
  31568. Note that this value is NOT the column at which the position appears in an editor.
  31569. If the line contains any tab characters, the relationship of the index to its
  31570. visual position depends on the number of spaces per tab being used!
  31571. */
  31572. int getIndexInLine() const throw() { return indexInLine; }
  31573. /** Allows the position to be automatically updated when the document changes.
  31574. If this is set to true, the positon will register with its document so that
  31575. when the document has text inserted or deleted, this position will be automatically
  31576. moved to keep it at the same position in the text.
  31577. */
  31578. void setPositionMaintained (const bool isMaintained) throw();
  31579. /** Moves the position forwards or backwards by the specified number of characters.
  31580. @see movedBy
  31581. */
  31582. void moveBy (int characterDelta) throw();
  31583. /** Returns a position which is the same as this one, moved by the specified number of
  31584. characters.
  31585. @see moveBy
  31586. */
  31587. const Position movedBy (const int characterDelta) const throw();
  31588. /** Returns a position which is the same as this one, moved up or down by the specified
  31589. number of lines.
  31590. @see movedBy
  31591. */
  31592. const Position movedByLines (const int deltaLines) const throw();
  31593. /** Returns the character in the document at this position.
  31594. @see getLineText
  31595. */
  31596. const tchar getCharacter() const throw();
  31597. /** Returns the line from the document that this position is within.
  31598. @see getCharacter, getLineNumber
  31599. */
  31600. const String getLineText() const throw();
  31601. private:
  31602. CodeDocument* owner;
  31603. int characterPos, line, indexInLine;
  31604. bool positionMaintained;
  31605. };
  31606. /** Returns the full text of the document. */
  31607. const String getAllContent() const throw();
  31608. /** Returns a section of the document's text. */
  31609. const String getTextBetween (const Position& start, const Position& end) const throw();
  31610. /** Returns a line from the document. */
  31611. const String getLine (const int lineIndex) const throw();
  31612. /** Returns the number of characters in the document. */
  31613. int getNumCharacters() const throw();
  31614. /** Returns the number of lines in the document. */
  31615. int getNumLines() const throw() { return lines.size(); }
  31616. /** Returns the number of characters in the longest line of the document. */
  31617. int getMaximumLineLength() throw();
  31618. /** Deletes a section of the text.
  31619. This operation is undoable.
  31620. */
  31621. void deleteSection (const Position& startPosition, const Position& endPosition);
  31622. /** Inserts some text into the document at a given position.
  31623. This operation is undoable.
  31624. */
  31625. void insertText (const Position& position, const String& text);
  31626. /** Clears the document and replaces it with some new text.
  31627. This operation is undoable - if you're trying to completely reset the document, you
  31628. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  31629. */
  31630. void replaceAllContent (const String& newContent);
  31631. /** Returns the preferred new-line characters for the document.
  31632. This will be either "\n", "\r\n", or (rarely) "\r".
  31633. @see setNewLineCharacters
  31634. */
  31635. const String getNewLineCharacters() const throw() { return newLineChars; }
  31636. /** Sets the new-line characters that the document should use.
  31637. The string must be either "\n", "\r\n", or (rarely) "\r".
  31638. @see getNewLineCharacters
  31639. */
  31640. void setNewLineCharacters (const String& newLine) throw();
  31641. /** Begins a new undo transaction.
  31642. The document itself will not call this internally, so relies on whatever is using the
  31643. document to periodically call this to break up the undo sequence into sensible chunks.
  31644. @see UndoManager::beginNewTransaction
  31645. */
  31646. void newTransaction();
  31647. /** Undo the last operation.
  31648. @see UndoManager::undo
  31649. */
  31650. void undo();
  31651. /** Redo the last operation.
  31652. @see UndoManager::redo
  31653. */
  31654. void redo();
  31655. /** Clears the undo history.
  31656. @see UndoManager::clearUndoHistory
  31657. */
  31658. void clearUndoHistory();
  31659. /** Returns the document's UndoManager */
  31660. UndoManager& getUndoManager() throw() { return undoManager; }
  31661. /** Makes a note that the document's current state matches the one that is saved.
  31662. After this has been called, hasChangedSinceSavePoint() will return false until
  31663. the document has been altered, and then it'll start returning true. If the document is
  31664. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  31665. will again return false.
  31666. @see hasChangedSinceSavePoint
  31667. */
  31668. void setSavePoint() throw();
  31669. /** Returns true if the state of the document differs from the state it was in when
  31670. setSavePoint() was last called.
  31671. @see setSavePoint
  31672. */
  31673. bool hasChangedSinceSavePoint() const throw();
  31674. /** Searches for a word-break. */
  31675. const Position findWordBreakAfter (const Position& position) const throw();
  31676. /** Searches for a word-break. */
  31677. const Position findWordBreakBefore (const Position& position) const throw();
  31678. /** An object that receives callbacks from the CodeDocument when its text changes.
  31679. @see CodeDocument::addListener, CodeDocument::removeListener
  31680. */
  31681. class JUCE_API Listener
  31682. {
  31683. public:
  31684. Listener() {}
  31685. virtual ~Listener() {}
  31686. /** Called by a CodeDocument when it is altered.
  31687. */
  31688. virtual void codeDocumentChanged (const Position& affectedTextStart,
  31689. const Position& affectedTextEnd) = 0;
  31690. };
  31691. /** Registers a listener object to receive callbacks when the document changes.
  31692. If the listener is already registered, this method has no effect.
  31693. @see removeListener
  31694. */
  31695. void addListener (Listener* const listener) throw();
  31696. /** Deregisters a listener.
  31697. @see addListener
  31698. */
  31699. void removeListener (Listener* const listener) throw();
  31700. /** Iterates the text in a CodeDocument.
  31701. This class lets you read characters from a CodeDocument. It's designed to be used
  31702. by a SyntaxAnalyser object.
  31703. @see CodeDocument, SyntaxAnalyser
  31704. */
  31705. class Iterator
  31706. {
  31707. public:
  31708. Iterator (CodeDocument* const document) throw();
  31709. Iterator (const Iterator& other);
  31710. const Iterator& operator= (const Iterator& other) throw();
  31711. ~Iterator() throw();
  31712. /** Reads the next character and returns it.
  31713. @see peekNextChar
  31714. */
  31715. juce_wchar nextChar() throw();
  31716. /** Reads the next character without advancing the current position. */
  31717. juce_wchar peekNextChar() const throw();
  31718. /** Advances the position by one character. */
  31719. void skip() throw();
  31720. /** Returns the position of the next character as its position within the
  31721. whole document.
  31722. */
  31723. int getPosition() const throw() { return position; }
  31724. /** Skips over any whitespace characters until the next character is non-whitespace. */
  31725. void skipWhitespace();
  31726. /** Skips forward until the next character will be the first character on the next line */
  31727. void skipToEndOfLine();
  31728. /** Returns the line number of the next character. */
  31729. int getLine() const throw() { return line; }
  31730. /** Returns true if the iterator has reached the end of the document. */
  31731. bool isEOF() const throw();
  31732. private:
  31733. CodeDocument* document;
  31734. int line, position;
  31735. };
  31736. juce_UseDebuggingNewOperator
  31737. private:
  31738. friend class CodeDocumentInsertAction;
  31739. friend class CodeDocumentDeleteAction;
  31740. friend class Iterator;
  31741. friend class Position;
  31742. OwnedArray <CodeDocumentLine> lines;
  31743. Array <Position*> positionsToMaintain;
  31744. UndoManager undoManager;
  31745. int currentActionIndex, indexOfSavedState;
  31746. int maximumLineLength;
  31747. VoidArray listeners;
  31748. String newLineChars;
  31749. void sendListenerChangeMessage (const int startLine, const int endLine);
  31750. void insert (const String& text, const int insertPos, const bool undoable);
  31751. void remove (const int startPos, const int endPos, const bool undoable);
  31752. CodeDocument (const CodeDocument&);
  31753. const CodeDocument& operator= (const CodeDocument&);
  31754. };
  31755. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  31756. /********* End of inlined file: juce_CodeDocument.h *********/
  31757. #endif
  31758. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31759. /********* Start of inlined file: juce_CodeEditorComponent.h *********/
  31760. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31761. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31762. /********* Start of inlined file: juce_CodeTokeniser.h *********/
  31763. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  31764. #define __JUCE_CODETOKENISER_JUCEHEADER__
  31765. /**
  31766. A base class for tokenising code so that the syntax can be displayed in a
  31767. code editor.
  31768. @see CodeDocument, CodeEditorComponent
  31769. */
  31770. class JUCE_API CodeTokeniser
  31771. {
  31772. public:
  31773. CodeTokeniser() {}
  31774. virtual ~CodeTokeniser() {}
  31775. /** Reads the next token from the source and returns its token type.
  31776. This must leave the source pointing to the first character in the
  31777. next token.
  31778. */
  31779. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  31780. /** Returns a list of the names of the token types this analyser uses.
  31781. The index in this list must match the token type numbers that are
  31782. returned by readNextToken().
  31783. */
  31784. virtual const StringArray getTokenTypes() = 0;
  31785. /** Returns a suggested syntax highlighting colour for a specified
  31786. token type.
  31787. */
  31788. virtual const Colour getDefaultColour (const int tokenType) = 0;
  31789. juce_UseDebuggingNewOperator
  31790. };
  31791. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  31792. /********* End of inlined file: juce_CodeTokeniser.h *********/
  31793. class CodeEditorLine;
  31794. /**
  31795. A text editor component designed specifically for source code.
  31796. This is designed to handle syntax highlighting and fast editing of very large
  31797. files.
  31798. */
  31799. class JUCE_API CodeEditorComponent : public Component,
  31800. public Timer,
  31801. public ScrollBarListener,
  31802. public CodeDocument::Listener,
  31803. public AsyncUpdater
  31804. {
  31805. public:
  31806. /** Creates an editor for a document.
  31807. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  31808. The object that you pass in is not owned or deleted by the editor - you must
  31809. make sure that it doesn't get deleted while this component is still using it.
  31810. @see CodeDocument
  31811. */
  31812. CodeEditorComponent (CodeDocument& document,
  31813. CodeTokeniser* const codeTokeniser);
  31814. /** Destructor. */
  31815. ~CodeEditorComponent();
  31816. /** Returns the code document that this component is editing. */
  31817. CodeDocument& getDocument() const throw() { return document; }
  31818. /** Loads the given content into the document.
  31819. This will completely reset the CodeDocument object, clear its undo history,
  31820. and fill it with this text.
  31821. */
  31822. void loadContent (const String& newContent);
  31823. /** Returns the standard character width. */
  31824. float getCharWidth() const throw() { return charWidth; }
  31825. /** Returns the height of a line of text, in pixels. */
  31826. int getLineHeight() const throw() { return lineHeight; }
  31827. /** Returns the number of whole lines visible on the screen,
  31828. This doesn't include a cut-off line that might be visible at the bottom if the
  31829. component's height isn't an exact multiple of the line-height.
  31830. */
  31831. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  31832. /** Returns the number of whole columns visible on the screen.
  31833. This doesn't include any cut-off columns at the right-hand edge.
  31834. */
  31835. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  31836. /** Returns the current caret position. */
  31837. const CodeDocument::Position getCaretPos() const { return caretPos; }
  31838. /** Moves the caret.
  31839. If selecting is true, the section of the document between the current
  31840. caret position and the new one will become selected. If false, any currently
  31841. selected region will be deselected.
  31842. */
  31843. void moveCaretTo (const CodeDocument::Position& newPos, const bool selecting);
  31844. /** Returns the on-screen position of a character in the document.
  31845. The rectangle returned is relative to this component's top-left origin.
  31846. */
  31847. const Rectangle getCharacterBounds (const CodeDocument::Position& pos) const throw();
  31848. /** Finds the character at a given on-screen position.
  31849. The co-ordinates are relative to this component's top-left origin.
  31850. */
  31851. const CodeDocument::Position getPositionAt (int x, int y);
  31852. void cursorLeft (const bool moveInWholeWordSteps, const bool selecting);
  31853. void cursorRight (const bool moveInWholeWordSteps, const bool selecting);
  31854. void cursorDown (const bool selecting);
  31855. void cursorUp (const bool selecting);
  31856. void pageDown (const bool selecting);
  31857. void pageUp (const bool selecting);
  31858. void scrollDown();
  31859. void scrollUp();
  31860. void scrollToLine (int newFirstLineOnScreen);
  31861. void scrollBy (int deltaLines);
  31862. void scrollToColumn (int newFirstColumnOnScreen);
  31863. void scrollToKeepCaretOnScreen();
  31864. void goToStartOfDocument (const bool selecting);
  31865. void goToStartOfLine (const bool selecting);
  31866. void goToEndOfDocument (const bool selecting);
  31867. void goToEndOfLine (const bool selecting);
  31868. void deselectAll();
  31869. void selectAll();
  31870. void insertTextAtCaret (const String& textToInsert);
  31871. void insertTabAtCaret();
  31872. void cut();
  31873. void copy();
  31874. void copyThenCut();
  31875. void paste();
  31876. void backspace (const bool moveInWholeWordSteps);
  31877. void deleteForward (const bool moveInWholeWordSteps);
  31878. void undo();
  31879. void redo();
  31880. /** Changes the current tab settings.
  31881. This lets you change the tab size and whether pressing the tab key inserts a
  31882. tab character, or its equivalent number of spaces.
  31883. */
  31884. void setTabSize (const int numSpacesPerTab,
  31885. const bool insertSpacesInsteadOfTabCharacters) throw();
  31886. /** Returns the current number of spaces per tab.
  31887. @see setTabSize
  31888. */
  31889. int getTabSize() const throw() { return spacesPerTab; }
  31890. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  31891. @see setTabSize
  31892. */
  31893. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  31894. /** Changes the font.
  31895. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  31896. */
  31897. void setFont (const Font& newFont);
  31898. /** Resets the syntax highlighting colours to the default ones provided by the
  31899. code tokeniser.
  31900. @see CodeTokeniser::getDefaultColour
  31901. */
  31902. void resetToDefaultColours();
  31903. /** Changes one of the syntax highlighting colours.
  31904. The token type values are dependent on the tokeniser being used - use
  31905. CodeTokeniser::getTokenTypes() to get a list of the token types.
  31906. @see getColourForTokenType
  31907. */
  31908. void setColourForTokenType (const int tokenType, const Colour& colour);
  31909. /** Returns one of the syntax highlighting colours.
  31910. The token type values are dependent on the tokeniser being used - use
  31911. CodeTokeniser::getTokenTypes() to get a list of the token types.
  31912. @see setColourForTokenType
  31913. */
  31914. const Colour getColourForTokenType (const int tokenType) const throw();
  31915. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  31916. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31917. methods.
  31918. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31919. */
  31920. enum ColourIds
  31921. {
  31922. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  31923. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  31924. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  31925. selected text. */
  31926. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  31927. enabled. */
  31928. };
  31929. /** Changes the size of the scrollbars. */
  31930. void setScrollbarThickness (const int thickness) throw();
  31931. /** @internal */
  31932. void resized();
  31933. /** @internal */
  31934. void paint (Graphics& g);
  31935. /** @internal */
  31936. bool keyPressed (const KeyPress& key);
  31937. /** @internal */
  31938. void mouseDown (const MouseEvent& e);
  31939. /** @internal */
  31940. void mouseDrag (const MouseEvent& e);
  31941. /** @internal */
  31942. void mouseUp (const MouseEvent& e);
  31943. /** @internal */
  31944. void mouseDoubleClick (const MouseEvent& e);
  31945. /** @internal */
  31946. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31947. /** @internal */
  31948. void timerCallback();
  31949. /** @internal */
  31950. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  31951. /** @internal */
  31952. void handleAsyncUpdate();
  31953. /** @internal */
  31954. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  31955. const CodeDocument::Position& affectedTextEnd);
  31956. juce_UseDebuggingNewOperator
  31957. private:
  31958. CodeDocument& document;
  31959. Font font;
  31960. int firstLineOnScreen, gutter, spacesPerTab;
  31961. float charWidth;
  31962. int lineHeight, linesOnScreen, columnsOnScreen;
  31963. int scrollbarThickness;
  31964. bool useSpacesForTabs;
  31965. double xOffset;
  31966. CodeDocument::Position caretPos;
  31967. CodeDocument::Position selectionStart, selectionEnd;
  31968. Component* caret;
  31969. ScrollBar* verticalScrollBar;
  31970. ScrollBar* horizontalScrollBar;
  31971. enum DragType
  31972. {
  31973. notDragging,
  31974. draggingSelectionStart,
  31975. draggingSelectionEnd
  31976. };
  31977. DragType dragType;
  31978. CodeTokeniser* codeTokeniser;
  31979. Array <Colour> coloursForTokenCategories;
  31980. OwnedArray <CodeEditorLine> lines;
  31981. void rebuildLineTokens();
  31982. OwnedArray <CodeDocument::Iterator> cachedIterators;
  31983. void clearCachedIterators (const int firstLineToBeInvalid) throw();
  31984. void updateCachedIterators (int maxLineNum);
  31985. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  31986. void updateScrollBars();
  31987. void scrollToLineInternal (int line);
  31988. void scrollToColumnInternal (double column);
  31989. void newTransaction();
  31990. int indexToColumn (int line, int index) const throw();
  31991. int columnToIndex (int line, int column) const throw();
  31992. CodeEditorComponent (const CodeEditorComponent&);
  31993. const CodeEditorComponent& operator= (const CodeEditorComponent&);
  31994. };
  31995. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31996. /********* End of inlined file: juce_CodeEditorComponent.h *********/
  31997. #endif
  31998. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  31999. #endif
  32000. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  32001. /********* Start of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  32002. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  32003. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  32004. /**
  32005. A simple lexical analyser for syntax colouring of C++ code.
  32006. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  32007. */
  32008. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  32009. {
  32010. public:
  32011. CPlusPlusCodeTokeniser();
  32012. ~CPlusPlusCodeTokeniser();
  32013. enum TokenType
  32014. {
  32015. tokenType_error = 0,
  32016. tokenType_comment,
  32017. tokenType_builtInKeyword,
  32018. tokenType_identifier,
  32019. tokenType_integerLiteral,
  32020. tokenType_floatLiteral,
  32021. tokenType_stringLiteral,
  32022. tokenType_operator,
  32023. tokenType_bracket,
  32024. tokenType_punctuation,
  32025. tokenType_preprocessor
  32026. };
  32027. int readNextToken (CodeDocument::Iterator& source);
  32028. const StringArray getTokenTypes();
  32029. const Colour getDefaultColour (const int tokenType);
  32030. juce_UseDebuggingNewOperator
  32031. };
  32032. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  32033. /********* End of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  32034. #endif
  32035. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  32036. #endif
  32037. #ifndef __JUCE_LABEL_JUCEHEADER__
  32038. #endif
  32039. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  32040. #endif
  32041. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  32042. /********* Start of inlined file: juce_ProgressBar.h *********/
  32043. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  32044. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  32045. /**
  32046. A progress bar component.
  32047. To use this, just create one and make it visible. It'll run its own timer
  32048. to keep an eye on a variable that you give it, and will automatically
  32049. redraw itself when the variable changes.
  32050. For an easy way of running a background task with a dialog box showing its
  32051. progress, see the ThreadWithProgressWindow class.
  32052. @see ThreadWithProgressWindow
  32053. */
  32054. class JUCE_API ProgressBar : public Component,
  32055. public SettableTooltipClient,
  32056. private Timer
  32057. {
  32058. public:
  32059. /** Creates a ProgressBar.
  32060. @param progress pass in a reference to a double that you're going to
  32061. update with your task's progress. The ProgressBar will
  32062. monitor the value of this variable and will redraw itself
  32063. when the value changes. The range is from 0 to 1.0. Obviously
  32064. you'd better be careful not to delete this variable while the
  32065. ProgressBar still exists!
  32066. */
  32067. ProgressBar (double& progress);
  32068. /** Destructor. */
  32069. ~ProgressBar();
  32070. /** Turns the percentage display on or off.
  32071. By default this is on, and the progress bar will display a text string showing
  32072. its current percentage.
  32073. */
  32074. void setPercentageDisplay (const bool shouldDisplayPercentage);
  32075. /** Gives the progress bar a string to display inside it.
  32076. If you call this, it will turn off the percentage display.
  32077. @see setPercentageDisplay
  32078. */
  32079. void setTextToDisplay (const String& text);
  32080. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  32081. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32082. methods.
  32083. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32084. */
  32085. enum ColourIds
  32086. {
  32087. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  32088. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  32089. classes will probably use variations on this colour. */
  32090. };
  32091. juce_UseDebuggingNewOperator
  32092. protected:
  32093. /** @internal */
  32094. void paint (Graphics& g);
  32095. /** @internal */
  32096. void lookAndFeelChanged();
  32097. /** @internal */
  32098. void visibilityChanged();
  32099. /** @internal */
  32100. void colourChanged();
  32101. private:
  32102. double& progress;
  32103. double currentValue;
  32104. bool displayPercentage;
  32105. String displayedMessage, currentMessage;
  32106. uint32 lastCallbackTime;
  32107. void timerCallback();
  32108. ProgressBar (const ProgressBar&);
  32109. const ProgressBar& operator= (const ProgressBar&);
  32110. };
  32111. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  32112. /********* End of inlined file: juce_ProgressBar.h *********/
  32113. #endif
  32114. #ifndef __JUCE_SLIDER_JUCEHEADER__
  32115. /********* Start of inlined file: juce_Slider.h *********/
  32116. #ifndef __JUCE_SLIDER_JUCEHEADER__
  32117. #define __JUCE_SLIDER_JUCEHEADER__
  32118. /********* Start of inlined file: juce_SliderListener.h *********/
  32119. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  32120. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  32121. class Slider;
  32122. /**
  32123. A class for receiving callbacks from a Slider.
  32124. To be told when a slider's value changes, you can register a SliderListener
  32125. object using Slider::addListener().
  32126. @see Slider::addListener, Slider::removeListener
  32127. */
  32128. class JUCE_API SliderListener
  32129. {
  32130. public:
  32131. /** Destructor. */
  32132. virtual ~SliderListener() {}
  32133. /** Called when the slider's value is changed.
  32134. This may be caused by dragging it, or by typing in its text entry box,
  32135. or by a call to Slider::setValue().
  32136. You can find out the new value using Slider::getValue().
  32137. @see Slider::valueChanged
  32138. */
  32139. virtual void sliderValueChanged (Slider* slider) = 0;
  32140. /** Called when the slider is about to be dragged.
  32141. This is called when a drag begins, then it's followed by multiple calls
  32142. to sliderValueChanged(), and then sliderDragEnded() is called after the
  32143. user lets go.
  32144. @see sliderDragEnded, Slider::startedDragging
  32145. */
  32146. virtual void sliderDragStarted (Slider* slider);
  32147. /** Called after a drag operation has finished.
  32148. @see sliderDragStarted, Slider::stoppedDragging
  32149. */
  32150. virtual void sliderDragEnded (Slider* slider);
  32151. };
  32152. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  32153. /********* End of inlined file: juce_SliderListener.h *********/
  32154. /**
  32155. A slider control for changing a value.
  32156. The slider can be horizontal, vertical, or rotary, and can optionally have
  32157. a text-box inside it to show an editable display of the current value.
  32158. To use it, create a Slider object and use the setSliderStyle() method
  32159. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  32160. To define the values that it can be set to, see the setRange() and setValue() methods.
  32161. There are also lots of custom tweaks you can do by subclassing and overriding
  32162. some of the virtual methods, such as changing the scaling, changing the format of
  32163. the text display, custom ways of limiting the values, etc.
  32164. You can register SliderListeners with a slider, which will be informed when the value
  32165. changes, or a subclass can override valueChanged() to be informed synchronously.
  32166. @see SliderListener
  32167. */
  32168. class JUCE_API Slider : public Component,
  32169. public SettableTooltipClient,
  32170. private AsyncUpdater,
  32171. private ButtonListener,
  32172. private LabelListener,
  32173. private Value::Listener
  32174. {
  32175. public:
  32176. /** Creates a slider.
  32177. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  32178. setRange(), etc.
  32179. */
  32180. Slider (const String& componentName);
  32181. /** Destructor. */
  32182. ~Slider();
  32183. /** The types of slider available.
  32184. @see setSliderStyle, setRotaryParameters
  32185. */
  32186. enum SliderStyle
  32187. {
  32188. LinearHorizontal, /**< A traditional horizontal slider. */
  32189. LinearVertical, /**< A traditional vertical slider. */
  32190. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  32191. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  32192. @see setRotaryParameters */
  32193. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  32194. @see setRotaryParameters */
  32195. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  32196. @see setRotaryParameters */
  32197. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  32198. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  32199. @see setMinValue, setMaxValue */
  32200. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  32201. @see setMinValue, setMaxValue */
  32202. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  32203. value, with the current value being somewhere between them.
  32204. @see setMinValue, setMaxValue */
  32205. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  32206. value, with the current value being somewhere between them.
  32207. @see setMinValue, setMaxValue */
  32208. };
  32209. /** Changes the type of slider interface being used.
  32210. @param newStyle the type of interface
  32211. @see setRotaryParameters, setVelocityBasedMode,
  32212. */
  32213. void setSliderStyle (const SliderStyle newStyle);
  32214. /** Returns the slider's current style.
  32215. @see setSliderStyle
  32216. */
  32217. SliderStyle getSliderStyle() const { return style; }
  32218. /** Changes the properties of a rotary slider.
  32219. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  32220. the slider's minimum value is represented
  32221. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  32222. the slider's maximum value is represented. This must be
  32223. greater than startAngleRadians
  32224. @param stopAtEnd if true, then when the slider is dragged around past the
  32225. minimum or maximum, it'll stop there; if false, it'll wrap
  32226. back to the opposite value
  32227. */
  32228. void setRotaryParameters (const float startAngleRadians,
  32229. const float endAngleRadians,
  32230. const bool stopAtEnd);
  32231. /** Sets the distance the mouse has to move to drag the slider across
  32232. the full extent of its range.
  32233. This only applies when in modes like RotaryHorizontalDrag, where it's using
  32234. relative mouse movements to adjust the slider.
  32235. */
  32236. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  32237. /** Changes the way the the mouse is used when dragging the slider.
  32238. If true, this will turn on velocity-sensitive dragging, so that
  32239. the faster the mouse moves, the bigger the movement to the slider. This
  32240. helps when making accurate adjustments if the slider's range is quite large.
  32241. If false, the slider will just try to snap to wherever the mouse is.
  32242. */
  32243. void setVelocityBasedMode (const bool isVelocityBased);
  32244. /** Returns true if velocity-based mode is active.
  32245. @see setVelocityBasedMode
  32246. */
  32247. bool getVelocityBasedMode() const { return isVelocityBased; }
  32248. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  32249. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  32250. or if you're holding down ctrl.
  32251. @param sensitivity higher values than 1.0 increase the range of acceleration used
  32252. @param threshold the minimum number of pixels that the mouse needs to move for it
  32253. to be treated as a movement
  32254. @param offset values greater than 0.0 increase the minimum speed that will be used when
  32255. the threshold is reached
  32256. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  32257. key to toggle velocity-sensitive mode
  32258. */
  32259. void setVelocityModeParameters (const double sensitivity = 1.0,
  32260. const int threshold = 1,
  32261. const double offset = 0.0,
  32262. const bool userCanPressKeyToSwapMode = true);
  32263. /** Returns the velocity sensitivity setting.
  32264. @see setVelocityModeParameters
  32265. */
  32266. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  32267. /** Returns the velocity threshold setting.
  32268. @see setVelocityModeParameters
  32269. */
  32270. int getVelocityThreshold() const { return velocityModeThreshold; }
  32271. /** Returns the velocity offset setting.
  32272. @see setVelocityModeParameters
  32273. */
  32274. double getVelocityOffset() const { return velocityModeOffset; }
  32275. /** Returns the velocity user key setting.
  32276. @see setVelocityModeParameters
  32277. */
  32278. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  32279. /** Sets up a skew factor to alter the way values are distributed.
  32280. You may want to use a range of values on the slider where more accuracy
  32281. is required towards one end of the range, so this will logarithmically
  32282. spread the values across the length of the slider.
  32283. If the factor is < 1.0, the lower end of the range will fill more of the
  32284. slider's length; if the factor is > 1.0, the upper end of the range
  32285. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  32286. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  32287. method instead.
  32288. @see getSkewFactor, setSkewFactorFromMidPoint
  32289. */
  32290. void setSkewFactor (const double factor);
  32291. /** Sets up a skew factor to alter the way values are distributed.
  32292. This allows you to specify the slider value that should appear in the
  32293. centre of the slider's visible range.
  32294. @see setSkewFactor, getSkewFactor
  32295. */
  32296. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint);
  32297. /** Returns the current skew factor.
  32298. See setSkewFactor for more info.
  32299. @see setSkewFactor, setSkewFactorFromMidPoint
  32300. */
  32301. double getSkewFactor() const { return skewFactor; }
  32302. /** Used by setIncDecButtonsMode().
  32303. */
  32304. enum IncDecButtonMode
  32305. {
  32306. incDecButtonsNotDraggable,
  32307. incDecButtonsDraggable_AutoDirection,
  32308. incDecButtonsDraggable_Horizontal,
  32309. incDecButtonsDraggable_Vertical
  32310. };
  32311. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  32312. can be dragged on the buttons to drag the values.
  32313. By default this is turned off. When enabled, clicking on the buttons still works
  32314. them as normal, but by holding down the mouse on a button and dragging it a little
  32315. distance, it flips into a mode where the value can be dragged. The drag direction can
  32316. either be set explicitly to be vertical or horizontal, or can be set to
  32317. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  32318. are side-by-side or above each other.
  32319. */
  32320. void setIncDecButtonsMode (const IncDecButtonMode mode);
  32321. /** The position of the slider's text-entry box.
  32322. @see setTextBoxStyle
  32323. */
  32324. enum TextEntryBoxPosition
  32325. {
  32326. NoTextBox, /**< Doesn't display a text box. */
  32327. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  32328. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  32329. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  32330. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  32331. };
  32332. /** Changes the location and properties of the text-entry box.
  32333. @param newPosition where it should go (or NoTextBox to not have one at all)
  32334. @param isReadOnly if true, it's a read-only display
  32335. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  32336. room for the slider as well!
  32337. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  32338. room for the slider as well!
  32339. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  32340. */
  32341. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  32342. const bool isReadOnly,
  32343. const int textEntryBoxWidth,
  32344. const int textEntryBoxHeight);
  32345. /** Returns the status of the text-box.
  32346. @see setTextBoxStyle
  32347. */
  32348. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  32349. /** Returns the width used for the text-box.
  32350. @see setTextBoxStyle
  32351. */
  32352. int getTextBoxWidth() const { return textBoxWidth; }
  32353. /** Returns the height used for the text-box.
  32354. @see setTextBoxStyle
  32355. */
  32356. int getTextBoxHeight() const { return textBoxHeight; }
  32357. /** Makes the text-box editable.
  32358. By default this is true, and the user can enter values into the textbox,
  32359. but it can be turned off if that's not suitable.
  32360. @see setTextBoxStyle, getValueFromText, getTextFromValue
  32361. */
  32362. void setTextBoxIsEditable (const bool shouldBeEditable);
  32363. /** Returns true if the text-box is read-only.
  32364. @see setTextBoxStyle
  32365. */
  32366. bool isTextBoxEditable() const { return editableText; }
  32367. /** If the text-box is editable, this will give it the focus so that the user can
  32368. type directly into it.
  32369. This is basically the effect as the user clicking on it.
  32370. */
  32371. void showTextBox();
  32372. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  32373. focus away from it.
  32374. @param discardCurrentEditorContents if true, the slider's value will be left
  32375. unchanged; if false, the current contents of the
  32376. text editor will be used to set the slider position
  32377. before it is hidden.
  32378. */
  32379. void hideTextBox (const bool discardCurrentEditorContents);
  32380. /** Changes the slider's current value.
  32381. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  32382. that are registered, and will synchronously call the valueChanged() method in case subclasses
  32383. want to handle it.
  32384. @param newValue the new value to set - this will be restricted by the
  32385. minimum and maximum range, and will be snapped to the
  32386. nearest interval if one has been set
  32387. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  32388. any SliderListeners or the valueChanged() method
  32389. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  32390. synchronously; if false, it will be asynchronous
  32391. */
  32392. void setValue (double newValue,
  32393. const bool sendUpdateMessage = true,
  32394. const bool sendMessageSynchronously = false);
  32395. /** Returns the slider's current value. */
  32396. double getValue() const;
  32397. /** Returns the Value object that represents the slider's current position.
  32398. You can use this Value object to connect the slider's position to external values or setters,
  32399. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  32400. your own Value object.
  32401. @see Value, getMaxValue, getMinValueObject
  32402. */
  32403. Value& getValueObject() { return currentValue; }
  32404. /** Sets the limits that the slider's value can take.
  32405. @param newMinimum the lowest value allowed
  32406. @param newMaximum the highest value allowed
  32407. @param newInterval the steps in which the value is allowed to increase - if this
  32408. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  32409. */
  32410. void setRange (const double newMinimum,
  32411. const double newMaximum,
  32412. const double newInterval = 0);
  32413. /** Returns the current maximum value.
  32414. @see setRange
  32415. */
  32416. double getMaximum() const { return maximum; }
  32417. /** Returns the current minimum value.
  32418. @see setRange
  32419. */
  32420. double getMinimum() const { return minimum; }
  32421. /** Returns the current step-size for values.
  32422. @see setRange
  32423. */
  32424. double getInterval() const { return interval; }
  32425. /** For a slider with two or three thumbs, this returns the lower of its values.
  32426. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  32427. A slider with three values also uses the normal getValue() and setValue() methods to
  32428. control the middle value.
  32429. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  32430. */
  32431. double getMinValue() const;
  32432. /** For a slider with two or three thumbs, this returns the lower of its values.
  32433. You can use this Value object to connect the slider's position to external values or setters,
  32434. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  32435. your own Value object.
  32436. @see Value, getMinValue, getMaxValueObject
  32437. */
  32438. Value& getMinValueObject() { return valueMin; }
  32439. /** For a slider with two or three thumbs, this sets the lower of its values.
  32440. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  32441. that are registered, and will synchronously call the valueChanged() method in case subclasses
  32442. want to handle it.
  32443. @param newValue the new value to set - this will be restricted by the
  32444. minimum and maximum range, and will be snapped to the nearest
  32445. interval if one has been set.
  32446. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  32447. any SliderListeners or the valueChanged() method
  32448. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  32449. synchronously; if false, it will be asynchronous
  32450. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  32451. max value (in a two-value slider) or the mid value (in a three-value
  32452. slider). If false, then if this value goes beyond those values,
  32453. it will push them along with it.
  32454. @see getMinValue, setMaxValue, setValue
  32455. */
  32456. void setMinValue (double newValue,
  32457. const bool sendUpdateMessage = true,
  32458. const bool sendMessageSynchronously = false,
  32459. const bool allowNudgingOfOtherValues = false);
  32460. /** For a slider with two or three thumbs, this returns the higher of its values.
  32461. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  32462. A slider with three values also uses the normal getValue() and setValue() methods to
  32463. control the middle value.
  32464. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  32465. */
  32466. double getMaxValue() const;
  32467. /** For a slider with two or three thumbs, this returns the higher of its values.
  32468. You can use this Value object to connect the slider's position to external values or setters,
  32469. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  32470. your own Value object.
  32471. @see Value, getMaxValue, getMinValueObject
  32472. */
  32473. Value& getMaxValueObject() { return valueMax; }
  32474. /** For a slider with two or three thumbs, this sets the lower of its values.
  32475. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  32476. that are registered, and will synchronously call the valueChanged() method in case subclasses
  32477. want to handle it.
  32478. @param newValue the new value to set - this will be restricted by the
  32479. minimum and maximum range, and will be snapped to the nearest
  32480. interval if one has been set.
  32481. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  32482. any SliderListeners or the valueChanged() method
  32483. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  32484. synchronously; if false, it will be asynchronous
  32485. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  32486. min value (in a two-value slider) or the mid value (in a three-value
  32487. slider). If false, then if this value goes beyond those values,
  32488. it will push them along with it.
  32489. @see getMaxValue, setMinValue, setValue
  32490. */
  32491. void setMaxValue (double newValue,
  32492. const bool sendUpdateMessage = true,
  32493. const bool sendMessageSynchronously = false,
  32494. const bool allowNudgingOfOtherValues = false);
  32495. /** Adds a listener to be called when this slider's value changes. */
  32496. void addListener (SliderListener* const listener);
  32497. /** Removes a previously-registered listener. */
  32498. void removeListener (SliderListener* const listener);
  32499. /** This lets you choose whether double-clicking moves the slider to a given position.
  32500. By default this is turned off, but it's handy if you want a double-click to act
  32501. as a quick way of resetting a slider. Just pass in the value you want it to
  32502. go to when double-clicked.
  32503. @see getDoubleClickReturnValue
  32504. */
  32505. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  32506. const double valueToSetOnDoubleClick);
  32507. /** Returns the values last set by setDoubleClickReturnValue() method.
  32508. Sets isEnabled to true if double-click is enabled, and returns the value
  32509. that was set.
  32510. @see setDoubleClickReturnValue
  32511. */
  32512. double getDoubleClickReturnValue (bool& isEnabled) const;
  32513. /** Tells the slider whether to keep sending change messages while the user
  32514. is dragging the slider.
  32515. If set to true, a change message will only be sent when the user has
  32516. dragged the slider and let go. If set to false (the default), then messages
  32517. will be continuously sent as they drag it while the mouse button is still
  32518. held down.
  32519. */
  32520. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease);
  32521. /** This lets you change whether the slider thumb jumps to the mouse position
  32522. when you click.
  32523. By default, this is true. If it's false, then the slider moves with relative
  32524. motion when you drag it.
  32525. This only applies to linear bars, and won't affect two- or three- value
  32526. sliders.
  32527. */
  32528. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse);
  32529. /** If enabled, this gives the slider a pop-up bubble which appears while the
  32530. slider is being dragged.
  32531. This can be handy if your slider doesn't have a text-box, so that users can
  32532. see the value just when they're changing it.
  32533. If you pass a component as the parentComponentToUse parameter, the pop-up
  32534. bubble will be added as a child of that component when it's needed. If you
  32535. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  32536. transparent window, so if you're using an OS that can't do transparent windows
  32537. you'll have to add it to a parent component instead).
  32538. */
  32539. void setPopupDisplayEnabled (const bool isEnabled,
  32540. Component* const parentComponentToUse);
  32541. /** If this is set to true, then right-clicking on the slider will pop-up
  32542. a menu to let the user change the way it works.
  32543. By default this is turned off, but when turned on, the menu will include
  32544. things like velocity sensitivity, and for rotary sliders, whether they
  32545. use a linear or rotary mouse-drag to move them.
  32546. */
  32547. void setPopupMenuEnabled (const bool menuEnabled);
  32548. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  32549. By default it's enabled.
  32550. */
  32551. void setScrollWheelEnabled (const bool enabled);
  32552. /** Returns a number to indicate which thumb is currently being dragged by the
  32553. mouse.
  32554. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  32555. the maximum-value thumb, or -1 if none is currently down.
  32556. */
  32557. int getThumbBeingDragged() const { return sliderBeingDragged; }
  32558. /** Callback to indicate that the user is about to start dragging the slider.
  32559. @see SliderListener::sliderDragStarted
  32560. */
  32561. virtual void startedDragging();
  32562. /** Callback to indicate that the user has just stopped dragging the slider.
  32563. @see SliderListener::sliderDragEnded
  32564. */
  32565. virtual void stoppedDragging();
  32566. /** Callback to indicate that the user has just moved the slider.
  32567. @see SliderListener::sliderValueChanged
  32568. */
  32569. virtual void valueChanged();
  32570. /** Callback to indicate that the user has just moved the slider.
  32571. Note - the valueChanged() method has changed its format and now no longer has
  32572. any parameters. Update your code to use the new version.
  32573. This version has been left here with an int as its return value to cause
  32574. a syntax error if you've got existing code that uses the old version.
  32575. */
  32576. virtual int valueChanged (double) { jassertfalse; return 0; }
  32577. /** Subclasses can override this to convert a text string to a value.
  32578. When the user enters something into the text-entry box, this method is
  32579. called to convert it to a value.
  32580. The default routine just tries to convert it to a double.
  32581. @see getTextFromValue
  32582. */
  32583. virtual double getValueFromText (const String& text);
  32584. /** Turns the slider's current value into a text string.
  32585. Subclasses can override this to customise the formatting of the text-entry box.
  32586. The default implementation just turns the value into a string, using
  32587. a number of decimal places based on the range interval. If a suffix string
  32588. has been set using setTextValueSuffix(), this will be appended to the text.
  32589. @see getValueFromText
  32590. */
  32591. virtual const String getTextFromValue (double value);
  32592. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  32593. a string.
  32594. This is used by the default implementation of getTextFromValue(), and is just
  32595. appended to the numeric value. For more advanced formatting, you can override
  32596. getTextFromValue() and do something else.
  32597. */
  32598. void setTextValueSuffix (const String& suffix);
  32599. /** Allows a user-defined mapping of distance along the slider to its value.
  32600. The default implementation for this performs the skewing operation that
  32601. can be set up in the setSkewFactor() method. Override it if you need
  32602. some kind of custom mapping instead, but make sure you also implement the
  32603. inverse function in valueToProportionOfLength().
  32604. @param proportion a value 0 to 1.0, indicating a distance along the slider
  32605. @returns the slider value that is represented by this position
  32606. @see valueToProportionOfLength
  32607. */
  32608. virtual double proportionOfLengthToValue (double proportion);
  32609. /** Allows a user-defined mapping of value to the position of the slider along its length.
  32610. The default implementation for this performs the skewing operation that
  32611. can be set up in the setSkewFactor() method. Override it if you need
  32612. some kind of custom mapping instead, but make sure you also implement the
  32613. inverse function in proportionOfLengthToValue().
  32614. @param value a valid slider value, between the range of values specified in
  32615. setRange()
  32616. @returns a value 0 to 1.0 indicating the distance along the slider that
  32617. represents this value
  32618. @see proportionOfLengthToValue
  32619. */
  32620. virtual double valueToProportionOfLength (double value);
  32621. /** Returns the X or Y coordinate of a value along the slider's length.
  32622. If the slider is horizontal, this will be the X coordinate of the given
  32623. value, relative to the left of the slider. If it's vertical, then this will
  32624. be the Y coordinate, relative to the top of the slider.
  32625. If the slider is rotary, this will throw an assertion and return 0. If the
  32626. value is out-of-range, it will be constrained to the length of the slider.
  32627. */
  32628. float getPositionOfValue (const double value);
  32629. /** This can be overridden to allow the slider to snap to user-definable values.
  32630. If overridden, it will be called when the user tries to move the slider to
  32631. a given position, and allows a subclass to sanity-check this value, possibly
  32632. returning a different value to use instead.
  32633. @param attemptedValue the value the user is trying to enter
  32634. @param userIsDragging true if the user is dragging with the mouse; false if
  32635. they are entering the value using the text box
  32636. @returns the value to use instead
  32637. */
  32638. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  32639. /** This can be called to force the text box to update its contents.
  32640. (Not normally needed, as this is done automatically).
  32641. */
  32642. void updateText();
  32643. /** True if the slider moves horizontally. */
  32644. bool isHorizontal() const;
  32645. /** True if the slider moves vertically. */
  32646. bool isVertical() const;
  32647. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  32648. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32649. methods.
  32650. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32651. */
  32652. enum ColourIds
  32653. {
  32654. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  32655. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  32656. and feel class how this is used. */
  32657. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  32658. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  32659. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  32660. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  32661. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  32662. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  32663. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  32664. };
  32665. juce_UseDebuggingNewOperator
  32666. protected:
  32667. /** @internal */
  32668. void labelTextChanged (Label*);
  32669. /** @internal */
  32670. void paint (Graphics& g);
  32671. /** @internal */
  32672. void resized();
  32673. /** @internal */
  32674. void mouseDown (const MouseEvent& e);
  32675. /** @internal */
  32676. void mouseUp (const MouseEvent& e);
  32677. /** @internal */
  32678. void mouseDrag (const MouseEvent& e);
  32679. /** @internal */
  32680. void mouseDoubleClick (const MouseEvent& e);
  32681. /** @internal */
  32682. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  32683. /** @internal */
  32684. void modifierKeysChanged (const ModifierKeys& modifiers);
  32685. /** @internal */
  32686. void buttonClicked (Button* button);
  32687. /** @internal */
  32688. void lookAndFeelChanged();
  32689. /** @internal */
  32690. void enablementChanged();
  32691. /** @internal */
  32692. void focusOfChildComponentChanged (FocusChangeType cause);
  32693. /** @internal */
  32694. void handleAsyncUpdate();
  32695. /** @internal */
  32696. void colourChanged();
  32697. /** @internal */
  32698. void valueChanged (Value& value);
  32699. private:
  32700. SortedSet <void*> listeners;
  32701. Value currentValue, valueMin, valueMax;
  32702. double lastCurrentValue, lastValueMin, lastValueMax;
  32703. double minimum, maximum, interval, doubleClickReturnValue;
  32704. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  32705. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  32706. int velocityModeThreshold;
  32707. float rotaryStart, rotaryEnd;
  32708. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  32709. int mouseDragStartX, mouseDragStartY;
  32710. int sliderRegionStart, sliderRegionSize;
  32711. int sliderBeingDragged;
  32712. int pixelsForFullDragExtent;
  32713. Rectangle sliderRect;
  32714. String textSuffix;
  32715. SliderStyle style;
  32716. TextEntryBoxPosition textBoxPos;
  32717. int textBoxWidth, textBoxHeight;
  32718. IncDecButtonMode incDecButtonMode;
  32719. bool editableText : 1, doubleClickToValue : 1;
  32720. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  32721. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  32722. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  32723. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  32724. Font font;
  32725. Label* valueBox;
  32726. Button* incButton;
  32727. Button* decButton;
  32728. ScopedPointer <Component> popupDisplay;
  32729. Component* parentForPopupDisplay;
  32730. float getLinearSliderPos (const double value);
  32731. void restoreMouseIfHidden();
  32732. void sendDragStart();
  32733. void sendDragEnd();
  32734. double constrainedValue (double value) const;
  32735. void triggerChangeMessage (const bool synchronous);
  32736. bool incDecDragDirectionIsHorizontal() const;
  32737. Slider (const Slider&);
  32738. const Slider& operator= (const Slider&);
  32739. };
  32740. #endif // __JUCE_SLIDER_JUCEHEADER__
  32741. /********* End of inlined file: juce_Slider.h *********/
  32742. #endif
  32743. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  32744. #endif
  32745. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32746. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  32747. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32748. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32749. class TableHeaderComponent;
  32750. /**
  32751. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  32752. You can register one of these objects for table events using TableHeaderComponent::addListener()
  32753. and TableHeaderComponent::removeListener().
  32754. @see TableHeaderComponent
  32755. */
  32756. class JUCE_API TableHeaderListener
  32757. {
  32758. public:
  32759. TableHeaderListener() {}
  32760. /** Destructor. */
  32761. virtual ~TableHeaderListener() {}
  32762. /** This is called when some of the table's columns are added, removed, hidden,
  32763. or rearranged.
  32764. */
  32765. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  32766. /** This is called when one or more of the table's columns are resized.
  32767. */
  32768. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  32769. /** This is called when the column by which the table should be sorted is changed.
  32770. */
  32771. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  32772. /** This is called when the user begins or ends dragging one of the columns around.
  32773. When the user starts dragging a column, this is called with the ID of that
  32774. column. When they finish dragging, it is called again with 0 as the ID.
  32775. */
  32776. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  32777. int columnIdNowBeingDragged);
  32778. };
  32779. /**
  32780. A component that displays a strip of column headings for a table, and allows these
  32781. to be resized, dragged around, etc.
  32782. This is just the component that goes at the top of a table. You can use it
  32783. directly for custom components, or to create a simple table, use the
  32784. TableListBox class.
  32785. To use one of these, create it and use addColumn() to add all the columns that you need.
  32786. Each column must be given a unique ID number that's used to refer to it.
  32787. @see TableListBox, TableHeaderListener
  32788. */
  32789. class JUCE_API TableHeaderComponent : public Component,
  32790. private AsyncUpdater
  32791. {
  32792. public:
  32793. /** Creates an empty table header.
  32794. */
  32795. TableHeaderComponent();
  32796. /** Destructor. */
  32797. ~TableHeaderComponent();
  32798. /** A combination of these flags are passed into the addColumn() method to specify
  32799. the properties of a column.
  32800. */
  32801. enum ColumnPropertyFlags
  32802. {
  32803. 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. */
  32804. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  32805. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  32806. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  32807. 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. */
  32808. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  32809. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  32810. /** This set of default flags is used as the default parameter value in addColumn(). */
  32811. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  32812. /** A quick way of combining flags for a column that's not resizable. */
  32813. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  32814. /** A quick way of combining flags for a column that's not resizable or sortable. */
  32815. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  32816. /** A quick way of combining flags for a column that's not sortable. */
  32817. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  32818. };
  32819. /** Adds a column to the table.
  32820. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  32821. registered listeners.
  32822. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  32823. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  32824. a unique ID. This is used to identify the column later on, after the user may have
  32825. changed the order that they appear in
  32826. @param width the initial width of the column, in pixels
  32827. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  32828. if the 'resizable' flag is specified for this column
  32829. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  32830. if the 'resizable' flag is specified for this column
  32831. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  32832. properties of this column
  32833. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  32834. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  32835. all columns, not just the index amongst those that are currently visible
  32836. */
  32837. void addColumn (const String& columnName,
  32838. const int columnId,
  32839. const int width,
  32840. const int minimumWidth = 30,
  32841. const int maximumWidth = -1,
  32842. const int propertyFlags = defaultFlags,
  32843. const int insertIndex = -1);
  32844. /** Removes a column with the given ID.
  32845. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  32846. registered listeners.
  32847. */
  32848. void removeColumn (const int columnIdToRemove);
  32849. /** Deletes all columns from the table.
  32850. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  32851. registered listeners.
  32852. */
  32853. void removeAllColumns();
  32854. /** Returns the number of columns in the table.
  32855. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  32856. return the total number of columns, including hidden ones.
  32857. @see isColumnVisible
  32858. */
  32859. int getNumColumns (const bool onlyCountVisibleColumns) const;
  32860. /** Returns the name for a column.
  32861. @see setColumnName
  32862. */
  32863. const String getColumnName (const int columnId) const;
  32864. /** Changes the name of a column. */
  32865. void setColumnName (const int columnId, const String& newName);
  32866. /** Moves a column to a different index in the table.
  32867. @param columnId the column to move
  32868. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  32869. */
  32870. void moveColumn (const int columnId, int newVisibleIndex);
  32871. /** Returns the width of one of the columns.
  32872. */
  32873. int getColumnWidth (const int columnId) const;
  32874. /** Changes the width of a column.
  32875. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  32876. */
  32877. void setColumnWidth (const int columnId, const int newWidth);
  32878. /** Shows or hides a column.
  32879. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  32880. @see isColumnVisible
  32881. */
  32882. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  32883. /** Returns true if this column is currently visible.
  32884. @see setColumnVisible
  32885. */
  32886. bool isColumnVisible (const int columnId) const;
  32887. /** Changes the column which is the sort column.
  32888. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  32889. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  32890. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  32891. @see getSortColumnId, isSortedForwards, reSortTable
  32892. */
  32893. void setSortColumnId (const int columnId, const bool sortForwards);
  32894. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  32895. @see setSortColumnId, isSortedForwards
  32896. */
  32897. int getSortColumnId() const;
  32898. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  32899. @see setSortColumnId
  32900. */
  32901. bool isSortedForwards() const;
  32902. /** Triggers a re-sort of the table according to the current sort-column.
  32903. If you modifiy the table's contents, you can call this to signal that the table needs
  32904. to be re-sorted.
  32905. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  32906. tableSortOrderChanged() method of any listeners).
  32907. */
  32908. void reSortTable();
  32909. /** Returns the total width of all the visible columns in the table.
  32910. */
  32911. int getTotalWidth() const;
  32912. /** Returns the index of a given column.
  32913. If there's no such column ID, this will return -1.
  32914. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  32915. otherwise it'll return the index amongst all the columns, including any hidden ones.
  32916. */
  32917. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const;
  32918. /** Returns the ID of the column at a given index.
  32919. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  32920. otherwise it'll count it amongst all the columns, including any hidden ones.
  32921. If the index is out-of-range, it'll return 0.
  32922. */
  32923. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const;
  32924. /** Returns the rectangle containing of one of the columns.
  32925. The index is an index from 0 to the number of columns that are currently visible (hidden
  32926. ones are not counted). It returns a rectangle showing the position of the column relative
  32927. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  32928. */
  32929. const Rectangle getColumnPosition (const int index) const;
  32930. /** Finds the column ID at a given x-position in the component.
  32931. If there is a column at this point this returns its ID, or if not, it will return 0.
  32932. */
  32933. int getColumnIdAtX (const int xToFind) const;
  32934. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  32935. entire width of the component.
  32936. By default this is disabled. Turning it on also means that when resizing a column, those
  32937. on the right will be squashed to fit.
  32938. */
  32939. void setStretchToFitActive (const bool shouldStretchToFit);
  32940. /** Returns true if stretch-to-fit has been enabled.
  32941. @see setStretchToFitActive
  32942. */
  32943. bool isStretchToFitActive() const;
  32944. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  32945. specified width, keeping their relative proportions the same.
  32946. If the minimum widths of the columns are too wide to fit into this space, it may
  32947. actually end up wider.
  32948. */
  32949. void resizeAllColumnsToFit (int targetTotalWidth);
  32950. /** Enables or disables the pop-up menu.
  32951. The default menu allows the user to show or hide columns. You can add custom
  32952. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  32953. By default the menu is enabled.
  32954. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  32955. */
  32956. void setPopupMenuActive (const bool hasMenu);
  32957. /** Returns true if the pop-up menu is enabled.
  32958. @see setPopupMenuActive
  32959. */
  32960. bool isPopupMenuActive() const;
  32961. /** Returns a string that encapsulates the table's current layout.
  32962. This can be restored later using restoreFromString(). It saves the order of
  32963. the columns, the currently-sorted column, and the widths.
  32964. @see restoreFromString
  32965. */
  32966. const String toString() const;
  32967. /** Restores the state of the table, based on a string previously created with
  32968. toString().
  32969. @see toString
  32970. */
  32971. void restoreFromString (const String& storedVersion);
  32972. /** Adds a listener to be informed about things that happen to the header. */
  32973. void addListener (TableHeaderListener* const newListener);
  32974. /** Removes a previously-registered listener. */
  32975. void removeListener (TableHeaderListener* const listenerToRemove);
  32976. /** This can be overridden to handle a mouse-click on one of the column headers.
  32977. The default implementation will use this click to call getSortColumnId() and
  32978. change the sort order.
  32979. */
  32980. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  32981. /** This can be overridden to add custom items to the pop-up menu.
  32982. If you override this, you should call the superclass's method to add its
  32983. column show/hide items, if you want them on the menu as well.
  32984. Then to handle the result, override reactToMenuItem().
  32985. @see reactToMenuItem
  32986. */
  32987. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  32988. /** Override this to handle any custom items that you have added to the
  32989. pop-up menu with an addMenuItems() override.
  32990. If the menuReturnId isn't one of your own custom menu items, you'll need to
  32991. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  32992. handle the items that it had added.
  32993. @see addMenuItems
  32994. */
  32995. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  32996. /** @internal */
  32997. void paint (Graphics& g);
  32998. /** @internal */
  32999. void resized();
  33000. /** @internal */
  33001. void mouseMove (const MouseEvent&);
  33002. /** @internal */
  33003. void mouseEnter (const MouseEvent&);
  33004. /** @internal */
  33005. void mouseExit (const MouseEvent&);
  33006. /** @internal */
  33007. void mouseDown (const MouseEvent&);
  33008. /** @internal */
  33009. void mouseDrag (const MouseEvent&);
  33010. /** @internal */
  33011. void mouseUp (const MouseEvent&);
  33012. /** @internal */
  33013. const MouseCursor getMouseCursor();
  33014. /** Can be overridden for more control over the pop-up menu behaviour. */
  33015. virtual void showColumnChooserMenu (const int columnIdClicked);
  33016. juce_UseDebuggingNewOperator
  33017. private:
  33018. struct ColumnInfo
  33019. {
  33020. String name;
  33021. int id, propertyFlags, width, minimumWidth, maximumWidth;
  33022. double lastDeliberateWidth;
  33023. bool isVisible() const;
  33024. };
  33025. OwnedArray <ColumnInfo> columns;
  33026. Array <TableHeaderListener*> listeners;
  33027. ScopedPointer <Component> dragOverlayComp;
  33028. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  33029. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  33030. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  33031. ColumnInfo* getInfoForId (const int columnId) const;
  33032. int visibleIndexToTotalIndex (const int visibleIndex) const;
  33033. void sendColumnsChanged();
  33034. void handleAsyncUpdate();
  33035. void beginDrag (const MouseEvent&);
  33036. void endDrag (const int finalIndex);
  33037. int getResizeDraggerAt (const int mouseX) const;
  33038. void updateColumnUnderMouse (int x, int y);
  33039. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  33040. TableHeaderComponent (const TableHeaderComponent&);
  33041. const TableHeaderComponent operator= (const TableHeaderComponent&);
  33042. };
  33043. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33044. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  33045. #endif
  33046. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  33047. /********* Start of inlined file: juce_TableListBox.h *********/
  33048. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  33049. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  33050. /**
  33051. One of these is used by a TableListBox as the data model for the table's contents.
  33052. The virtual methods that you override in this class take care of drawing the
  33053. table cells, and reacting to events.
  33054. @see TableListBox
  33055. */
  33056. class JUCE_API TableListBoxModel
  33057. {
  33058. public:
  33059. TableListBoxModel() {}
  33060. /** Destructor. */
  33061. virtual ~TableListBoxModel() {}
  33062. /** This must return the number of rows currently in the table.
  33063. If the number of rows changes, you must call TableListBox::updateContent() to
  33064. cause it to refresh the list.
  33065. */
  33066. virtual int getNumRows() = 0;
  33067. /** This must draw the background behind one of the rows in the table.
  33068. The graphics context has its origin at the row's top-left, and your method
  33069. should fill the area specified by the width and height parameters.
  33070. */
  33071. virtual void paintRowBackground (Graphics& g,
  33072. int rowNumber,
  33073. int width, int height,
  33074. bool rowIsSelected) = 0;
  33075. /** This must draw one of the cells.
  33076. The graphics context's origin will already be set to the top-left of the cell,
  33077. whose size is specified by (width, height).
  33078. */
  33079. virtual void paintCell (Graphics& g,
  33080. int rowNumber,
  33081. int columnId,
  33082. int width, int height,
  33083. bool rowIsSelected) = 0;
  33084. /** This is used to create or update a custom component to go in a cell.
  33085. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  33086. and handle mouse clicks with cellClicked().
  33087. This method will be called whenever a custom component might need to be updated - e.g.
  33088. when the table is changed, or TableListBox::updateContent() is called.
  33089. If you don't need a custom component for the specified cell, then return 0.
  33090. If you do want a custom component, and the existingComponentToUpdate is null, then
  33091. this method must create a new component suitable for the cell, and return it.
  33092. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  33093. by this method. In this case, the method must either update it to make sure it's correctly representing
  33094. the given cell (which may be different from the one that the component was created for), or it can
  33095. delete this component and return a new one.
  33096. */
  33097. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  33098. Component* existingComponentToUpdate);
  33099. /** This callback is made when the user clicks on one of the cells in the table.
  33100. The mouse event's coordinates will be relative to the entire table row.
  33101. @see cellDoubleClicked, backgroundClicked
  33102. */
  33103. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  33104. /** This callback is made when the user clicks on one of the cells in the table.
  33105. The mouse event's coordinates will be relative to the entire table row.
  33106. @see cellClicked, backgroundClicked
  33107. */
  33108. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  33109. /** This can be overridden to react to the user double-clicking on a part of the list where
  33110. there are no rows.
  33111. @see cellClicked
  33112. */
  33113. virtual void backgroundClicked();
  33114. /** This callback is made when the table's sort order is changed.
  33115. This could be because the user has clicked a column header, or because the
  33116. TableHeaderComponent::setSortColumnId() method was called.
  33117. If you implement this, your method should re-sort the table using the given
  33118. column as the key.
  33119. */
  33120. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  33121. /** Returns the best width for one of the columns.
  33122. If you implement this method, you should measure the width of all the items
  33123. in this column, and return the best size.
  33124. Returning 0 means that the column shouldn't be changed.
  33125. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  33126. */
  33127. virtual int getColumnAutoSizeWidth (int columnId);
  33128. /** Returns a tooltip for a particular cell in the table.
  33129. */
  33130. virtual const String getCellTooltip (int rowNumber, int columnId);
  33131. /** Override this to be informed when rows are selected or deselected.
  33132. @see ListBox::selectedRowsChanged()
  33133. */
  33134. virtual void selectedRowsChanged (int lastRowSelected);
  33135. /** Override this to be informed when the delete key is pressed.
  33136. @see ListBox::deleteKeyPressed()
  33137. */
  33138. virtual void deleteKeyPressed (int lastRowSelected);
  33139. /** Override this to be informed when the return key is pressed.
  33140. @see ListBox::returnKeyPressed()
  33141. */
  33142. virtual void returnKeyPressed (int lastRowSelected);
  33143. /** Override this to be informed when the list is scrolled.
  33144. This might be caused by the user moving the scrollbar, or by programmatic changes
  33145. to the list position.
  33146. */
  33147. virtual void listWasScrolled();
  33148. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  33149. If this returns a non-empty name then when the user drags a row, the table will try to
  33150. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  33151. drag-and-drop operation, using this string as the source description, and the listbox
  33152. itself as the source component.
  33153. @see DragAndDropContainer::startDragging
  33154. */
  33155. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  33156. };
  33157. /**
  33158. A table of cells, using a TableHeaderComponent as its header.
  33159. This component makes it easy to create a table by providing a TableListBoxModel as
  33160. the data source.
  33161. @see TableListBoxModel, TableHeaderComponent
  33162. */
  33163. class JUCE_API TableListBox : public ListBox,
  33164. private ListBoxModel,
  33165. private TableHeaderListener
  33166. {
  33167. public:
  33168. /** Creates a TableListBox.
  33169. The model pointer passed-in can be null, in which case you can set it later
  33170. with setModel().
  33171. */
  33172. TableListBox (const String& componentName,
  33173. TableListBoxModel* const model);
  33174. /** Destructor. */
  33175. ~TableListBox();
  33176. /** Changes the TableListBoxModel that is being used for this table.
  33177. */
  33178. void setModel (TableListBoxModel* const newModel);
  33179. /** Returns the model currently in use. */
  33180. TableListBoxModel* getModel() const { return model; }
  33181. /** Returns the header component being used in this table. */
  33182. TableHeaderComponent* getHeader() const { return header; }
  33183. /** Changes the height of the table header component.
  33184. @see getHeaderHeight
  33185. */
  33186. void setHeaderHeight (const int newHeight);
  33187. /** Returns the height of the table header.
  33188. @see setHeaderHeight
  33189. */
  33190. int getHeaderHeight() const;
  33191. /** Resizes a column to fit its contents.
  33192. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  33193. and applies that to the column.
  33194. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  33195. */
  33196. void autoSizeColumn (const int columnId);
  33197. /** Calls autoSizeColumn() for all columns in the table. */
  33198. void autoSizeAllColumns();
  33199. /** Enables or disables the auto size options on the popup menu.
  33200. By default, these are enabled.
  33201. */
  33202. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  33203. /** True if the auto-size options should be shown on the menu.
  33204. @see setAutoSizeMenuOptionsShown
  33205. */
  33206. bool isAutoSizeMenuOptionShown() const;
  33207. /** Returns the position of one of the cells in the table.
  33208. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  33209. the table component's top-left. The row number isn't checked to see if it's
  33210. in-range, but the column ID must exist or this will return an empty rectangle.
  33211. If relativeToComponentTopLeft is false, the co-ords are relative to the
  33212. top-left of the table's top-left cell.
  33213. */
  33214. const Rectangle getCellPosition (const int columnId,
  33215. const int rowNumber,
  33216. const bool relativeToComponentTopLeft) const;
  33217. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  33218. @see ListBox::scrollToEnsureRowIsOnscreen
  33219. */
  33220. void scrollToEnsureColumnIsOnscreen (const int columnId);
  33221. /** @internal */
  33222. int getNumRows();
  33223. /** @internal */
  33224. void paintListBoxItem (int, Graphics&, int, int, bool);
  33225. /** @internal */
  33226. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  33227. /** @internal */
  33228. void selectedRowsChanged (int lastRowSelected);
  33229. /** @internal */
  33230. void deleteKeyPressed (int currentSelectedRow);
  33231. /** @internal */
  33232. void returnKeyPressed (int currentSelectedRow);
  33233. /** @internal */
  33234. void backgroundClicked();
  33235. /** @internal */
  33236. void listWasScrolled();
  33237. /** @internal */
  33238. void tableColumnsChanged (TableHeaderComponent*);
  33239. /** @internal */
  33240. void tableColumnsResized (TableHeaderComponent*);
  33241. /** @internal */
  33242. void tableSortOrderChanged (TableHeaderComponent*);
  33243. /** @internal */
  33244. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  33245. /** @internal */
  33246. void resized();
  33247. juce_UseDebuggingNewOperator
  33248. private:
  33249. TableHeaderComponent* header;
  33250. TableListBoxModel* model;
  33251. int columnIdNowBeingDragged;
  33252. bool autoSizeOptionsShown;
  33253. void updateColumnComponents() const;
  33254. TableListBox (const TableListBox&);
  33255. const TableListBox& operator= (const TableListBox&);
  33256. };
  33257. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  33258. /********* End of inlined file: juce_TableListBox.h *********/
  33259. #endif
  33260. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  33261. #endif
  33262. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  33263. #endif
  33264. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33265. #endif
  33266. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33267. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  33268. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33269. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33270. /**
  33271. A factory object which can create ToolbarItemComponent objects.
  33272. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  33273. that it can create.
  33274. Each type of item is identified by a unique ID, and multiple instances of an
  33275. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  33276. bars).
  33277. @see Toolbar, ToolbarItemComponent, ToolbarButton
  33278. */
  33279. class JUCE_API ToolbarItemFactory
  33280. {
  33281. public:
  33282. ToolbarItemFactory();
  33283. /** Destructor. */
  33284. virtual ~ToolbarItemFactory();
  33285. /** A set of reserved item ID values, used for the built-in item types.
  33286. */
  33287. enum SpecialItemIds
  33288. {
  33289. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  33290. can be placed between sets of items to break them into groups. */
  33291. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  33292. items.*/
  33293. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  33294. either side of it, filling any available space. */
  33295. };
  33296. /** Must return a list of the IDs for all the item types that this factory can create.
  33297. The ids should be added to the array that is passed-in.
  33298. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  33299. and the predefined IDs in the SpecialItemIds enum.
  33300. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  33301. to this list if you want your toolbar to be able to contain those items.
  33302. The list returned here is used by the ToolbarItemPalette class to obtain its list
  33303. of available items, and their order on the palette will reflect the order in which
  33304. they appear on this list.
  33305. @see ToolbarItemPalette
  33306. */
  33307. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  33308. /** Must return the set of items that should be added to a toolbar as its default set.
  33309. This method is used by Toolbar::addDefaultItems() to determine which items to
  33310. create.
  33311. The items that your method adds to the array that is passed-in will be added to the
  33312. toolbar in the same order. Items can appear in the list more than once.
  33313. */
  33314. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  33315. /** Must create an instance of one of the items that the factory lists in its
  33316. getAllToolbarItemIds() method.
  33317. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  33318. method, except for the built-in item types from the SpecialItemIds enum, which
  33319. are created internally by the toolbar code.
  33320. Try not to keep a pointer to the object that is returned, as it will be deleted
  33321. automatically by the toolbar, and remember that multiple instances of the same
  33322. item type are likely to exist at the same time.
  33323. */
  33324. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  33325. };
  33326. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33327. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  33328. #endif
  33329. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33330. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  33331. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33332. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33333. /**
  33334. A component containing a list of toolbar items, which the user can drag onto
  33335. a toolbar to add them.
  33336. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  33337. which automatically shows one of these in a dialog box with lots of extra controls.
  33338. @see Toolbar
  33339. */
  33340. class JUCE_API ToolbarItemPalette : public Component,
  33341. public DragAndDropContainer
  33342. {
  33343. public:
  33344. /** Creates a palette of items for a given factory, with the aim of adding them
  33345. to the specified toolbar.
  33346. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  33347. set of items that are shown in this palette.
  33348. The toolbar and factory must not be deleted while this object exists.
  33349. */
  33350. ToolbarItemPalette (ToolbarItemFactory& factory,
  33351. Toolbar* const toolbar);
  33352. /** Destructor. */
  33353. ~ToolbarItemPalette();
  33354. /** @internal */
  33355. void resized();
  33356. juce_UseDebuggingNewOperator
  33357. private:
  33358. ToolbarItemFactory& factory;
  33359. Toolbar* toolbar;
  33360. Viewport* viewport;
  33361. friend class Toolbar;
  33362. void replaceComponent (ToolbarItemComponent* const comp);
  33363. ToolbarItemPalette (const ToolbarItemPalette&);
  33364. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  33365. };
  33366. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33367. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  33368. #endif
  33369. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  33370. /********* Start of inlined file: juce_TreeView.h *********/
  33371. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  33372. #define __JUCE_TREEVIEW_JUCEHEADER__
  33373. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  33374. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33375. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33376. /**
  33377. Components derived from this class can have files dropped onto them by an external application.
  33378. @see DragAndDropContainer
  33379. */
  33380. class JUCE_API FileDragAndDropTarget
  33381. {
  33382. public:
  33383. /** Destructor. */
  33384. virtual ~FileDragAndDropTarget() {}
  33385. /** Callback to check whether this target is interested in the set of files being offered.
  33386. Note that this will be called repeatedly when the user is dragging the mouse around over your
  33387. component, so don't do anything time-consuming in here, like opening the files to have a look
  33388. inside them!
  33389. @param files the set of (absolute) pathnames of the files that the user is dragging
  33390. @returns true if this component wants to receive the other callbacks regarging this
  33391. type of object; if it returns false, no other callbacks will be made.
  33392. */
  33393. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  33394. /** Callback to indicate that some files are being dragged over this component.
  33395. This gets called when the user moves the mouse into this component while dragging.
  33396. Use this callback as a trigger to make your component repaint itself to give the
  33397. user feedback about whether the files can be dropped here or not.
  33398. @param files the set of (absolute) pathnames of the files that the user is dragging
  33399. @param x the mouse x position, relative to this component
  33400. @param y the mouse y position, relative to this component
  33401. */
  33402. virtual void fileDragEnter (const StringArray& files, int x, int y);
  33403. /** Callback to indicate that the user is dragging some files over this component.
  33404. This gets called when the user moves the mouse over this component while dragging.
  33405. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33406. this lets you know what happens in-between.
  33407. @param files the set of (absolute) pathnames of the files that the user is dragging
  33408. @param x the mouse x position, relative to this component
  33409. @param y the mouse y position, relative to this component
  33410. */
  33411. virtual void fileDragMove (const StringArray& files, int x, int y);
  33412. /** Callback to indicate that the mouse has moved away from this component.
  33413. This gets called when the user moves the mouse out of this component while dragging
  33414. the files.
  33415. If you've used fileDragEnter() to repaint your component and give feedback, use this
  33416. as a signal to repaint it in its normal state.
  33417. @param files the set of (absolute) pathnames of the files that the user is dragging
  33418. */
  33419. virtual void fileDragExit (const StringArray& files);
  33420. /** Callback to indicate that the user has dropped the files onto this component.
  33421. When the user drops the files, this get called, and you can use the files in whatever
  33422. way is appropriate.
  33423. Note that after this is called, the fileDragExit method may not be called, so you should
  33424. clean up in here if there's anything you need to do when the drag finishes.
  33425. @param files the set of (absolute) pathnames of the files that the user is dragging
  33426. @param x the mouse x position, relative to this component
  33427. @param y the mouse y position, relative to this component
  33428. */
  33429. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  33430. };
  33431. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33432. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  33433. class TreeView;
  33434. /**
  33435. An item in a treeview.
  33436. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  33437. own sub-items.
  33438. To implement an item that contains sub-items, override the itemOpennessChanged()
  33439. method so that when it is opened, it adds the new sub-items to itself using the
  33440. addSubItem method. Depending on the nature of the item it might choose to only
  33441. do this the first time it's opened, or it might want to refresh itself each time.
  33442. It also has the option of deleting its sub-items when it is closed, or leaving them
  33443. in place.
  33444. */
  33445. class JUCE_API TreeViewItem
  33446. {
  33447. public:
  33448. /** Constructor. */
  33449. TreeViewItem();
  33450. /** Destructor. */
  33451. virtual ~TreeViewItem();
  33452. /** Returns the number of sub-items that have been added to this item.
  33453. Note that this doesn't mean much if the node isn't open.
  33454. @see getSubItem, mightContainSubItems, addSubItem
  33455. */
  33456. int getNumSubItems() const throw();
  33457. /** Returns one of the item's sub-items.
  33458. Remember that the object returned might get deleted at any time when its parent
  33459. item is closed or refreshed, depending on the nature of the items you're using.
  33460. @see getNumSubItems
  33461. */
  33462. TreeViewItem* getSubItem (const int index) const throw();
  33463. /** Removes any sub-items. */
  33464. void clearSubItems();
  33465. /** Adds a sub-item.
  33466. @param newItem the object to add to the item's sub-item list. Once added, these can be
  33467. found using getSubItem(). When the items are later removed with
  33468. removeSubItem() (or when this item is deleted), they will be deleted.
  33469. @param insertPosition the index which the new item should have when it's added. If this
  33470. value is less than 0, the item will be added to the end of the list.
  33471. */
  33472. void addSubItem (TreeViewItem* const newItem,
  33473. const int insertPosition = -1);
  33474. /** Removes one of the sub-items.
  33475. @param index the item to remove
  33476. @param deleteItem if true, the item that is removed will also be deleted.
  33477. */
  33478. void removeSubItem (const int index,
  33479. const bool deleteItem = true);
  33480. /** Returns the TreeView to which this item belongs. */
  33481. TreeView* getOwnerView() const throw() { return ownerView; }
  33482. /** Returns the item within which this item is contained. */
  33483. TreeViewItem* getParentItem() const throw() { return parentItem; }
  33484. /** True if this item is currently open in the treeview. */
  33485. bool isOpen() const throw();
  33486. /** Opens or closes the item.
  33487. When opened or closed, the item's itemOpennessChanged() method will be called,
  33488. and a subclass should use this callback to create and add any sub-items that
  33489. it needs to.
  33490. @see itemOpennessChanged, mightContainSubItems
  33491. */
  33492. void setOpen (const bool shouldBeOpen);
  33493. /** True if this item is currently selected.
  33494. Use this when painting the node, to decide whether to draw it as selected or not.
  33495. */
  33496. bool isSelected() const throw();
  33497. /** Selects or deselects the item.
  33498. This will cause a callback to itemSelectionChanged()
  33499. */
  33500. void setSelected (const bool shouldBeSelected,
  33501. const bool deselectOtherItemsFirst);
  33502. /** Returns the rectangle that this item occupies.
  33503. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  33504. top-left of the TreeView comp, so this will depend on the scroll-position of
  33505. the tree. If false, it is relative to the top-left of the topmost item in the
  33506. tree (so this would be unaffected by scrolling the view).
  33507. */
  33508. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  33509. /** Sends a signal to the treeview to make it refresh itself.
  33510. Call this if your items have changed and you want the tree to update to reflect
  33511. this.
  33512. */
  33513. void treeHasChanged() const throw();
  33514. /** Sends a repaint message to redraw just this item.
  33515. Note that you should only call this if you want to repaint a superficial change. If
  33516. you're altering the tree's nodes, you should instead call treeHasChanged().
  33517. */
  33518. void repaintItem() const;
  33519. /** Returns the row number of this item in the tree.
  33520. The row number of an item will change according to which items are open.
  33521. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  33522. */
  33523. int getRowNumberInTree() const throw();
  33524. /** Returns true if all the item's parent nodes are open.
  33525. This is useful to check whether the item might actually be visible or not.
  33526. */
  33527. bool areAllParentsOpen() const throw();
  33528. /** Changes whether lines are drawn to connect any sub-items to this item.
  33529. By default, line-drawing is turned on.
  33530. */
  33531. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  33532. /** Tells the tree whether this item can potentially be opened.
  33533. If your item could contain sub-items, this should return true; if it returns
  33534. false then the tree will not try to open the item. This determines whether or
  33535. not the item will be drawn with a 'plus' button next to it.
  33536. */
  33537. virtual bool mightContainSubItems() = 0;
  33538. /** Returns a string to uniquely identify this item.
  33539. If you're planning on using the TreeView::getOpennessState() method, then
  33540. these strings will be used to identify which nodes are open. The string
  33541. should be unique amongst the item's sibling items, but it's ok for there
  33542. to be duplicates at other levels of the tree.
  33543. If you're not going to store the state, then it's ok not to bother implementing
  33544. this method.
  33545. */
  33546. virtual const String getUniqueName() const;
  33547. /** Called when an item is opened or closed.
  33548. When setOpen() is called and the item has specified that it might
  33549. have sub-items with the mightContainSubItems() method, this method
  33550. is called to let the item create or manage its sub-items.
  33551. So when this is called with isNowOpen set to true (i.e. when the item is being
  33552. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  33553. refresh its sub-item list.
  33554. When this is called with isNowOpen set to false, the subclass might want
  33555. to use clearSubItems() to save on space, or it might choose to leave them,
  33556. depending on the nature of the tree.
  33557. You could also use this callback as a trigger to start a background process
  33558. which asynchronously creates sub-items and adds them, if that's more
  33559. appropriate for the task in hand.
  33560. @see mightContainSubItems
  33561. */
  33562. virtual void itemOpennessChanged (bool isNowOpen);
  33563. /** Must return the width required by this item.
  33564. If your item needs to have a particular width in pixels, return that value; if
  33565. you'd rather have it just fill whatever space is available in the treeview,
  33566. return -1.
  33567. If all your items return -1, no horizontal scrollbar will be shown, but if any
  33568. items have fixed widths and extend beyond the width of the treeview, a
  33569. scrollbar will appear.
  33570. Each item can be a different width, but if they change width, you should call
  33571. treeHasChanged() to update the tree.
  33572. */
  33573. virtual int getItemWidth() const { return -1; }
  33574. /** Must return the height required by this item.
  33575. This is the height in pixels that the item will take up. Items in the tree
  33576. can be different heights, but if they change height, you should call
  33577. treeHasChanged() to update the tree.
  33578. */
  33579. virtual int getItemHeight() const { return 20; }
  33580. /** You can override this method to return false if you don't want to allow the
  33581. user to select this item.
  33582. */
  33583. virtual bool canBeSelected() const { return true; }
  33584. /** Creates a component that will be used to represent this item.
  33585. You don't have to implement this method - if it returns 0 then no component
  33586. will be used for the item, and you can just draw it using the paintItem()
  33587. callback. But if you do return a component, it will be positioned in the
  33588. treeview so that it can be used to represent this item.
  33589. The component returned will be managed by the treeview, so always return
  33590. a new component, and don't keep a reference to it, as the treeview will
  33591. delete it later when it goes off the screen or is no longer needed. Also
  33592. bear in mind that if the component keeps a reference to the item that
  33593. created it, that item could be deleted before the component. Its position
  33594. and size will be completely managed by the tree, so don't attempt to move it
  33595. around.
  33596. Something you may want to do with your component is to give it a pointer to
  33597. the TreeView that created it. This is perfectly safe, and there's no danger
  33598. of it becoming a dangling pointer because the TreeView will always delete
  33599. the component before it is itself deleted.
  33600. As long as you stick to these rules you can return whatever kind of
  33601. component you like. It's most useful if you're doing things like drag-and-drop
  33602. of items, or want to use a Label component to edit item names, etc.
  33603. */
  33604. virtual Component* createItemComponent() { return 0; }
  33605. /** Draws the item's contents.
  33606. You can choose to either implement this method and draw each item, or you
  33607. can use createItemComponent() to create a component that will represent the
  33608. item.
  33609. If all you need in your tree is to be able to draw the items and detect when
  33610. the user selects or double-clicks one of them, it's probably enough to
  33611. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  33612. complicated interactions, you may need to use createItemComponent() instead.
  33613. @param g the graphics context to draw into
  33614. @param width the width of the area available for drawing
  33615. @param height the height of the area available for drawing
  33616. */
  33617. virtual void paintItem (Graphics& g, int width, int height);
  33618. /** Draws the item's open/close button.
  33619. If you don't implement this method, the default behaviour is to
  33620. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  33621. it for custom effects.
  33622. */
  33623. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  33624. /** Called when the user clicks on this item.
  33625. If you're using createItemComponent() to create a custom component for the
  33626. item, the mouse-clicks might not make it through to the treeview, but this
  33627. is how you find out about clicks when just drawing each item individually.
  33628. The associated mouse-event details are passed in, so you can find out about
  33629. which button, where it was, etc.
  33630. @see itemDoubleClicked
  33631. */
  33632. virtual void itemClicked (const MouseEvent& e);
  33633. /** Called when the user double-clicks on this item.
  33634. If you're using createItemComponent() to create a custom component for the
  33635. item, the mouse-clicks might not make it through to the treeview, but this
  33636. is how you find out about clicks when just drawing each item individually.
  33637. The associated mouse-event details are passed in, so you can find out about
  33638. which button, where it was, etc.
  33639. If not overridden, the base class method here will open or close the item as
  33640. if the 'plus' button had been clicked.
  33641. @see itemClicked
  33642. */
  33643. virtual void itemDoubleClicked (const MouseEvent& e);
  33644. /** Called when the item is selected or deselected.
  33645. Use this if you want to do something special when the item's selectedness
  33646. changes. By default it'll get repainted when this happens.
  33647. */
  33648. virtual void itemSelectionChanged (bool isNowSelected);
  33649. /** The item can return a tool tip string here if it wants to.
  33650. @see TooltipClient
  33651. */
  33652. virtual const String getTooltip();
  33653. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  33654. If this returns a non-empty name then when the user drags an item, the treeview will
  33655. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  33656. a drag-and-drop operation, using this string as the source description, with the treeview
  33657. itself as the source component.
  33658. If you need more complex drag-and-drop behaviour, you can use custom components for
  33659. the items, and use those to trigger the drag.
  33660. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  33661. isInterestedInFileDrag(), etc.
  33662. @see DragAndDropContainer::startDragging
  33663. */
  33664. virtual const String getDragSourceDescription();
  33665. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  33666. method and return true.
  33667. If you return true and allow some files to be dropped, you'll also need to implement the
  33668. filesDropped() method to do something with them.
  33669. Note that this will be called often, so make your implementation very quick! There's
  33670. certainly no time to try opening the files and having a think about what's inside them!
  33671. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  33672. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  33673. */
  33674. virtual bool isInterestedInFileDrag (const StringArray& files);
  33675. /** When files are dropped into this item, this callback is invoked.
  33676. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  33677. The insertIndex value indicates where in the list of sub-items the files were dropped.
  33678. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  33679. */
  33680. virtual void filesDropped (const StringArray& files, int insertIndex);
  33681. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  33682. If you implement this method, you'll also need to implement itemDropped() in order to handle
  33683. the items when they are dropped.
  33684. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  33685. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  33686. */
  33687. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  33688. /** When a things are dropped into this item, this callback is invoked.
  33689. For this to work, you need to have also implemented isInterestedInDragSource().
  33690. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  33691. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  33692. */
  33693. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  33694. /** Sets a flag to indicate that the item wants to be allowed
  33695. to draw all the way across to the left edge of the treeview.
  33696. By default this is false, which means that when the paintItem()
  33697. method is called, its graphics context is clipped to only allow
  33698. drawing within the item's rectangle. If this flag is set to true,
  33699. then the graphics context isn't clipped on its left side, so it
  33700. can draw all the way across to the left margin. Note that the
  33701. context will still have its origin in the same place though, so
  33702. the coordinates of anything to its left will be negative. It's
  33703. mostly useful if you want to draw a wider bar behind the
  33704. highlighted item.
  33705. */
  33706. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  33707. /** Saves the current state of open/closed nodes so it can be restored later.
  33708. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  33709. and records it as XML. To identify node objects it uses the
  33710. TreeViewItem::getUniqueName() method to create named paths. This
  33711. means that the same state of open/closed nodes can be restored to a
  33712. completely different instance of the tree, as long as it contains nodes
  33713. whose unique names are the same.
  33714. You'd normally want to use TreeView::getOpennessState() rather than call it
  33715. for a specific item, but this can be handy if you need to briefly save the state
  33716. for a section of the tree.
  33717. The caller is responsible for deleting the object that is returned.
  33718. @see TreeView::getOpennessState, restoreOpennessState
  33719. */
  33720. XmlElement* getOpennessState() const throw();
  33721. /** Restores the openness of this item and all its sub-items from a saved state.
  33722. See TreeView::restoreOpennessState for more details.
  33723. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  33724. for a specific item, but this can be handy if you need to briefly save the state
  33725. for a section of the tree.
  33726. @see TreeView::restoreOpennessState, getOpennessState
  33727. */
  33728. void restoreOpennessState (const XmlElement& xml) throw();
  33729. /** Returns the index of this item in its parent's sub-items. */
  33730. int getIndexInParent() const throw();
  33731. /** Returns true if this item is the last of its parent's sub-itens. */
  33732. bool isLastOfSiblings() const throw();
  33733. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  33734. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  33735. The string takes the form of a path, constructed from the getUniqueName() of this
  33736. item and all its parents, so these must all be correctly implemented for it to work.
  33737. @see TreeView::findItemFromIdentifierString, getUniqueName
  33738. */
  33739. const String getItemIdentifierString() const;
  33740. juce_UseDebuggingNewOperator
  33741. private:
  33742. TreeView* ownerView;
  33743. TreeViewItem* parentItem;
  33744. OwnedArray <TreeViewItem> subItems;
  33745. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  33746. int uid;
  33747. bool selected : 1;
  33748. bool redrawNeeded : 1;
  33749. bool drawLinesInside : 1;
  33750. bool drawsInLeftMargin : 1;
  33751. unsigned int openness : 2;
  33752. friend class TreeView;
  33753. friend class TreeViewContentComponent;
  33754. void updatePositions (int newY);
  33755. int getIndentX() const throw();
  33756. void setOwnerView (TreeView* const newOwner) throw();
  33757. void paintRecursively (Graphics& g, int width);
  33758. TreeViewItem* getTopLevelItem() throw();
  33759. TreeViewItem* findItemRecursively (int y) throw();
  33760. TreeViewItem* getDeepestOpenParentItem() throw();
  33761. int getNumRows() const throw();
  33762. TreeViewItem* getItemOnRow (int index) throw();
  33763. void deselectAllRecursively();
  33764. int countSelectedItemsRecursively() const throw();
  33765. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  33766. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  33767. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  33768. TreeViewItem (const TreeViewItem&);
  33769. const TreeViewItem& operator= (const TreeViewItem&);
  33770. };
  33771. /**
  33772. A tree-view component.
  33773. Use one of these to hold and display a structure of TreeViewItem objects.
  33774. */
  33775. class JUCE_API TreeView : public Component,
  33776. public SettableTooltipClient,
  33777. public FileDragAndDropTarget,
  33778. public DragAndDropTarget,
  33779. private AsyncUpdater
  33780. {
  33781. public:
  33782. /** Creates an empty treeview.
  33783. Once you've got a treeview component, you'll need to give it something to
  33784. display, using the setRootItem() method.
  33785. */
  33786. TreeView (const String& componentName = String::empty);
  33787. /** Destructor. */
  33788. ~TreeView();
  33789. /** Sets the item that is displayed in the treeview.
  33790. A tree has a single root item which contains as many sub-items as it needs. If
  33791. you want the tree to contain a number of root items, you should still use a single
  33792. root item above these, but hide it using setRootItemVisible().
  33793. You can pass in 0 to this method to clear the tree and remove its current root item.
  33794. The object passed in will not be deleted by the treeview, it's up to the caller
  33795. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  33796. this item until you've removed it from the tree, either by calling setRootItem (0),
  33797. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  33798. to delete it.
  33799. */
  33800. void setRootItem (TreeViewItem* const newRootItem);
  33801. /** Returns the tree's root item.
  33802. This will be the last object passed to setRootItem(), or 0 if none has been set.
  33803. */
  33804. TreeViewItem* getRootItem() const throw() { return rootItem; }
  33805. /** This will remove and delete the current root item.
  33806. It's a convenient way of deleting the item and calling setRootItem (0).
  33807. */
  33808. void deleteRootItem();
  33809. /** Changes whether the tree's root item is shown or not.
  33810. If the root item is hidden, only its sub-items will be shown in the treeview - this
  33811. lets you make the tree look as if it's got many root items. If it's hidden, this call
  33812. will also make sure the root item is open (otherwise the treeview would look empty).
  33813. */
  33814. void setRootItemVisible (const bool shouldBeVisible);
  33815. /** Returns true if the root item is visible.
  33816. @see setRootItemVisible
  33817. */
  33818. bool isRootItemVisible() const throw() { return rootItemVisible; }
  33819. /** Sets whether items are open or closed by default.
  33820. Normally, items are closed until the user opens them, but you can use this
  33821. to make them default to being open until explicitly closed.
  33822. @see areItemsOpenByDefault
  33823. */
  33824. void setDefaultOpenness (const bool isOpenByDefault);
  33825. /** Returns true if the tree's items default to being open.
  33826. @see setDefaultOpenness
  33827. */
  33828. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  33829. /** This sets a flag to indicate that the tree can be used for multi-selection.
  33830. You can always select multiple items internally by calling the
  33831. TreeViewItem::setSelected() method, but this flag indicates whether the user
  33832. is allowed to multi-select by clicking on the tree.
  33833. By default it is disabled.
  33834. @see isMultiSelectEnabled
  33835. */
  33836. void setMultiSelectEnabled (const bool canMultiSelect);
  33837. /** Returns whether multi-select has been enabled for the tree.
  33838. @see setMultiSelectEnabled
  33839. */
  33840. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  33841. /** Sets a flag to indicate whether to hide the open/close buttons.
  33842. @see areOpenCloseButtonsVisible
  33843. */
  33844. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  33845. /** Returns whether open/close buttons are shown.
  33846. @see setOpenCloseButtonsVisible
  33847. */
  33848. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  33849. /** Deselects any items that are currently selected. */
  33850. void clearSelectedItems();
  33851. /** Returns the number of items that are currently selected.
  33852. @see getSelectedItem, clearSelectedItems
  33853. */
  33854. int getNumSelectedItems() const throw();
  33855. /** Returns one of the selected items in the tree.
  33856. @param index the index, 0 to (getNumSelectedItems() - 1)
  33857. */
  33858. TreeViewItem* getSelectedItem (const int index) const throw();
  33859. /** Returns the number of rows the tree is using.
  33860. This will depend on which items are open.
  33861. @see TreeViewItem::getRowNumberInTree()
  33862. */
  33863. int getNumRowsInTree() const;
  33864. /** Returns the item on a particular row of the tree.
  33865. If the index is out of range, this will return 0.
  33866. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  33867. */
  33868. TreeViewItem* getItemOnRow (int index) const;
  33869. /** Returns the item that contains a given y position.
  33870. The y is relative to the top of the TreeView component.
  33871. */
  33872. TreeViewItem* getItemAt (int yPosition) const throw();
  33873. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  33874. void scrollToKeepItemVisible (TreeViewItem* item);
  33875. /** Returns the treeview's Viewport object. */
  33876. Viewport* getViewport() const throw() { return viewport; }
  33877. /** Returns the number of pixels by which each nested level of the tree is indented.
  33878. @see setIndentSize
  33879. */
  33880. int getIndentSize() const throw() { return indentSize; }
  33881. /** Changes the distance by which each nested level of the tree is indented.
  33882. @see getIndentSize
  33883. */
  33884. void setIndentSize (const int newIndentSize);
  33885. /** Searches the tree for an item with the specified identifier.
  33886. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  33887. If no such item exists, this will return false. If the item is found, all of its items
  33888. will be automatically opened.
  33889. */
  33890. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  33891. /** Saves the current state of open/closed nodes so it can be restored later.
  33892. This takes a snapshot of which nodes have been explicitly opened or closed,
  33893. and records it as XML. To identify node objects it uses the
  33894. TreeViewItem::getUniqueName() method to create named paths. This
  33895. means that the same state of open/closed nodes can be restored to a
  33896. completely different instance of the tree, as long as it contains nodes
  33897. whose unique names are the same.
  33898. The caller is responsible for deleting the object that is returned.
  33899. @param alsoIncludeScrollPosition if this is true, the state will also
  33900. include information about where the
  33901. tree has been scrolled to vertically,
  33902. so this can also be restored
  33903. @see restoreOpennessState
  33904. */
  33905. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  33906. /** Restores a previously saved arrangement of open/closed nodes.
  33907. This will try to restore a snapshot of the tree's state that was created by
  33908. the getOpennessState() method. If any of the nodes named in the original
  33909. XML aren't present in this tree, they will be ignored.
  33910. @see getOpennessState
  33911. */
  33912. void restoreOpennessState (const XmlElement& newState);
  33913. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  33914. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33915. methods.
  33916. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33917. */
  33918. enum ColourIds
  33919. {
  33920. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  33921. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  33922. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  33923. };
  33924. /** @internal */
  33925. void paint (Graphics& g);
  33926. /** @internal */
  33927. void resized();
  33928. /** @internal */
  33929. bool keyPressed (const KeyPress& key);
  33930. /** @internal */
  33931. void colourChanged();
  33932. /** @internal */
  33933. void enablementChanged();
  33934. /** @internal */
  33935. bool isInterestedInFileDrag (const StringArray& files);
  33936. /** @internal */
  33937. void fileDragEnter (const StringArray& files, int x, int y);
  33938. /** @internal */
  33939. void fileDragMove (const StringArray& files, int x, int y);
  33940. /** @internal */
  33941. void fileDragExit (const StringArray& files);
  33942. /** @internal */
  33943. void filesDropped (const StringArray& files, int x, int y);
  33944. /** @internal */
  33945. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  33946. /** @internal */
  33947. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33948. /** @internal */
  33949. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33950. /** @internal */
  33951. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  33952. /** @internal */
  33953. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33954. juce_UseDebuggingNewOperator
  33955. private:
  33956. friend class TreeViewItem;
  33957. friend class TreeViewContentComponent;
  33958. Viewport* viewport;
  33959. CriticalSection nodeAlterationLock;
  33960. TreeViewItem* rootItem;
  33961. Component* dragInsertPointHighlight;
  33962. Component* dragTargetGroupHighlight;
  33963. int indentSize;
  33964. bool defaultOpenness : 1;
  33965. bool needsRecalculating : 1;
  33966. bool rootItemVisible : 1;
  33967. bool multiSelectEnabled : 1;
  33968. bool openCloseButtonsVisible : 1;
  33969. void itemsChanged() throw();
  33970. void handleAsyncUpdate();
  33971. void moveSelectedRow (int delta);
  33972. void updateButtonUnderMouse (const MouseEvent& e);
  33973. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  33974. void hideDragHighlight() throw();
  33975. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  33976. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  33977. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  33978. const StringArray& files, const String& sourceDescription,
  33979. Component* sourceComponent) const throw();
  33980. TreeView (const TreeView&);
  33981. const TreeView& operator= (const TreeView&);
  33982. };
  33983. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  33984. /********* End of inlined file: juce_TreeView.h *********/
  33985. #endif
  33986. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  33987. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  33988. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  33989. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  33990. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  33991. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  33992. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  33993. /********* Start of inlined file: juce_FileFilter.h *********/
  33994. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  33995. #define __JUCE_FILEFILTER_JUCEHEADER__
  33996. /**
  33997. Interface for deciding which files are suitable for something.
  33998. For example, this is used by DirectoryContentsList to select which files
  33999. go into the list.
  34000. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  34001. */
  34002. class JUCE_API FileFilter
  34003. {
  34004. public:
  34005. /** Creates a filter with the given description.
  34006. The description can be returned later with the getDescription() method.
  34007. */
  34008. FileFilter (const String& filterDescription);
  34009. /** Destructor. */
  34010. virtual ~FileFilter();
  34011. /** Returns the description that the filter was created with. */
  34012. const String& getDescription() const throw();
  34013. /** Should return true if this file is suitable for inclusion in whatever context
  34014. the object is being used.
  34015. */
  34016. virtual bool isFileSuitable (const File& file) const = 0;
  34017. /** Should return true if this directory is suitable for inclusion in whatever context
  34018. the object is being used.
  34019. */
  34020. virtual bool isDirectorySuitable (const File& file) const = 0;
  34021. protected:
  34022. String description;
  34023. };
  34024. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  34025. /********* End of inlined file: juce_FileFilter.h *********/
  34026. /********* Start of inlined file: juce_Image.h *********/
  34027. #ifndef __JUCE_IMAGE_JUCEHEADER__
  34028. #define __JUCE_IMAGE_JUCEHEADER__
  34029. /**
  34030. Holds a fixed-size bitmap.
  34031. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  34032. To draw into an image, create a Graphics object for it.
  34033. e.g. @code
  34034. // create a transparent 500x500 image..
  34035. Image myImage (Image::RGB, 500, 500, true);
  34036. Graphics g (myImage);
  34037. g.setColour (Colours::red);
  34038. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  34039. @endcode
  34040. Other useful ways to create an image are with the ImageCache class, or the
  34041. ImageFileFormat, which provides a way to load common image files.
  34042. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  34043. */
  34044. class JUCE_API Image
  34045. {
  34046. public:
  34047. enum PixelFormat
  34048. {
  34049. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  34050. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  34051. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  34052. };
  34053. /** Creates an in-memory image with a specified size and format.
  34054. To create an image that can use native OS rendering methods, see createNativeImage().
  34055. @param format the number of colour channels in the image
  34056. @param imageWidth the desired width of the image, in pixels - this value must be
  34057. greater than zero (otherwise a width of 1 will be used)
  34058. @param imageHeight the desired width of the image, in pixels - this value must be
  34059. greater than zero (otherwise a height of 1 will be used)
  34060. @param clearImage if true, the image will initially be cleared to black or transparent
  34061. black. If false, the image may contain random data, and the
  34062. user will have to deal with this
  34063. */
  34064. Image (const PixelFormat format,
  34065. const int imageWidth,
  34066. const int imageHeight,
  34067. const bool clearImage);
  34068. /** Creates a copy of another image.
  34069. @see createCopy
  34070. */
  34071. Image (const Image& other);
  34072. /** Destructor. */
  34073. virtual ~Image();
  34074. /** Tries to create an image that is uses native drawing methods when you render
  34075. onto it.
  34076. On some platforms this will just return a normal software-based image.
  34077. */
  34078. static Image* createNativeImage (const PixelFormat format,
  34079. const int imageWidth,
  34080. const int imageHeight,
  34081. const bool clearImage);
  34082. /** Returns the image's width (in pixels). */
  34083. int getWidth() const throw() { return imageWidth; }
  34084. /** Returns the image's height (in pixels). */
  34085. int getHeight() const throw() { return imageHeight; }
  34086. /** Returns a rectangle with the same size as this image.
  34087. The rectangle is always at position (0, 0).
  34088. */
  34089. const Rectangle getBounds() const throw() { return Rectangle (0, 0, imageWidth, imageHeight); }
  34090. /** Returns the image's pixel format. */
  34091. PixelFormat getFormat() const throw() { return format; }
  34092. /** True if the image's format is ARGB. */
  34093. bool isARGB() const throw() { return format == ARGB; }
  34094. /** True if the image's format is RGB. */
  34095. bool isRGB() const throw() { return format == RGB; }
  34096. /** True if the image contains an alpha-channel. */
  34097. bool hasAlphaChannel() const throw() { return format != RGB; }
  34098. /** Clears a section of the image with a given colour.
  34099. This won't do any alpha-blending - it just sets all pixels in the image to
  34100. the given colour (which may be non-opaque if the image has an alpha channel).
  34101. */
  34102. virtual void clear (int x, int y, int w, int h,
  34103. const Colour& colourToClearTo = Colour (0x00000000));
  34104. /** Returns a new image that's a copy of this one.
  34105. A new size for the copied image can be specified, or values less than
  34106. zero can be passed-in to use the image's existing dimensions.
  34107. It's up to the caller to delete the image when no longer needed.
  34108. */
  34109. virtual Image* createCopy (int newWidth = -1,
  34110. int newHeight = -1,
  34111. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  34112. /** Returns a new single-channel image which is a copy of the alpha-channel of this image.
  34113. */
  34114. virtual Image* createCopyOfAlphaChannel() const;
  34115. /** Returns the colour of one of the pixels in the image.
  34116. If the co-ordinates given are beyond the image's boundaries, this will
  34117. return Colours::transparentBlack.
  34118. (0, 0) is the image's top-left corner.
  34119. @see getAlphaAt, setPixelAt, blendPixelAt
  34120. */
  34121. virtual const Colour getPixelAt (const int x, const int y) const;
  34122. /** Sets the colour of one of the image's pixels.
  34123. If the co-ordinates are beyond the image's boundaries, then nothing will
  34124. happen.
  34125. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  34126. just replace the existing pixel with the given one. The colour's opacity
  34127. will be ignored if this image doesn't have an alpha-channel.
  34128. (0, 0) is the image's top-left corner.
  34129. @see blendPixelAt
  34130. */
  34131. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  34132. /** Changes the opacity of a pixel.
  34133. This only has an effect if the image has an alpha channel and if the
  34134. given co-ordinates are inside the image's boundary.
  34135. The multiplier must be in the range 0 to 1.0, and the current alpha
  34136. at the given co-ordinates will be multiplied by this value.
  34137. @see getAlphaAt, setPixelAt
  34138. */
  34139. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  34140. /** Changes the overall opacity of the image.
  34141. This will multiply the alpha value of each pixel in the image by the given
  34142. amount (limiting the resulting alpha values between 0 and 255). This allows
  34143. you to make an image more or less transparent.
  34144. If the image doesn't have an alpha channel, this won't have any effect.
  34145. */
  34146. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  34147. /** Changes all the colours to be shades of grey, based on their current luminosity.
  34148. */
  34149. virtual void desaturate();
  34150. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  34151. You should only use this class as a last resort - messing about with the internals of
  34152. an image is only recommended for people who really know what they're doing!
  34153. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  34154. hanging around while the image is being used elsewhere.
  34155. Depending on the way the image class is implemented, this may create a temporary buffer
  34156. which is copied back to the image when the object is deleted, or it may just get a pointer
  34157. directly into the image's raw data.
  34158. You can use the stride and data values in this class directly, but don't alter them!
  34159. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  34160. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  34161. */
  34162. class BitmapData
  34163. {
  34164. public:
  34165. BitmapData (Image& image, int x, int y, int w, int h, const bool needsToBeWritable);
  34166. BitmapData (const Image& image, int x, int y, int w, int h);
  34167. ~BitmapData();
  34168. /** Returns a pointer to the start of a line in the image.
  34169. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  34170. sure it's not out-of-range.
  34171. */
  34172. inline uint8* getLinePointer (const int y) const { return data + y * lineStride; }
  34173. /** Returns a pointer to a pixel in the image.
  34174. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  34175. not out-of-range.
  34176. */
  34177. inline uint8* getPixelPointer (const int x, const int y) const { return data + y * lineStride + x * pixelStride; }
  34178. uint8* data;
  34179. int lineStride, pixelStride, width, height;
  34180. private:
  34181. BitmapData (const BitmapData&);
  34182. const BitmapData& operator= (const BitmapData&);
  34183. };
  34184. /** Copies some pixel values to a rectangle of the image.
  34185. The format of the pixel data must match that of the image itself, and the
  34186. rectangle supplied must be within the image's bounds.
  34187. */
  34188. virtual void setPixelData (int destX, int destY, int destW, int destH,
  34189. const uint8* sourcePixelData, int sourceLineStride);
  34190. /** Copies a section of the image to somewhere else within itself.
  34191. */
  34192. virtual void moveImageSection (int destX, int destY,
  34193. int sourceX, int sourceY,
  34194. int width, int height);
  34195. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  34196. of the image.
  34197. @param result the list that will have the area added to it
  34198. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  34199. above this level will be considered opaque
  34200. */
  34201. void createSolidAreaMask (RectangleList& result,
  34202. const float alphaThreshold = 0.5f) const;
  34203. juce_UseDebuggingNewOperator
  34204. /** Creates a context suitable for drawing onto this image.
  34205. Don't call this method directly! It's used internally by the Graphics class.
  34206. */
  34207. virtual LowLevelGraphicsContext* createLowLevelContext();
  34208. protected:
  34209. friend class BitmapData;
  34210. const PixelFormat format;
  34211. const int imageWidth, imageHeight;
  34212. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  34213. Image (const PixelFormat format,
  34214. const int imageWidth,
  34215. const int imageHeight);
  34216. int pixelStride, lineStride;
  34217. HeapBlock <uint8> imageDataAllocated;
  34218. uint8* imageData;
  34219. private:
  34220. const Image& operator= (const Image&);
  34221. };
  34222. #endif // __JUCE_IMAGE_JUCEHEADER__
  34223. /********* End of inlined file: juce_Image.h *********/
  34224. /**
  34225. A class to asynchronously scan for details about the files in a directory.
  34226. This keeps a list of files and some information about them, using a background
  34227. thread to scan for more files. As files are found, it broadcasts change messages
  34228. to tell any listeners.
  34229. @see FileListComponent, FileBrowserComponent
  34230. */
  34231. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  34232. public TimeSliceClient
  34233. {
  34234. public:
  34235. /** Creates a directory list.
  34236. To set the directory it should point to, use setDirectory(), which will
  34237. also start it scanning for files on the background thread.
  34238. When the background thread finds and adds new files to this list, the
  34239. ChangeBroadcaster class will send a change message, so you can register
  34240. listeners and update them when the list changes.
  34241. @param fileFilter an optional filter to select which files are
  34242. included in the list. If this is 0, then all files
  34243. and directories are included. Make sure that the
  34244. filter doesn't get deleted during the lifetime of this
  34245. object
  34246. @param threadToUse a thread object that this list can use
  34247. to scan for files as a background task. Make sure
  34248. that the thread you give it has been started, or you
  34249. won't get any files!
  34250. */
  34251. DirectoryContentsList (const FileFilter* const fileFilter,
  34252. TimeSliceThread& threadToUse);
  34253. /** Destructor. */
  34254. ~DirectoryContentsList();
  34255. /** Sets the directory to look in for files.
  34256. If the directory that's passed in is different to the current one, this will
  34257. also start the background thread scanning it for files.
  34258. */
  34259. void setDirectory (const File& directory,
  34260. const bool includeDirectories,
  34261. const bool includeFiles);
  34262. /** Returns the directory that's currently being used. */
  34263. const File& getDirectory() const;
  34264. /** Clears the list, and stops the thread scanning for files. */
  34265. void clear();
  34266. /** Clears the list and restarts scanning the directory for files. */
  34267. void refresh();
  34268. /** True if the background thread hasn't yet finished scanning for files. */
  34269. bool isStillLoading() const;
  34270. /** Tells the list whether or not to ignore hidden files.
  34271. By default these are ignored.
  34272. */
  34273. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  34274. /** Returns true if hidden files are ignored.
  34275. @see setIgnoresHiddenFiles
  34276. */
  34277. bool ignoresHiddenFiles() const { return ignoreHiddenFiles; }
  34278. /** Contains cached information about one of the files in a DirectoryContentsList.
  34279. */
  34280. struct FileInfo
  34281. {
  34282. /** The filename.
  34283. This isn't a full pathname, it's just the last part of the path, same as you'd
  34284. get from File::getFileName().
  34285. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  34286. */
  34287. String filename;
  34288. /** File size in bytes. */
  34289. int64 fileSize;
  34290. /** File modification time.
  34291. As supplied by File::getLastModificationTime().
  34292. */
  34293. Time modificationTime;
  34294. /** File creation time.
  34295. As supplied by File::getCreationTime().
  34296. */
  34297. Time creationTime;
  34298. /** True if the file is a directory. */
  34299. bool isDirectory;
  34300. /** True if the file is read-only. */
  34301. bool isReadOnly;
  34302. };
  34303. /** Returns the number of files currently available in the list.
  34304. The info about one of these files can be retrieved with getFileInfo() or
  34305. getFile().
  34306. Obviously as the background thread runs and scans the directory for files, this
  34307. number will change.
  34308. @see getFileInfo, getFile
  34309. */
  34310. int getNumFiles() const;
  34311. /** Returns the cached information about one of the files in the list.
  34312. If the index is in-range, this will return true and will copy the file's details
  34313. to the structure that is passed-in.
  34314. If it returns false, then the index wasn't in range, and the structure won't
  34315. be affected.
  34316. @see getNumFiles, getFile
  34317. */
  34318. bool getFileInfo (const int index,
  34319. FileInfo& resultInfo) const;
  34320. /** Returns one of the files in the list.
  34321. @param index should be less than getNumFiles(). If this is out-of-range, the
  34322. return value will be File::nonexistent
  34323. @see getNumFiles, getFileInfo
  34324. */
  34325. const File getFile (const int index) const;
  34326. /** Returns the file filter being used.
  34327. The filter is specified in the constructor.
  34328. */
  34329. const FileFilter* getFilter() const { return fileFilter; }
  34330. /** @internal */
  34331. bool useTimeSlice();
  34332. /** @internal */
  34333. TimeSliceThread& getTimeSliceThread() { return thread; }
  34334. /** @internal */
  34335. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  34336. const DirectoryContentsList::FileInfo* const second);
  34337. juce_UseDebuggingNewOperator
  34338. private:
  34339. File root;
  34340. const FileFilter* fileFilter;
  34341. TimeSliceThread& thread;
  34342. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  34343. CriticalSection fileListLock;
  34344. OwnedArray <FileInfo> files;
  34345. void* volatile fileFindHandle;
  34346. bool volatile shouldStop;
  34347. void changed();
  34348. bool checkNextFile (bool& hasChanged);
  34349. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  34350. const int64 fileSize, const Time& modTime,
  34351. const Time& creationTime, const bool isReadOnly);
  34352. DirectoryContentsList (const DirectoryContentsList&);
  34353. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  34354. };
  34355. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  34356. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  34357. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  34358. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34359. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34360. /**
  34361. A listener for user selection events in a file browser.
  34362. This is used by a FileBrowserComponent or FileListComponent.
  34363. */
  34364. class JUCE_API FileBrowserListener
  34365. {
  34366. public:
  34367. /** Destructor. */
  34368. virtual ~FileBrowserListener();
  34369. /** Callback when the user selects a different file in the browser. */
  34370. virtual void selectionChanged() = 0;
  34371. /** Callback when the user clicks on a file in the browser. */
  34372. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  34373. /** Callback when the user double-clicks on a file in the browser. */
  34374. virtual void fileDoubleClicked (const File& file) = 0;
  34375. };
  34376. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34377. /********* End of inlined file: juce_FileBrowserListener.h *********/
  34378. /**
  34379. A base class for components that display a list of the files in a directory.
  34380. @see DirectoryContentsList
  34381. */
  34382. class JUCE_API DirectoryContentsDisplayComponent
  34383. {
  34384. public:
  34385. /**
  34386. */
  34387. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  34388. /** Destructor. */
  34389. virtual ~DirectoryContentsDisplayComponent();
  34390. /** Returns the number of files the user has got selected.
  34391. @see getSelectedFile
  34392. */
  34393. virtual int getNumSelectedFiles() const = 0;
  34394. /** Returns one of the files that the user has currently selected.
  34395. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  34396. @see getNumSelectedFiles
  34397. */
  34398. virtual const File getSelectedFile (int index) const = 0;
  34399. /** Scrolls this view to the top. */
  34400. virtual void scrollToTop() = 0;
  34401. /** Adds a listener to be told when files are selected or clicked.
  34402. @see removeListener
  34403. */
  34404. void addListener (FileBrowserListener* const listener) throw();
  34405. /** Removes a listener.
  34406. @see addListener
  34407. */
  34408. void removeListener (FileBrowserListener* const listener) throw();
  34409. /** A set of colour IDs to use to change the colour of various aspects of the label.
  34410. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34411. methods.
  34412. Note that you can also use the constants from TextEditor::ColourIds to change the
  34413. colour of the text editor that is opened when a label is editable.
  34414. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34415. */
  34416. enum ColourIds
  34417. {
  34418. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  34419. textColourId = 0x1000541, /**< The colour for the text. */
  34420. };
  34421. /** @internal */
  34422. void sendSelectionChangeMessage();
  34423. /** @internal */
  34424. void sendDoubleClickMessage (const File& file);
  34425. /** @internal */
  34426. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  34427. juce_UseDebuggingNewOperator
  34428. protected:
  34429. DirectoryContentsList& fileList;
  34430. SortedSet <void*> listeners;
  34431. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  34432. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  34433. };
  34434. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  34435. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  34436. #endif
  34437. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  34438. #endif
  34439. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34440. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  34441. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34442. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34443. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  34444. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  34445. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  34446. /**
  34447. Base class for components that live inside a file chooser dialog box and
  34448. show previews of the files that get selected.
  34449. One of these allows special extra information to be displayed for files
  34450. in a dialog box as the user selects them. Each time the current file or
  34451. directory is changed, the selectedFileChanged() method will be called
  34452. to allow it to update itself appropriately.
  34453. @see FileChooser, ImagePreviewComponent
  34454. */
  34455. class JUCE_API FilePreviewComponent : public Component
  34456. {
  34457. public:
  34458. /** Creates a FilePreviewComponent. */
  34459. FilePreviewComponent();
  34460. /** Destructor. */
  34461. ~FilePreviewComponent();
  34462. /** Called to indicate that the user's currently selected file has changed.
  34463. @param newSelectedFile the newly selected file or directory, which may be
  34464. File::nonexistent if none is selected.
  34465. */
  34466. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  34467. juce_UseDebuggingNewOperator
  34468. private:
  34469. FilePreviewComponent (const FilePreviewComponent&);
  34470. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  34471. };
  34472. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  34473. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  34474. /**
  34475. A component for browsing and selecting a file or directory to open or save.
  34476. This contains a FileListComponent and adds various boxes and controls for
  34477. navigating and selecting a file. It can work in different modes so that it can
  34478. be used for loading or saving a file, or for choosing a directory.
  34479. @see FileChooserDialogBox, FileChooser, FileListComponent
  34480. */
  34481. class JUCE_API FileBrowserComponent : public Component,
  34482. public ChangeBroadcaster,
  34483. private FileBrowserListener,
  34484. private TextEditorListener,
  34485. private ButtonListener,
  34486. private ComboBoxListener,
  34487. private FileFilter
  34488. {
  34489. public:
  34490. /** Various options for the browser.
  34491. A combination of these is passed into the FileBrowserComponent constructor.
  34492. */
  34493. enum FileChooserFlags
  34494. {
  34495. openMode = 1, /**< specifies that the component should allow the user to
  34496. choose an existing file with the intention of opening it. */
  34497. saveMode = 2, /**< specifies that the component should allow the user to specify
  34498. the name of a file that will be used to save something. */
  34499. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  34500. conjunction with canSelectDirectories). */
  34501. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  34502. conjuction with canSelectFiles). */
  34503. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  34504. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  34505. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  34506. };
  34507. /** Creates a FileBrowserComponent.
  34508. @param flags A combination of flags from the FileChooserFlags enumeration,
  34509. used to specify the component's behaviour. The flags must contain
  34510. either openMode or saveMode, and canSelectFiles and/or
  34511. canSelectDirectories.
  34512. @param initialFileOrDirectory The file or directory that should be selected when
  34513. the component begins. If this is File::nonexistent,
  34514. a default directory will be chosen.
  34515. @param fileFilter an optional filter to use to determine which files
  34516. are shown. If this is 0 then all files are displayed. Note
  34517. that a pointer is kept internally to this object, so
  34518. make sure that it is not deleted before the browser object
  34519. is deleted.
  34520. @param previewComp an optional preview component that will be used to
  34521. show previews of files that the user selects
  34522. */
  34523. FileBrowserComponent (int flags,
  34524. const File& initialFileOrDirectory,
  34525. const FileFilter* fileFilter,
  34526. FilePreviewComponent* previewComp);
  34527. /** Destructor. */
  34528. ~FileBrowserComponent();
  34529. /** Returns the number of files that the user has got selected.
  34530. If multiple select isn't active, this will only be 0 or 1. To get the complete
  34531. list of files they've chosen, pass an index to getCurrentFile().
  34532. */
  34533. int getNumSelectedFiles() const throw();
  34534. /** Returns one of the files that the user has chosen.
  34535. If the box has multi-select enabled, the index lets you specify which of the files
  34536. to get - see getNumSelectedFiles() to find out how many files were chosen.
  34537. @see getHighlightedFile
  34538. */
  34539. const File getSelectedFile (int index) const throw();
  34540. /** Returns true if the currently selected file(s) are usable.
  34541. This can be used to decide whether the user can press "ok" for the
  34542. current file. What it does depends on the mode, so for example in an "open"
  34543. mode, this only returns true if a file has been selected and if it exists.
  34544. In a "save" mode, a non-existent file would also be valid.
  34545. */
  34546. bool currentFileIsValid() const;
  34547. /** This returns the last item in the view that the user has highlighted.
  34548. This may be different from getCurrentFile(), which returns the value
  34549. that is shown in the filename box, and if there are multiple selections,
  34550. this will only return one of them.
  34551. @see getCurrentFile
  34552. */
  34553. const File getHighlightedFile() const throw();
  34554. /** Returns the directory whose contents are currently being shown in the listbox. */
  34555. const File getRoot() const;
  34556. /** Changes the directory that's being shown in the listbox. */
  34557. void setRoot (const File& newRootDirectory);
  34558. /** Equivalent to pressing the "up" button to browse the parent directory. */
  34559. void goUp();
  34560. /** Refreshes the directory that's currently being listed. */
  34561. void refresh();
  34562. /** Returns a verb to describe what should happen when the file is accepted.
  34563. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  34564. mode, it'll be "Save", etc.
  34565. */
  34566. virtual const String getActionVerb() const;
  34567. /** Returns true if the saveMode flag was set when this component was created.
  34568. */
  34569. bool isSaveMode() const throw();
  34570. /** Adds a listener to be told when the user selects and clicks on files.
  34571. @see removeListener
  34572. */
  34573. void addListener (FileBrowserListener* const listener) throw();
  34574. /** Removes a listener.
  34575. @see addListener
  34576. */
  34577. void removeListener (FileBrowserListener* const listener) throw();
  34578. /** @internal */
  34579. void resized();
  34580. /** @internal */
  34581. void buttonClicked (Button* b);
  34582. /** @internal */
  34583. void comboBoxChanged (ComboBox*);
  34584. /** @internal */
  34585. void textEditorTextChanged (TextEditor& editor);
  34586. /** @internal */
  34587. void textEditorReturnKeyPressed (TextEditor& editor);
  34588. /** @internal */
  34589. void textEditorEscapeKeyPressed (TextEditor& editor);
  34590. /** @internal */
  34591. void textEditorFocusLost (TextEditor& editor);
  34592. /** @internal */
  34593. bool keyPressed (const KeyPress& key);
  34594. /** @internal */
  34595. void selectionChanged();
  34596. /** @internal */
  34597. void fileClicked (const File& f, const MouseEvent& e);
  34598. /** @internal */
  34599. void fileDoubleClicked (const File& f);
  34600. /** @internal */
  34601. bool isFileSuitable (const File& file) const;
  34602. /** @internal */
  34603. bool isDirectorySuitable (const File&) const;
  34604. /** @internal */
  34605. FilePreviewComponent* getPreviewComponent() const throw();
  34606. juce_UseDebuggingNewOperator
  34607. protected:
  34608. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  34609. private:
  34610. ScopedPointer <DirectoryContentsList> fileList;
  34611. const FileFilter* fileFilter;
  34612. int flags;
  34613. File currentRoot;
  34614. OwnedArray <File> chosenFiles;
  34615. SortedSet <void*> listeners;
  34616. DirectoryContentsDisplayComponent* fileListComponent;
  34617. FilePreviewComponent* previewComp;
  34618. ComboBox* currentPathBox;
  34619. TextEditor* filenameBox;
  34620. Button* goUpButton;
  34621. TimeSliceThread thread;
  34622. void sendListenerChangeMessage();
  34623. bool isFileOrDirSuitable (const File& f) const;
  34624. FileBrowserComponent (const FileBrowserComponent&);
  34625. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  34626. };
  34627. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34628. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  34629. #endif
  34630. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34631. #endif
  34632. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  34633. /********* Start of inlined file: juce_FileChooser.h *********/
  34634. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  34635. #define __JUCE_FILECHOOSER_JUCEHEADER__
  34636. /**
  34637. Creates a dialog box to choose a file or directory to load or save.
  34638. To use a FileChooser:
  34639. - create one (as a local stack variable is the neatest way)
  34640. - call one of its browseFor.. methods
  34641. - if this returns true, the user has selected a file, so you can retrieve it
  34642. with the getResult() method.
  34643. e.g. @code
  34644. void loadMooseFile()
  34645. {
  34646. FileChooser myChooser ("Please select the moose you want to load...",
  34647. File::getSpecialLocation (File::userHomeDirectory),
  34648. "*.moose");
  34649. if (myChooser.browseForFileToOpen())
  34650. {
  34651. File mooseFile (myChooser.getResult());
  34652. loadMoose (mooseFile);
  34653. }
  34654. }
  34655. @endcode
  34656. */
  34657. class JUCE_API FileChooser
  34658. {
  34659. public:
  34660. /** Creates a FileChooser.
  34661. After creating one of these, use one of the browseFor... methods to display it.
  34662. @param dialogBoxTitle a text string to display in the dialog box to
  34663. tell the user what's going on
  34664. @param initialFileOrDirectory the file or directory that should be selected when
  34665. the dialog box opens. If this parameter is set to
  34666. File::nonexistent, a sensible default directory
  34667. will be used instead.
  34668. @param filePatternsAllowed a set of file patterns to specify which files can be
  34669. selected - each pattern should be separated by a
  34670. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  34671. empty string means that all files are allowed
  34672. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  34673. possible; if false, then a Juce-based browser dialog
  34674. box will always be used
  34675. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  34676. */
  34677. FileChooser (const String& dialogBoxTitle,
  34678. const File& initialFileOrDirectory = File::nonexistent,
  34679. const String& filePatternsAllowed = String::empty,
  34680. const bool useOSNativeDialogBox = true);
  34681. /** Destructor. */
  34682. ~FileChooser();
  34683. /** Shows a dialog box to choose a file to open.
  34684. This will display the dialog box modally, using an "open file" mode, so that
  34685. it won't allow non-existent files or directories to be chosen.
  34686. @param previewComponent an optional component to display inside the dialog
  34687. box to show special info about the files that the user
  34688. is browsing. The component will not be deleted by this
  34689. object, so the caller must take care of it.
  34690. @returns true if the user selected a file, in which case, use the getResult()
  34691. method to find out what it was. Returns false if they cancelled instead.
  34692. @see browseForFileToSave, browseForDirectory
  34693. */
  34694. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  34695. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  34696. The files that are returned can be obtained by calling getResults(). See
  34697. browseForFileToOpen() for more info about the behaviour of this method.
  34698. */
  34699. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  34700. /** Shows a dialog box to choose a file to save.
  34701. This will display the dialog box modally, using an "save file" mode, so it
  34702. will allow non-existent files to be chosen, but not directories.
  34703. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  34704. the user if they're sure they want to overwrite a file that already
  34705. exists
  34706. @returns true if the user chose a file and pressed 'ok', in which case, use
  34707. the getResult() method to find out what the file was. Returns false
  34708. if they cancelled instead.
  34709. @see browseForFileToOpen, browseForDirectory
  34710. */
  34711. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  34712. /** Shows a dialog box to choose a directory.
  34713. This will display the dialog box modally, using an "open directory" mode, so it
  34714. will only allow directories to be returned, not files.
  34715. @returns true if the user chose a directory and pressed 'ok', in which case, use
  34716. the getResult() method to find out what they chose. Returns false
  34717. if they cancelled instead.
  34718. @see browseForFileToOpen, browseForFileToSave
  34719. */
  34720. bool browseForDirectory();
  34721. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  34722. The files that are returned can be obtained by calling getResults(). See
  34723. browseForFileToOpen() for more info about the behaviour of this method.
  34724. */
  34725. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  34726. /** Returns the last file that was chosen by one of the browseFor methods.
  34727. After calling the appropriate browseFor... method, this method lets you
  34728. find out what file or directory they chose.
  34729. Note that the file returned is only valid if the browse method returned true (i.e.
  34730. if the user pressed 'ok' rather than cancelling).
  34731. If you're using a multiple-file select, then use the getResults() method instead,
  34732. to obtain the list of all files chosen.
  34733. @see getResults
  34734. */
  34735. const File getResult() const;
  34736. /** Returns a list of all the files that were chosen during the last call to a
  34737. browse method.
  34738. This array may be empty if no files were chosen, or can contain multiple entries
  34739. if multiple files were chosen.
  34740. @see getResult
  34741. */
  34742. const OwnedArray <File>& getResults() const;
  34743. juce_UseDebuggingNewOperator
  34744. private:
  34745. String title, filters;
  34746. File startingFile;
  34747. OwnedArray <File> results;
  34748. bool useNativeDialogBox;
  34749. bool showDialog (const bool selectsDirectories,
  34750. const bool selectsFiles,
  34751. const bool isSave,
  34752. const bool warnAboutOverwritingExistingFiles,
  34753. const bool selectMultipleFiles,
  34754. FilePreviewComponent* const previewComponent);
  34755. static void showPlatformDialog (OwnedArray<File>& results,
  34756. const String& title,
  34757. const File& file,
  34758. const String& filters,
  34759. bool selectsDirectories,
  34760. bool selectsFiles,
  34761. bool isSave,
  34762. bool warnAboutOverwritingExistingFiles,
  34763. bool selectMultipleFiles,
  34764. FilePreviewComponent* previewComponent);
  34765. };
  34766. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  34767. /********* End of inlined file: juce_FileChooser.h *********/
  34768. #endif
  34769. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  34770. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  34771. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  34772. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  34773. /********* Start of inlined file: juce_ResizableWindow.h *********/
  34774. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  34775. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  34776. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  34777. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34778. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34779. /********* Start of inlined file: juce_DropShadower.h *********/
  34780. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  34781. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  34782. /**
  34783. Adds a drop-shadow to a component.
  34784. This object creates and manages a set of components which sit around a
  34785. component, creating a gaussian shadow around it. The components will track
  34786. the position of the component and if it's brought to the front they'll also
  34787. follow this.
  34788. For desktop windows you don't need to use this class directly - just
  34789. set the Component::windowHasDropShadow flag when calling
  34790. Component::addToDesktop(), and the system will create one of these if it's
  34791. needed (which it obviously isn't on the Mac, for example).
  34792. */
  34793. class JUCE_API DropShadower : public ComponentListener
  34794. {
  34795. public:
  34796. /** Creates a DropShadower.
  34797. @param alpha the opacity of the shadows, from 0 to 1.0
  34798. @param xOffset the horizontal displacement of the shadow, in pixels
  34799. @param yOffset the vertical displacement of the shadow, in pixels
  34800. @param blurRadius the radius of the blur to use for creating the shadow
  34801. */
  34802. DropShadower (const float alpha = 0.5f,
  34803. const int xOffset = 1,
  34804. const int yOffset = 5,
  34805. const float blurRadius = 10.0f);
  34806. /** Destructor. */
  34807. virtual ~DropShadower();
  34808. /** Attaches the DropShadower to the component you want to shadow. */
  34809. void setOwner (Component* componentToFollow);
  34810. /** @internal */
  34811. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34812. /** @internal */
  34813. void componentBroughtToFront (Component& component);
  34814. /** @internal */
  34815. void componentChildrenChanged (Component& component);
  34816. /** @internal */
  34817. void componentParentHierarchyChanged (Component& component);
  34818. /** @internal */
  34819. void componentVisibilityChanged (Component& component);
  34820. juce_UseDebuggingNewOperator
  34821. private:
  34822. Component* owner;
  34823. int numShadows;
  34824. Component* shadowWindows[4];
  34825. Image* shadowImageSections[12];
  34826. const int shadowEdge, xOffset, yOffset;
  34827. const float alpha, blurRadius;
  34828. bool inDestructor, reentrant;
  34829. void updateShadows();
  34830. void setShadowImage (Image* const src,
  34831. const int num,
  34832. const int w, const int h,
  34833. const int sx, const int sy);
  34834. void bringShadowWindowsToFront();
  34835. void deleteShadowWindows();
  34836. DropShadower (const DropShadower&);
  34837. const DropShadower& operator= (const DropShadower&);
  34838. };
  34839. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  34840. /********* End of inlined file: juce_DropShadower.h *********/
  34841. /**
  34842. A base class for top-level windows.
  34843. This class is used for components that are considered a major part of your
  34844. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  34845. etc. Things like menus that pop up briefly aren't derived from it.
  34846. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  34847. could itself be the child of another component.
  34848. The class manages a list of all instances of top-level windows that are in use,
  34849. and each one is also given the concept of being "active". The active window is
  34850. one that is actively being used by the user. This isn't quite the same as the
  34851. component with the keyboard focus, because there may be a popup menu or other
  34852. temporary window which gets keyboard focus while the active top level window is
  34853. unchanged.
  34854. A top-level window also has an optional drop-shadow.
  34855. @see ResizableWindow, DocumentWindow, DialogWindow
  34856. */
  34857. class JUCE_API TopLevelWindow : public Component
  34858. {
  34859. public:
  34860. /** Creates a TopLevelWindow.
  34861. @param name the name to give the component
  34862. @param addToDesktop if true, the window will be automatically added to the
  34863. desktop; if false, you can use it as a child component
  34864. */
  34865. TopLevelWindow (const String& name,
  34866. const bool addToDesktop);
  34867. /** Destructor. */
  34868. ~TopLevelWindow();
  34869. /** True if this is currently the TopLevelWindow that is actively being used.
  34870. This isn't quite the same as having keyboard focus, because the focus may be
  34871. on a child component or a temporary pop-up menu, etc, while this window is
  34872. still considered to be active.
  34873. @see activeWindowStatusChanged
  34874. */
  34875. bool isActiveWindow() const throw() { return windowIsActive_; }
  34876. /** This will set the bounds of the window so that it's centred in front of another
  34877. window.
  34878. If your app has a few windows open and want to pop up a dialog box for one of
  34879. them, you can use this to show it in front of the relevent parent window, which
  34880. is a bit neater than just having it appear in the middle of the screen.
  34881. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  34882. be used instead. If no window is focused, it'll just default to the middle of the
  34883. screen.
  34884. */
  34885. void centreAroundComponent (Component* componentToCentreAround,
  34886. const int width, const int height);
  34887. /** Turns the drop-shadow on and off. */
  34888. void setDropShadowEnabled (const bool useShadow);
  34889. /** Sets whether an OS-native title bar will be used, or a Juce one.
  34890. @see isUsingNativeTitleBar
  34891. */
  34892. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  34893. /** Returns true if the window is currently using an OS-native title bar.
  34894. @see setUsingNativeTitleBar
  34895. */
  34896. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  34897. /** Returns the number of TopLevelWindow objects currently in use.
  34898. @see getTopLevelWindow
  34899. */
  34900. static int getNumTopLevelWindows() throw();
  34901. /** Returns one of the TopLevelWindow objects currently in use.
  34902. The index is 0 to (getNumTopLevelWindows() - 1).
  34903. */
  34904. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  34905. /** Returns the currently-active top level window.
  34906. There might not be one, of course, so this can return 0.
  34907. */
  34908. static TopLevelWindow* getActiveTopLevelWindow() throw();
  34909. juce_UseDebuggingNewOperator
  34910. /** @internal */
  34911. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  34912. protected:
  34913. /** This callback happens when this window becomes active or inactive.
  34914. @see isActiveWindow
  34915. */
  34916. virtual void activeWindowStatusChanged();
  34917. /** @internal */
  34918. void focusOfChildComponentChanged (FocusChangeType cause);
  34919. /** @internal */
  34920. void parentHierarchyChanged();
  34921. /** @internal */
  34922. void visibilityChanged();
  34923. /** @internal */
  34924. virtual int getDesktopWindowStyleFlags() const;
  34925. /** @internal */
  34926. void recreateDesktopWindow();
  34927. private:
  34928. friend class TopLevelWindowManager;
  34929. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  34930. ScopedPointer <DropShadower> shadower;
  34931. void setWindowActive (const bool isNowActive) throw();
  34932. TopLevelWindow (const TopLevelWindow&);
  34933. const TopLevelWindow& operator= (const TopLevelWindow&);
  34934. };
  34935. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34936. /********* End of inlined file: juce_TopLevelWindow.h *********/
  34937. /********* Start of inlined file: juce_ComponentDragger.h *********/
  34938. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34939. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34940. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  34941. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34942. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34943. /**
  34944. A class that imposes restrictions on a Component's size or position.
  34945. This is used by classes such as ResizableCornerComponent,
  34946. ResizableBorderComponent and ResizableWindow.
  34947. The base class can impose some basic size and position limits, but you can
  34948. also subclass this for custom uses.
  34949. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  34950. */
  34951. class JUCE_API ComponentBoundsConstrainer
  34952. {
  34953. public:
  34954. /** When first created, the object will not impose any restrictions on the components. */
  34955. ComponentBoundsConstrainer() throw();
  34956. /** Destructor. */
  34957. virtual ~ComponentBoundsConstrainer();
  34958. /** Imposes a minimum width limit. */
  34959. void setMinimumWidth (const int minimumWidth) throw();
  34960. /** Returns the current minimum width. */
  34961. int getMinimumWidth() const throw() { return minW; }
  34962. /** Imposes a maximum width limit. */
  34963. void setMaximumWidth (const int maximumWidth) throw();
  34964. /** Returns the current maximum width. */
  34965. int getMaximumWidth() const throw() { return maxW; }
  34966. /** Imposes a minimum height limit. */
  34967. void setMinimumHeight (const int minimumHeight) throw();
  34968. /** Returns the current minimum height. */
  34969. int getMinimumHeight() const throw() { return minH; }
  34970. /** Imposes a maximum height limit. */
  34971. void setMaximumHeight (const int maximumHeight) throw();
  34972. /** Returns the current maximum height. */
  34973. int getMaximumHeight() const throw() { return maxH; }
  34974. /** Imposes a minimum width and height limit. */
  34975. void setMinimumSize (const int minimumWidth,
  34976. const int minimumHeight) throw();
  34977. /** Imposes a maximum width and height limit. */
  34978. void setMaximumSize (const int maximumWidth,
  34979. const int maximumHeight) throw();
  34980. /** Set all the maximum and minimum dimensions. */
  34981. void setSizeLimits (const int minimumWidth,
  34982. const int minimumHeight,
  34983. const int maximumWidth,
  34984. const int maximumHeight) throw();
  34985. /** Sets the amount by which the component is allowed to go off-screen.
  34986. The values indicate how many pixels must remain on-screen when dragged off
  34987. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  34988. when the component goes off the top of the screen, its y-position will be
  34989. clipped so that there are always at least 10 pixels on-screen. In other words,
  34990. the lowest y-position it can take would be (10 - the component's height).
  34991. If you pass 0 or less for one of these amounts, the component is allowed
  34992. to move beyond that edge completely, with no restrictions at all.
  34993. If you pass a very large number (i.e. larger that the dimensions of the
  34994. component itself), then the component won't be allowed to overlap that
  34995. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  34996. the component will bump into the left side of the screen and go no further.
  34997. */
  34998. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  34999. const int minimumWhenOffTheLeft,
  35000. const int minimumWhenOffTheBottom,
  35001. const int minimumWhenOffTheRight) throw();
  35002. /** Specifies a width-to-height ratio that the resizer should always maintain.
  35003. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  35004. will always be maintained as this multiple of the height.
  35005. @see setResizeLimits
  35006. */
  35007. void setFixedAspectRatio (const double widthOverHeight) throw();
  35008. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  35009. If no aspect ratio is being enforced, this will return 0.
  35010. */
  35011. double getFixedAspectRatio() const throw();
  35012. /** This callback changes the given co-ordinates to impose whatever the current
  35013. constraints are set to be.
  35014. @param x the x position that should be examined and adjusted
  35015. @param y the y position that should be examined and adjusted
  35016. @param w the width that should be examined and adjusted
  35017. @param h the height that should be examined and adjusted
  35018. @param previousBounds the component's current size
  35019. @param limits the region in which the component can be positioned
  35020. @param isStretchingTop whether the top edge of the component is being resized
  35021. @param isStretchingLeft whether the left edge of the component is being resized
  35022. @param isStretchingBottom whether the bottom edge of the component is being resized
  35023. @param isStretchingRight whether the right edge of the component is being resized
  35024. */
  35025. virtual void checkBounds (int& x, int& y, int& w, int& h,
  35026. const Rectangle& previousBounds,
  35027. const Rectangle& limits,
  35028. const bool isStretchingTop,
  35029. const bool isStretchingLeft,
  35030. const bool isStretchingBottom,
  35031. const bool isStretchingRight);
  35032. /** This callback happens when the resizer is about to start dragging. */
  35033. virtual void resizeStart();
  35034. /** This callback happens when the resizer has finished dragging. */
  35035. virtual void resizeEnd();
  35036. /** Checks the given bounds, and then sets the component to the corrected size. */
  35037. void setBoundsForComponent (Component* const component,
  35038. int x, int y, int w, int h,
  35039. const bool isStretchingTop,
  35040. const bool isStretchingLeft,
  35041. const bool isStretchingBottom,
  35042. const bool isStretchingRight);
  35043. /** Performs a check on the current size of a component, and moves or resizes
  35044. it if it fails the constraints.
  35045. */
  35046. void checkComponentBounds (Component* component);
  35047. /** Called by setBoundsForComponent() to apply a new constrained size to a
  35048. component.
  35049. By default this just calls setBounds(), but it virtual in case it's needed for
  35050. extremely cunning purposes.
  35051. */
  35052. virtual void applyBoundsToComponent (Component* component,
  35053. int x, int y, int w, int h);
  35054. juce_UseDebuggingNewOperator
  35055. private:
  35056. int minW, maxW, minH, maxH;
  35057. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  35058. double aspectRatio;
  35059. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  35060. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  35061. };
  35062. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  35063. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  35064. /**
  35065. An object to take care of the logic for dragging components around with the mouse.
  35066. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  35067. then in your mouseDrag() callback, call dragComponent().
  35068. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  35069. to limit the component's position and keep it on-screen.
  35070. e.g. @code
  35071. class MyDraggableComp
  35072. {
  35073. ComponentDragger myDragger;
  35074. void mouseDown (const MouseEvent& e)
  35075. {
  35076. myDragger.startDraggingComponent (this, 0);
  35077. }
  35078. void mouseDrag (const MouseEvent& e)
  35079. {
  35080. myDragger.dragComponent (this, e);
  35081. }
  35082. };
  35083. @endcode
  35084. */
  35085. class JUCE_API ComponentDragger
  35086. {
  35087. public:
  35088. /** Creates a ComponentDragger. */
  35089. ComponentDragger();
  35090. /** Destructor. */
  35091. virtual ~ComponentDragger();
  35092. /** Call this from your component's mouseDown() method, to prepare for dragging.
  35093. @param componentToDrag the component that you want to drag
  35094. @param constrainer a constrainer object to use to keep the component
  35095. from going offscreen
  35096. @see dragComponent
  35097. */
  35098. void startDraggingComponent (Component* const componentToDrag,
  35099. ComponentBoundsConstrainer* constrainer);
  35100. /** Call this from your mouseDrag() callback to move the component.
  35101. This will move the component, but will first check the validity of the
  35102. component's new position using the checkPosition() method, which you
  35103. can override if you need to enforce special positioning limits on the
  35104. component.
  35105. @param componentToDrag the component that you want to drag
  35106. @param e the current mouse-drag event
  35107. @see dragComponent
  35108. */
  35109. void dragComponent (Component* const componentToDrag,
  35110. const MouseEvent& e);
  35111. juce_UseDebuggingNewOperator
  35112. private:
  35113. ComponentBoundsConstrainer* constrainer;
  35114. int originalX, originalY;
  35115. };
  35116. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  35117. /********* End of inlined file: juce_ComponentDragger.h *********/
  35118. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35119. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35120. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35121. /**
  35122. A component that resizes its parent window when dragged.
  35123. This component forms a frame around the edge of a component, allowing it to
  35124. be dragged by the edges or corners to resize it - like the way windows are
  35125. resized in MSWindows or Linux.
  35126. To use it, just add it to your component, making it fill the entire parent component
  35127. (there's a mouse hit-test that only traps mouse-events which land around the
  35128. edge of the component, so it's even ok to put it on top of any other components
  35129. you're using). Make sure you rescale the resizer component to fill the parent
  35130. each time the parent's size changes.
  35131. @see ResizableCornerComponent
  35132. */
  35133. class JUCE_API ResizableBorderComponent : public Component
  35134. {
  35135. public:
  35136. /** Creates a resizer.
  35137. Pass in the target component which you want to be resized when this one is
  35138. dragged.
  35139. The target component will usually be a parent of the resizer component, but this
  35140. isn't mandatory.
  35141. Remember that when the target component is resized, it'll need to move and
  35142. resize this component to keep it in place, as this won't happen automatically.
  35143. If the constrainer parameter is non-zero, then this object will be used to enforce
  35144. limits on the size and position that the component can be stretched to. Make sure
  35145. that the constrainer isn't deleted while still in use by this object.
  35146. @see ComponentBoundsConstrainer
  35147. */
  35148. ResizableBorderComponent (Component* const componentToResize,
  35149. ComponentBoundsConstrainer* const constrainer);
  35150. /** Destructor. */
  35151. ~ResizableBorderComponent();
  35152. /** Specifies how many pixels wide the draggable edges of this component are.
  35153. @see getBorderThickness
  35154. */
  35155. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35156. /** Returns the number of pixels wide that the draggable edges of this component are.
  35157. @see setBorderThickness
  35158. */
  35159. const BorderSize getBorderThickness() const throw();
  35160. juce_UseDebuggingNewOperator
  35161. protected:
  35162. /** @internal */
  35163. void paint (Graphics& g);
  35164. /** @internal */
  35165. void mouseEnter (const MouseEvent& e);
  35166. /** @internal */
  35167. void mouseMove (const MouseEvent& e);
  35168. /** @internal */
  35169. void mouseDown (const MouseEvent& e);
  35170. /** @internal */
  35171. void mouseDrag (const MouseEvent& e);
  35172. /** @internal */
  35173. void mouseUp (const MouseEvent& e);
  35174. /** @internal */
  35175. bool hitTest (int x, int y);
  35176. private:
  35177. Component* const component;
  35178. ComponentBoundsConstrainer* constrainer;
  35179. BorderSize borderSize;
  35180. int originalX, originalY, originalW, originalH;
  35181. int mouseZone;
  35182. void updateMouseZone (const MouseEvent& e) throw();
  35183. ResizableBorderComponent (const ResizableBorderComponent&);
  35184. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35185. };
  35186. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35187. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35188. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35189. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35190. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35191. /** A component that resizes a parent window when dragged.
  35192. This is the small triangular stripey resizer component you get in the bottom-right
  35193. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35194. a larger component and it will automatically resize its parent when it gets dragged
  35195. around.
  35196. @see ResizableFrameComponent
  35197. */
  35198. class JUCE_API ResizableCornerComponent : public Component
  35199. {
  35200. public:
  35201. /** Creates a resizer.
  35202. Pass in the target component which you want to be resized when this one is
  35203. dragged.
  35204. The target component will usually be a parent of the resizer component, but this
  35205. isn't mandatory.
  35206. Remember that when the target component is resized, it'll need to move and
  35207. resize this component to keep it in place, as this won't happen automatically.
  35208. If the constrainer parameter is non-zero, then this object will be used to enforce
  35209. limits on the size and position that the component can be stretched to. Make sure
  35210. that the constrainer isn't deleted while still in use by this object. If you
  35211. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35212. @see ComponentBoundsConstrainer
  35213. */
  35214. ResizableCornerComponent (Component* const componentToResize,
  35215. ComponentBoundsConstrainer* const constrainer);
  35216. /** Destructor. */
  35217. ~ResizableCornerComponent();
  35218. juce_UseDebuggingNewOperator
  35219. protected:
  35220. /** @internal */
  35221. void paint (Graphics& g);
  35222. /** @internal */
  35223. void mouseDown (const MouseEvent& e);
  35224. /** @internal */
  35225. void mouseDrag (const MouseEvent& e);
  35226. /** @internal */
  35227. void mouseUp (const MouseEvent& e);
  35228. /** @internal */
  35229. bool hitTest (int x, int y);
  35230. private:
  35231. Component* const component;
  35232. ComponentBoundsConstrainer* constrainer;
  35233. int originalX, originalY, originalW, originalH;
  35234. ResizableCornerComponent (const ResizableCornerComponent&);
  35235. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35236. };
  35237. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35238. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35239. /**
  35240. A base class for top-level windows that can be dragged around and resized.
  35241. To add content to the window, use its setContentComponent() method to
  35242. give it a component that will remain positioned inside it (leaving a gap around
  35243. the edges for a border).
  35244. It's not advisable to add child components directly to a ResizableWindow: put them
  35245. inside your content component instead. And overriding methods like resized(), moved(), etc
  35246. is also not recommended - instead override these methods for your content component.
  35247. (If for some obscure reason you do need to override these methods, always remember to
  35248. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35249. decorations correctly).
  35250. By default resizing isn't enabled - use the setResizable() method to enable it and
  35251. to choose the style of resizing to use.
  35252. @see TopLevelWindow
  35253. */
  35254. class JUCE_API ResizableWindow : public TopLevelWindow
  35255. {
  35256. public:
  35257. /** Creates a ResizableWindow.
  35258. This constructor doesn't specify a background colour, so the LookAndFeel's default
  35259. background colour will be used.
  35260. @param name the name to give the component
  35261. @param addToDesktop if true, the window will be automatically added to the
  35262. desktop; if false, you can use it as a child component
  35263. */
  35264. ResizableWindow (const String& name,
  35265. const bool addToDesktop);
  35266. /** Creates a ResizableWindow.
  35267. @param name the name to give the component
  35268. @param backgroundColour the colour to use for filling the window's background.
  35269. @param addToDesktop if true, the window will be automatically added to the
  35270. desktop; if false, you can use it as a child component
  35271. */
  35272. ResizableWindow (const String& name,
  35273. const Colour& backgroundColour,
  35274. const bool addToDesktop);
  35275. /** Destructor.
  35276. If a content component has been set with setContentComponent(), it
  35277. will be deleted.
  35278. */
  35279. ~ResizableWindow();
  35280. /** Returns the colour currently being used for the window's background.
  35281. As a convenience the window will fill itself with this colour, but you
  35282. can override the paint() method if you need more customised behaviour.
  35283. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  35284. @see setBackgroundColour
  35285. */
  35286. const Colour getBackgroundColour() const throw();
  35287. /** Changes the colour currently being used for the window's background.
  35288. As a convenience the window will fill itself with this colour, but you
  35289. can override the paint() method if you need more customised behaviour.
  35290. Note that the opaque state of this window is altered by this call to reflect
  35291. the opacity of the colour passed-in. On window systems which can't support
  35292. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35293. be using this class as a base for a semi-transparent component anyway).
  35294. You can also use the ResizableWindow::backgroundColourId colour id to set
  35295. this colour.
  35296. @see getBackgroundColour
  35297. */
  35298. void setBackgroundColour (const Colour& newColour);
  35299. /** Make the window resizable or fixed.
  35300. @param shouldBeResizable whether it's resizable at all
  35301. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35302. bottom-right; if false, it'll use a ResizableBorderComponent
  35303. around the edge
  35304. @see setResizeLimits, isResizable
  35305. */
  35306. void setResizable (const bool shouldBeResizable,
  35307. const bool useBottomRightCornerResizer);
  35308. /** True if resizing is enabled.
  35309. @see setResizable
  35310. */
  35311. bool isResizable() const throw();
  35312. /** This sets the maximum and minimum sizes for the window.
  35313. If the window's current size is outside these limits, it will be resized to
  35314. make sure it's within them.
  35315. Calling setBounds() on the component will bypass any size checking - it's only when
  35316. the window is being resized by the user that these values are enforced.
  35317. @see setResizable, setFixedAspectRatio
  35318. */
  35319. void setResizeLimits (const int newMinimumWidth,
  35320. const int newMinimumHeight,
  35321. const int newMaximumWidth,
  35322. const int newMaximumHeight) throw();
  35323. /** Returns the bounds constrainer object that this window is using.
  35324. You can access this to change its properties.
  35325. */
  35326. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35327. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35328. A pointer to the object you pass in will be kept, but it won't be deleted
  35329. by this object, so it's the caller's responsiblity to manage it.
  35330. If you pass 0, then no contraints will be placed on the positioning of the window.
  35331. */
  35332. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35333. /** Calls the window's setBounds method, after first checking these bounds
  35334. with the current constrainer.
  35335. @see setConstrainer
  35336. */
  35337. void setBoundsConstrained (int x, int y, int width, int height);
  35338. /** Returns true if the window is currently in full-screen mode.
  35339. @see setFullScreen
  35340. */
  35341. bool isFullScreen() const;
  35342. /** Puts the window into full-screen mode, or restores it to its normal size.
  35343. If true, the window will become full-screen; if false, it will return to the
  35344. last size it was before being made full-screen.
  35345. @see isFullScreen
  35346. */
  35347. void setFullScreen (const bool shouldBeFullScreen);
  35348. /** Returns true if the window is currently minimised.
  35349. @see setMinimised
  35350. */
  35351. bool isMinimised() const;
  35352. /** Minimises the window, or restores it to its previous position and size.
  35353. When being un-minimised, it'll return to the last position and size it
  35354. was in before being minimised.
  35355. @see isMinimised
  35356. */
  35357. void setMinimised (const bool shouldMinimise);
  35358. /** Returns a string which encodes the window's current size and position.
  35359. This string will encapsulate the window's size, position, and whether it's
  35360. in full-screen mode. It's intended for letting your application save and
  35361. restore a window's position.
  35362. Use the restoreWindowStateFromString() to restore from a saved state.
  35363. @see restoreWindowStateFromString
  35364. */
  35365. const String getWindowStateAsString();
  35366. /** Restores the window to a previously-saved size and position.
  35367. This restores the window's size, positon and full-screen status from an
  35368. string that was previously created with the getWindowStateAsString()
  35369. method.
  35370. @returns false if the string wasn't a valid window state
  35371. @see getWindowStateAsString
  35372. */
  35373. bool restoreWindowStateFromString (const String& previousState);
  35374. /** Returns the current content component.
  35375. This will be the component set by setContentComponent(), or 0 if none
  35376. has yet been specified.
  35377. @see setContentComponent
  35378. */
  35379. Component* getContentComponent() const throw() { return contentComponent; }
  35380. /** Changes the current content component.
  35381. This sets a component that will be placed in the centre of the ResizableWindow,
  35382. (leaving a space around the edge for the border).
  35383. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35384. with addChildComponent(). Instead, add them to the content component.
  35385. @param newContentComponent the new component to use (or null to not use one) - this
  35386. component will be deleted either when replaced by another call
  35387. to this method, or when the ResizableWindow is deleted.
  35388. To remove a content component without deleting it, use
  35389. setContentComponent (0, false).
  35390. @param deleteOldOne if true, the previous content component will be deleted; if
  35391. false, the previous component will just be removed without
  35392. deleting it.
  35393. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35394. it always fits around the size of the content component. If false, the
  35395. new content will be resized to fit the current space available.
  35396. */
  35397. void setContentComponent (Component* const newContentComponent,
  35398. const bool deleteOldOne = true,
  35399. const bool resizeToFit = false);
  35400. /** Changes the window so that the content component ends up with the specified size.
  35401. This is basically a setSize call on the window, but which adds on the borders,
  35402. so you can specify the content component's target size.
  35403. */
  35404. void setContentComponentSize (int width, int height);
  35405. /** A set of colour IDs to use to change the colour of various aspects of the window.
  35406. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35407. methods.
  35408. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35409. */
  35410. enum ColourIds
  35411. {
  35412. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  35413. };
  35414. juce_UseDebuggingNewOperator
  35415. protected:
  35416. /** @internal */
  35417. void paint (Graphics& g);
  35418. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35419. void moved();
  35420. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35421. void resized();
  35422. /** @internal */
  35423. void mouseDown (const MouseEvent& e);
  35424. /** @internal */
  35425. void mouseDrag (const MouseEvent& e);
  35426. /** @internal */
  35427. void lookAndFeelChanged();
  35428. /** @internal */
  35429. void childBoundsChanged (Component* child);
  35430. /** @internal */
  35431. void parentSizeChanged();
  35432. /** @internal */
  35433. void visibilityChanged();
  35434. /** @internal */
  35435. void activeWindowStatusChanged();
  35436. /** @internal */
  35437. int getDesktopWindowStyleFlags() const;
  35438. /** Returns the width of the border to use around the window.
  35439. @see getContentComponentBorder
  35440. */
  35441. virtual const BorderSize getBorderThickness();
  35442. /** Returns the insets to use when positioning the content component.
  35443. @see getBorderThickness
  35444. */
  35445. virtual const BorderSize getContentComponentBorder();
  35446. #ifdef JUCE_DEBUG
  35447. /** Overridden to warn people about adding components directly to this component
  35448. instead of using setContentComponent().
  35449. If you know what you're doing and are sure you really want to add a component, specify
  35450. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35451. */
  35452. void addChildComponent (Component* const child, int zOrder = -1);
  35453. /** Overridden to warn people about adding components directly to this component
  35454. instead of using setContentComponent().
  35455. If you know what you're doing and are sure you really want to add a component, specify
  35456. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35457. */
  35458. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35459. #endif
  35460. ScopedPointer <ResizableCornerComponent> resizableCorner;
  35461. ScopedPointer <ResizableBorderComponent> resizableBorder;
  35462. private:
  35463. ScopedPointer <Component> contentComponent;
  35464. bool resizeToFitContent, fullscreen;
  35465. ComponentDragger dragger;
  35466. Rectangle lastNonFullScreenPos;
  35467. ComponentBoundsConstrainer defaultConstrainer;
  35468. ComponentBoundsConstrainer* constrainer;
  35469. #ifdef JUCE_DEBUG
  35470. bool hasBeenResized;
  35471. #endif
  35472. void updateLastPos();
  35473. ResizableWindow (const ResizableWindow&);
  35474. const ResizableWindow& operator= (const ResizableWindow&);
  35475. // (xxx remove these eventually)
  35476. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35477. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35478. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35479. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35480. };
  35481. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35482. /********* End of inlined file: juce_ResizableWindow.h *********/
  35483. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  35484. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  35485. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  35486. /**
  35487. A glyph from a particular font, with a particular size, style,
  35488. typeface and position.
  35489. @see GlyphArrangement, Font
  35490. */
  35491. class JUCE_API PositionedGlyph
  35492. {
  35493. public:
  35494. /** Returns the character the glyph represents. */
  35495. juce_wchar getCharacter() const { return character; }
  35496. /** Checks whether the glyph is actually empty. */
  35497. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  35498. /** Returns the position of the glyph's left-hand edge. */
  35499. float getLeft() const { return x; }
  35500. /** Returns the position of the glyph's right-hand edge. */
  35501. float getRight() const { return x + w; }
  35502. /** Returns the y position of the glyph's baseline. */
  35503. float getBaselineY() const { return y; }
  35504. /** Returns the y position of the top of the glyph. */
  35505. float getTop() const { return y - font.getAscent(); }
  35506. /** Returns the y position of the bottom of the glyph. */
  35507. float getBottom() const { return y + font.getDescent(); }
  35508. /** Shifts the glyph's position by a relative amount. */
  35509. void moveBy (const float deltaX,
  35510. const float deltaY);
  35511. /** Draws the glyph into a graphics context. */
  35512. void draw (const Graphics& g) const;
  35513. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  35514. void draw (const Graphics& g, const AffineTransform& transform) const;
  35515. /** Returns the path for this glyph.
  35516. @param path the glyph's outline will be appended to this path
  35517. */
  35518. void createPath (Path& path) const;
  35519. /** Checks to see if a point lies within this glyph. */
  35520. bool hitTest (float x, float y) const;
  35521. juce_UseDebuggingNewOperator
  35522. private:
  35523. friend class GlyphArrangement;
  35524. float x, y, w;
  35525. Font font;
  35526. juce_wchar character;
  35527. int glyph;
  35528. PositionedGlyph();
  35529. };
  35530. /**
  35531. A set of glyphs, each with a position.
  35532. You can create a GlyphArrangement, text to it and then draw it onto a
  35533. graphics context. It's used internally by the text methods in the
  35534. Graphics class, but can be used directly if more control is needed.
  35535. @see Font, PositionedGlyph
  35536. */
  35537. class JUCE_API GlyphArrangement
  35538. {
  35539. public:
  35540. /** Creates an empty arrangement. */
  35541. GlyphArrangement();
  35542. /** Takes a copy of another arrangement. */
  35543. GlyphArrangement (const GlyphArrangement& other);
  35544. /** Copies another arrangement onto this one.
  35545. To add another arrangement without clearing this one, use addGlyphArrangement().
  35546. */
  35547. const GlyphArrangement& operator= (const GlyphArrangement& other);
  35548. /** Destructor. */
  35549. ~GlyphArrangement();
  35550. /** Returns the total number of glyphs in the arrangement. */
  35551. int getNumGlyphs() const { return glyphs.size(); }
  35552. /** Returns one of the glyphs from the arrangement.
  35553. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  35554. careful not to pass an out-of-range index here, as it
  35555. doesn't do any bounds-checking.
  35556. */
  35557. PositionedGlyph& getGlyph (const int index) const;
  35558. /** Clears all text from the arrangement and resets it.
  35559. */
  35560. void clear();
  35561. /** Appends a line of text to the arrangement.
  35562. This will add the text as a single line, where x is the left-hand edge of the
  35563. first character, and y is the position for the text's baseline.
  35564. If the text contains new-lines or carriage-returns, this will ignore them - use
  35565. addJustifiedText() to add multi-line arrangements.
  35566. */
  35567. void addLineOfText (const Font& font,
  35568. const String& text,
  35569. const float x,
  35570. const float y);
  35571. /** Adds a line of text, truncating it if it's wider than a specified size.
  35572. This is the same as addLineOfText(), but if the line's width exceeds the value
  35573. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  35574. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  35575. */
  35576. void addCurtailedLineOfText (const Font& font,
  35577. const String& text,
  35578. float x,
  35579. const float y,
  35580. const float maxWidthPixels,
  35581. const bool useEllipsis);
  35582. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  35583. This will add text to the arrangement, breaking it into new lines either where there
  35584. is a new-line or carriage-return character in the text, or where a line's width
  35585. exceeds the value set in maxLineWidth.
  35586. Each line that is added will be laid out using the flags set in horizontalLayout, so
  35587. the lines can be left- or right-justified, or centred horizontally in the space
  35588. between x and (x + maxLineWidth).
  35589. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  35590. lines will be placed below it, separated by a distance of font.getHeight().
  35591. */
  35592. void addJustifiedText (const Font& font,
  35593. const String& text,
  35594. float x, float y,
  35595. const float maxLineWidth,
  35596. const Justification& horizontalLayout);
  35597. /** Tries to fit some text withing a given space.
  35598. This does its best to make the given text readable within the specified rectangle,
  35599. so it useful for labelling things.
  35600. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  35601. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  35602. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  35603. it's been truncated.
  35604. A Justification parameter lets you specify how the text is laid out within the rectangle,
  35605. both horizontally and vertically.
  35606. @see Graphics::drawFittedText
  35607. */
  35608. void addFittedText (const Font& font,
  35609. const String& text,
  35610. const float x, const float y,
  35611. const float width, const float height,
  35612. const Justification& layout,
  35613. int maximumLinesToUse,
  35614. const float minimumHorizontalScale = 0.7f);
  35615. /** Appends another glyph arrangement to this one. */
  35616. void addGlyphArrangement (const GlyphArrangement& other);
  35617. /** Draws this glyph arrangement to a graphics context.
  35618. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  35619. method, which renders the glyphs as filled vectors.
  35620. */
  35621. void draw (const Graphics& g) const;
  35622. /** Draws this glyph arrangement to a graphics context.
  35623. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  35624. method for non-transformed arrangements.
  35625. */
  35626. void draw (const Graphics& g, const AffineTransform& transform) const;
  35627. /** Converts the set of glyphs into a path.
  35628. @param path the glyphs' outlines will be appended to this path
  35629. */
  35630. void createPath (Path& path) const;
  35631. /** Looks for a glyph that contains the given co-ordinate.
  35632. @returns the index of the glyph, or -1 if none were found.
  35633. */
  35634. int findGlyphIndexAt (float x, float y) const;
  35635. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  35636. @param startIndex the first glyph to test
  35637. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  35638. startIndex will be included
  35639. @param left on return, the leftmost co-ordinate of the rectangle
  35640. @param top on return, the top co-ordinate of the rectangle
  35641. @param right on return, the rightmost co-ordinate of the rectangle
  35642. @param bottom on return, the bottom co-ordinate of the rectangle
  35643. @param includeWhitespace if true, the extent of any whitespace characters will also
  35644. be taken into account
  35645. */
  35646. void getBoundingBox (int startIndex,
  35647. int numGlyphs,
  35648. float& left,
  35649. float& top,
  35650. float& right,
  35651. float& bottom,
  35652. const bool includeWhitespace) const;
  35653. /** Shifts a set of glyphs by a given amount.
  35654. @param startIndex the first glyph to transform
  35655. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  35656. startIndex will be used
  35657. @param deltaX the amount to add to their x-positions
  35658. @param deltaY the amount to add to their y-positions
  35659. */
  35660. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  35661. const float deltaX,
  35662. const float deltaY);
  35663. /** Removes a set of glyphs from the arrangement.
  35664. @param startIndex the first glyph to remove
  35665. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  35666. startIndex will be deleted
  35667. */
  35668. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  35669. /** Expands or compresses a set of glyphs horizontally.
  35670. @param startIndex the first glyph to transform
  35671. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  35672. startIndex will be used
  35673. @param horizontalScaleFactor how much to scale their horizontal width by
  35674. */
  35675. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  35676. const float horizontalScaleFactor);
  35677. /** Justifies a set of glyphs within a given space.
  35678. This moves the glyphs as a block so that the whole thing is located within the
  35679. given rectangle with the specified layout.
  35680. If the Justification::horizontallyJustified flag is specified, each line will
  35681. be stretched out to fill the specified width.
  35682. */
  35683. void justifyGlyphs (const int startIndex, const int numGlyphs,
  35684. const float x,
  35685. const float y,
  35686. const float width,
  35687. const float height,
  35688. const Justification& justification);
  35689. juce_UseDebuggingNewOperator
  35690. private:
  35691. OwnedArray <PositionedGlyph> glyphs;
  35692. int insertEllipsis (const Font& font, const float maxXPos, const int startIndex, int endIndex);
  35693. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  35694. const Justification& justification, float minimumHorizontalScale);
  35695. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth);
  35696. };
  35697. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  35698. /********* End of inlined file: juce_GlyphArrangement.h *********/
  35699. /**
  35700. A file open/save dialog box.
  35701. This is a Juce-based file dialog box; to use a native file chooser, see the
  35702. FileChooser class.
  35703. To use one of these, create it and call its show() method. e.g.
  35704. @code
  35705. {
  35706. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  35707. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  35708. File::nonexistent,
  35709. &wildcardFilter,
  35710. 0);
  35711. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  35712. T("Please choose some kind of file that you want to open..."),
  35713. browser,
  35714. getLookAndFeel().alertWindowBackground);
  35715. if (dialogBox.show())
  35716. {
  35717. File selectedFile = browser.getCurrentFile();
  35718. ...
  35719. }
  35720. }
  35721. @endcode
  35722. @see FileChooser
  35723. */
  35724. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  35725. public ButtonListener,
  35726. public FileBrowserListener
  35727. {
  35728. public:
  35729. /** Creates a file chooser box.
  35730. @param title the main title to show at the top of the box
  35731. @param instructions an optional longer piece of text to show below the title in
  35732. a smaller font, describing in more detail what's required.
  35733. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  35734. box. Make sure you delete this after (but not before!) the
  35735. dialog box has been deleted.
  35736. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  35737. if they try to select a file that already exists. (This
  35738. flag is only used when saving files)
  35739. @param backgroundColour the background colour for the top level window
  35740. @see FileBrowserComponent, FilePreviewComponent
  35741. */
  35742. FileChooserDialogBox (const String& title,
  35743. const String& instructions,
  35744. FileBrowserComponent& browserComponent,
  35745. const bool warnAboutOverwritingExistingFiles,
  35746. const Colour& backgroundColour);
  35747. /** Destructor. */
  35748. ~FileChooserDialogBox();
  35749. /** Displays and runs the dialog box modally.
  35750. This will show the box with the specified size, returning true if the user
  35751. pressed 'ok', or false if they cancelled.
  35752. Leave the width or height as 0 to use the default size
  35753. */
  35754. bool show (int width = 0,int height = 0);
  35755. /** @internal */
  35756. void buttonClicked (Button* button);
  35757. /** @internal */
  35758. void closeButtonPressed();
  35759. /** @internal */
  35760. void selectionChanged();
  35761. /** @internal */
  35762. void fileClicked (const File& file, const MouseEvent& e);
  35763. /** @internal */
  35764. void fileDoubleClicked (const File& file);
  35765. juce_UseDebuggingNewOperator
  35766. private:
  35767. class ContentComponent : public Component
  35768. {
  35769. public:
  35770. ContentComponent();
  35771. ~ContentComponent();
  35772. void paint (Graphics& g);
  35773. void resized();
  35774. String instructions;
  35775. GlyphArrangement text;
  35776. FileBrowserComponent* chooserComponent;
  35777. FilePreviewComponent* previewComponent;
  35778. TextButton* okButton;
  35779. TextButton* cancelButton;
  35780. };
  35781. ContentComponent* content;
  35782. const bool warnAboutOverwritingExistingFiles;
  35783. FileChooserDialogBox (const FileChooserDialogBox&);
  35784. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  35785. };
  35786. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  35787. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  35788. #endif
  35789. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  35790. #endif
  35791. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35792. /********* Start of inlined file: juce_FileListComponent.h *********/
  35793. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35794. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35795. /**
  35796. A component that displays the files in a directory as a listbox.
  35797. This implements the DirectoryContentsDisplayComponent base class so that
  35798. it can be used in a FileBrowserComponent.
  35799. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  35800. class and the FileBrowserListener class.
  35801. @see DirectoryContentsList, FileTreeComponent
  35802. */
  35803. class JUCE_API FileListComponent : public ListBox,
  35804. public DirectoryContentsDisplayComponent,
  35805. private ListBoxModel,
  35806. private ChangeListener
  35807. {
  35808. public:
  35809. /** Creates a listbox to show the contents of a specified directory.
  35810. */
  35811. FileListComponent (DirectoryContentsList& listToShow);
  35812. /** Destructor. */
  35813. ~FileListComponent();
  35814. /** Returns the number of files the user has got selected.
  35815. @see getSelectedFile
  35816. */
  35817. int getNumSelectedFiles() const;
  35818. /** Returns one of the files that the user has currently selected.
  35819. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  35820. @see getNumSelectedFiles
  35821. */
  35822. const File getSelectedFile (int index = 0) const;
  35823. /** Scrolls to the top of the list. */
  35824. void scrollToTop();
  35825. /** @internal */
  35826. void changeListenerCallback (void*);
  35827. /** @internal */
  35828. int getNumRows();
  35829. /** @internal */
  35830. void paintListBoxItem (int, Graphics&, int, int, bool);
  35831. /** @internal */
  35832. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35833. /** @internal */
  35834. void selectedRowsChanged (int lastRowSelected);
  35835. /** @internal */
  35836. void deleteKeyPressed (int currentSelectedRow);
  35837. /** @internal */
  35838. void returnKeyPressed (int currentSelectedRow);
  35839. juce_UseDebuggingNewOperator
  35840. private:
  35841. FileListComponent (const FileListComponent&);
  35842. const FileListComponent& operator= (const FileListComponent&);
  35843. File lastDirectory;
  35844. };
  35845. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35846. /********* End of inlined file: juce_FileListComponent.h *********/
  35847. #endif
  35848. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35849. /********* Start of inlined file: juce_FilenameComponent.h *********/
  35850. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35851. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35852. class FilenameComponent;
  35853. /**
  35854. Listens for events happening to a FilenameComponent.
  35855. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  35856. register one of these objects for event callbacks when the filename is changed.
  35857. @see FilenameComponent
  35858. */
  35859. class JUCE_API FilenameComponentListener
  35860. {
  35861. public:
  35862. /** Destructor. */
  35863. virtual ~FilenameComponentListener() {}
  35864. /** This method is called after the FilenameComponent's file has been changed. */
  35865. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  35866. };
  35867. /**
  35868. Shows a filename as an editable text box, with a 'browse' button and a
  35869. drop-down list for recently selected files.
  35870. A handy component for dialogue boxes where you want the user to be able to
  35871. select a file or directory.
  35872. Attach an FilenameComponentListener using the addListener() method, and it will
  35873. get called each time the user changes the filename, either by browsing for a file
  35874. and clicking 'ok', or by typing a new filename into the box and pressing return.
  35875. @see FileChooser, ComboBox
  35876. */
  35877. class JUCE_API FilenameComponent : public Component,
  35878. public SettableTooltipClient,
  35879. public FileDragAndDropTarget,
  35880. private AsyncUpdater,
  35881. private ButtonListener,
  35882. private ComboBoxListener
  35883. {
  35884. public:
  35885. /** Creates a FilenameComponent.
  35886. @param name the name for this component.
  35887. @param currentFile the file to initially show in the box
  35888. @param canEditFilename if true, the user can manually edit the filename; if false,
  35889. they can only change it by browsing for a new file
  35890. @param isDirectory if true, the file will be treated as a directory, and
  35891. an appropriate directory browser used
  35892. @param isForSaving if true, the file browser will allow non-existent files to
  35893. be picked, as the file is assumed to be used for saving rather
  35894. than loading
  35895. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  35896. If an empty string is passed in, then the pattern is assumed to be "*"
  35897. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  35898. to any filenames that are entered or chosen
  35899. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  35900. will only appear if the initial file isn't valid)
  35901. */
  35902. FilenameComponent (const String& name,
  35903. const File& currentFile,
  35904. const bool canEditFilename,
  35905. const bool isDirectory,
  35906. const bool isForSaving,
  35907. const String& fileBrowserWildcard,
  35908. const String& enforcedSuffix,
  35909. const String& textWhenNothingSelected);
  35910. /** Destructor. */
  35911. ~FilenameComponent();
  35912. /** Returns the currently displayed filename. */
  35913. const File getCurrentFile() const;
  35914. /** Changes the current filename.
  35915. If addToRecentlyUsedList is true, the filename will also be added to the
  35916. drop-down list of recent files.
  35917. If sendChangeNotification is false, then the listeners won't be told of the
  35918. change.
  35919. */
  35920. void setCurrentFile (File newFile,
  35921. const bool addToRecentlyUsedList,
  35922. const bool sendChangeNotification = true);
  35923. /** Changes whether the use can type into the filename box.
  35924. */
  35925. void setFilenameIsEditable (const bool shouldBeEditable);
  35926. /** Sets a file or directory to be the default starting point for the browser to show.
  35927. This is only used if the current file hasn't been set.
  35928. */
  35929. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  35930. /** Returns all the entries on the recent files list.
  35931. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  35932. state of this list.
  35933. @see setRecentlyUsedFilenames
  35934. */
  35935. const StringArray getRecentlyUsedFilenames() const;
  35936. /** Sets all the entries on the recent files list.
  35937. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  35938. state of this list.
  35939. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  35940. */
  35941. void setRecentlyUsedFilenames (const StringArray& filenames);
  35942. /** Adds an entry to the recently-used files dropdown list.
  35943. If the file is already in the list, it will be moved to the top. A limit
  35944. is also placed on the number of items that are kept in the list.
  35945. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  35946. */
  35947. void addRecentlyUsedFile (const File& file);
  35948. /** Changes the limit for the number of files that will be stored in the recent-file list.
  35949. */
  35950. void setMaxNumberOfRecentFiles (const int newMaximum);
  35951. /** Changes the text shown on the 'browse' button.
  35952. By default this button just says "..." but you can change it. The button itself
  35953. can be changed using the look-and-feel classes, so it might not actually have any
  35954. text on it.
  35955. */
  35956. void setBrowseButtonText (const String& browseButtonText);
  35957. /** Adds a listener that will be called when the selected file is changed. */
  35958. void addListener (FilenameComponentListener* const listener) throw();
  35959. /** Removes a previously-registered listener. */
  35960. void removeListener (FilenameComponentListener* const listener) throw();
  35961. /** Gives the component a tooltip. */
  35962. void setTooltip (const String& newTooltip);
  35963. /** @internal */
  35964. void paintOverChildren (Graphics& g);
  35965. /** @internal */
  35966. void resized();
  35967. /** @internal */
  35968. void lookAndFeelChanged();
  35969. /** @internal */
  35970. bool isInterestedInFileDrag (const StringArray& files);
  35971. /** @internal */
  35972. void filesDropped (const StringArray& files, int, int);
  35973. /** @internal */
  35974. void fileDragEnter (const StringArray& files, int, int);
  35975. /** @internal */
  35976. void fileDragExit (const StringArray& files);
  35977. juce_UseDebuggingNewOperator
  35978. private:
  35979. ComboBox* filenameBox;
  35980. String lastFilename;
  35981. Button* browseButton;
  35982. int maxRecentFiles;
  35983. bool isDir, isSaving, isFileDragOver;
  35984. String wildcard, enforcedSuffix, browseButtonText;
  35985. SortedSet <void*> listeners;
  35986. File defaultBrowseFile;
  35987. void comboBoxChanged (ComboBox*);
  35988. void buttonClicked (Button* button);
  35989. void handleAsyncUpdate();
  35990. FilenameComponent (const FilenameComponent&);
  35991. const FilenameComponent& operator= (const FilenameComponent&);
  35992. };
  35993. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35994. /********* End of inlined file: juce_FilenameComponent.h *********/
  35995. #endif
  35996. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  35997. #endif
  35998. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  35999. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  36000. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  36001. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  36002. /**
  36003. Shows a set of file paths in a list, allowing them to be added, removed or
  36004. re-ordered.
  36005. @see FileSearchPath
  36006. */
  36007. class JUCE_API FileSearchPathListComponent : public Component,
  36008. public SettableTooltipClient,
  36009. public FileDragAndDropTarget,
  36010. private ButtonListener,
  36011. private ListBoxModel
  36012. {
  36013. public:
  36014. /** Creates an empty FileSearchPathListComponent.
  36015. */
  36016. FileSearchPathListComponent();
  36017. /** Destructor. */
  36018. ~FileSearchPathListComponent();
  36019. /** Returns the path as it is currently shown. */
  36020. const FileSearchPath& getPath() const throw() { return path; }
  36021. /** Changes the current path. */
  36022. void setPath (const FileSearchPath& newPath);
  36023. /** Sets a file or directory to be the default starting point for the browser to show.
  36024. This is only used if the current file hasn't been set.
  36025. */
  36026. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  36027. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36028. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36029. methods.
  36030. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36031. */
  36032. enum ColourIds
  36033. {
  36034. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  36035. Make this transparent if you don't want the background to be filled. */
  36036. };
  36037. /** @internal */
  36038. int getNumRows();
  36039. /** @internal */
  36040. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  36041. /** @internal */
  36042. void deleteKeyPressed (int lastRowSelected);
  36043. /** @internal */
  36044. void returnKeyPressed (int lastRowSelected);
  36045. /** @internal */
  36046. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  36047. /** @internal */
  36048. void selectedRowsChanged (int lastRowSelected);
  36049. /** @internal */
  36050. void resized();
  36051. /** @internal */
  36052. void paint (Graphics& g);
  36053. /** @internal */
  36054. bool isInterestedInFileDrag (const StringArray& files);
  36055. /** @internal */
  36056. void filesDropped (const StringArray& files, int, int);
  36057. /** @internal */
  36058. void buttonClicked (Button* button);
  36059. juce_UseDebuggingNewOperator
  36060. private:
  36061. FileSearchPath path;
  36062. File defaultBrowseTarget;
  36063. ListBox* listBox;
  36064. Button* addButton;
  36065. Button* removeButton;
  36066. Button* changeButton;
  36067. Button* upButton;
  36068. Button* downButton;
  36069. void changed() throw();
  36070. void updateButtons() throw();
  36071. FileSearchPathListComponent (const FileSearchPathListComponent&);
  36072. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  36073. };
  36074. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  36075. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  36076. #endif
  36077. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  36078. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  36079. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  36080. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  36081. /**
  36082. A component that displays the files in a directory as a treeview.
  36083. This implements the DirectoryContentsDisplayComponent base class so that
  36084. it can be used in a FileBrowserComponent.
  36085. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  36086. class and the FileBrowserListener class.
  36087. @see DirectoryContentsList, FileListComponent
  36088. */
  36089. class JUCE_API FileTreeComponent : public TreeView,
  36090. public DirectoryContentsDisplayComponent
  36091. {
  36092. public:
  36093. /** Creates a listbox to show the contents of a specified directory.
  36094. */
  36095. FileTreeComponent (DirectoryContentsList& listToShow);
  36096. /** Destructor. */
  36097. ~FileTreeComponent();
  36098. /** Returns the number of files the user has got selected.
  36099. @see getSelectedFile
  36100. */
  36101. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  36102. /** Returns one of the files that the user has currently selected.
  36103. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  36104. @see getNumSelectedFiles
  36105. */
  36106. const File getSelectedFile (int index = 0) const;
  36107. /** Scrolls the list to the top. */
  36108. void scrollToTop();
  36109. /** Setting a name for this allows tree items to be dragged.
  36110. The string that you pass in here will be returned by the getDragSourceDescription()
  36111. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  36112. */
  36113. void setDragAndDropDescription (const String& description) throw();
  36114. /** Returns the last value that was set by setDragAndDropDescription().
  36115. */
  36116. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  36117. juce_UseDebuggingNewOperator
  36118. private:
  36119. String dragAndDropDescription;
  36120. FileTreeComponent (const FileTreeComponent&);
  36121. const FileTreeComponent& operator= (const FileTreeComponent&);
  36122. };
  36123. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  36124. /********* End of inlined file: juce_FileTreeComponent.h *********/
  36125. #endif
  36126. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  36127. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  36128. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  36129. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  36130. /**
  36131. A simple preview component that shows thumbnails of image files.
  36132. @see FileChooserDialogBox, FilePreviewComponent
  36133. */
  36134. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  36135. private Timer
  36136. {
  36137. public:
  36138. /** Creates an ImagePreviewComponent. */
  36139. ImagePreviewComponent();
  36140. /** Destructor. */
  36141. ~ImagePreviewComponent();
  36142. /** @internal */
  36143. void selectedFileChanged (const File& newSelectedFile);
  36144. /** @internal */
  36145. void paint (Graphics& g);
  36146. /** @internal */
  36147. void timerCallback();
  36148. juce_UseDebuggingNewOperator
  36149. private:
  36150. File fileToLoad;
  36151. ScopedPointer <Image> currentThumbnail;
  36152. String currentDetails;
  36153. void getThumbSize (int& w, int& h) const;
  36154. ImagePreviewComponent (const ImagePreviewComponent&);
  36155. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  36156. };
  36157. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  36158. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  36159. #endif
  36160. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  36161. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  36162. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  36163. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  36164. /**
  36165. A type of FileFilter that works by wildcard pattern matching.
  36166. This filter only allows files that match one of the specified patterns, but
  36167. allows all directories through.
  36168. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36169. */
  36170. class JUCE_API WildcardFileFilter : public FileFilter
  36171. {
  36172. public:
  36173. /**
  36174. Creates a wildcard filter for one or more patterns.
  36175. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  36176. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  36177. or .aiff.
  36178. The description is a name to show the user in a list of possible patterns, so
  36179. for the wav/aiff example, your description might be "audio files".
  36180. */
  36181. WildcardFileFilter (const String& fileWildcardPatterns,
  36182. const String& directoryWildcardPatterns,
  36183. const String& description);
  36184. /** Destructor. */
  36185. ~WildcardFileFilter();
  36186. /** Returns true if the filename matches one of the patterns specified. */
  36187. bool isFileSuitable (const File& file) const;
  36188. /** This always returns true. */
  36189. bool isDirectorySuitable (const File& file) const;
  36190. juce_UseDebuggingNewOperator
  36191. private:
  36192. StringArray fileWildcards, directoryWildcards;
  36193. static void parse (const String& pattern, StringArray& result) throw();
  36194. static bool match (const File& file, const StringArray& wildcards) throw();
  36195. };
  36196. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  36197. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  36198. #endif
  36199. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  36200. #endif
  36201. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  36202. #endif
  36203. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  36204. #endif
  36205. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  36206. #endif
  36207. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  36208. #endif
  36209. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  36210. #endif
  36211. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  36212. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  36213. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  36214. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  36215. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  36216. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  36217. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  36218. /**
  36219. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  36220. command in a ApplicationCommandManager.
  36221. Normally, you won't actually create a KeyPressMappingSet directly, because
  36222. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  36223. you'd create yourself an ApplicationCommandManager, and call its
  36224. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  36225. KeyPressMappingSet.
  36226. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  36227. to the top-level component for which you want to handle keystrokes. So for example:
  36228. @code
  36229. class MyMainWindow : public Component
  36230. {
  36231. ApplicationCommandManager* myCommandManager;
  36232. public:
  36233. MyMainWindow()
  36234. {
  36235. myCommandManager = new ApplicationCommandManager();
  36236. // first, make sure the command manager has registered all the commands that its
  36237. // targets can perform..
  36238. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  36239. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  36240. // this will use the command manager to initialise the KeyPressMappingSet with
  36241. // the default keypresses that were specified when the targets added their commands
  36242. // to the manager.
  36243. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  36244. // having set up the default key-mappings, you might now want to load the last set
  36245. // of mappings that the user configured.
  36246. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  36247. // Now tell our top-level window to send any keypresses that arrive to the
  36248. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  36249. addKeyListener (myCommandManager->getKeyMappings());
  36250. }
  36251. ...
  36252. }
  36253. @endcode
  36254. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  36255. register to be told when a command or mapping is added, removed, etc.
  36256. There's also a UI component called KeyMappingEditorComponent that can be used
  36257. to easily edit the key mappings.
  36258. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  36259. */
  36260. class JUCE_API KeyPressMappingSet : public KeyListener,
  36261. public ChangeBroadcaster,
  36262. public FocusChangeListener
  36263. {
  36264. public:
  36265. /** Creates a KeyPressMappingSet for a given command manager.
  36266. Normally, you won't actually create a KeyPressMappingSet directly, because
  36267. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  36268. best thing to do is to create your ApplicationCommandManager, and use the
  36269. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  36270. When a suitable keypress happens, the manager's invoke() method will be
  36271. used to invoke the appropriate command.
  36272. @see ApplicationCommandManager
  36273. */
  36274. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  36275. /** Creates an copy of a KeyPressMappingSet. */
  36276. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  36277. /** Destructor. */
  36278. ~KeyPressMappingSet();
  36279. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  36280. /** Returns a list of keypresses that are assigned to a particular command.
  36281. @param commandID the command's ID
  36282. */
  36283. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  36284. /** Assigns a keypress to a command.
  36285. If the keypress is already assigned to a different command, it will first be
  36286. removed from that command, to avoid it triggering multiple functions.
  36287. @param commandID the ID of the command that you want to add a keypress to. If
  36288. this is 0, the keypress will be removed from anything that it
  36289. was previously assigned to, but not re-assigned
  36290. @param newKeyPress the new key-press
  36291. @param insertIndex if this is less than zero, the key will be appended to the
  36292. end of the list of keypresses; otherwise the new keypress will
  36293. be inserted into the existing list at this index
  36294. */
  36295. void addKeyPress (const CommandID commandID,
  36296. const KeyPress& newKeyPress,
  36297. int insertIndex = -1) throw();
  36298. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  36299. @see resetToDefaultMapping
  36300. */
  36301. void resetToDefaultMappings() throw();
  36302. /** Resets all key-mappings to the defaults for a particular command.
  36303. @see resetToDefaultMappings
  36304. */
  36305. void resetToDefaultMapping (const CommandID commandID) throw();
  36306. /** Removes all keypresses that are assigned to any commands. */
  36307. void clearAllKeyPresses() throw();
  36308. /** Removes all keypresses that are assigned to a particular command. */
  36309. void clearAllKeyPresses (const CommandID commandID) throw();
  36310. /** Removes one of the keypresses that are assigned to a command.
  36311. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  36312. which the keyPressIndex refers.
  36313. */
  36314. void removeKeyPress (const CommandID commandID,
  36315. const int keyPressIndex) throw();
  36316. /** Removes a keypress from any command that it may be assigned to.
  36317. */
  36318. void removeKeyPress (const KeyPress& keypress) throw();
  36319. /** Returns true if the given command is linked to this key. */
  36320. bool containsMapping (const CommandID commandID,
  36321. const KeyPress& keyPress) const throw();
  36322. /** Looks for a command that corresponds to a keypress.
  36323. @returns the UID of the command or 0 if none was found
  36324. */
  36325. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  36326. /** Tries to recreate the mappings from a previously stored state.
  36327. The XML passed in must have been created by the createXml() method.
  36328. If the stored state makes any reference to commands that aren't
  36329. currently available, these will be ignored.
  36330. If the set of mappings being loaded was a set of differences (using createXml (true)),
  36331. then this will call resetToDefaultMappings() and then merge the saved mappings
  36332. on top. If the saved set was created with createXml (false), then this method
  36333. will first clear all existing mappings and load the saved ones as a complete set.
  36334. @returns true if it manages to load the XML correctly
  36335. @see createXml
  36336. */
  36337. bool restoreFromXml (const XmlElement& xmlVersion);
  36338. /** Creates an XML representation of the current mappings.
  36339. This will produce a lump of XML that can be later reloaded using
  36340. restoreFromXml() to recreate the current mapping state.
  36341. The object that is returned must be deleted by the caller.
  36342. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  36343. will be saved into the XML. If it's true, then the XML will
  36344. only store the differences between the current mappings and
  36345. the default mappings you'd get from calling resetToDefaultMappings().
  36346. The advantage of saving a set of differences from the default is that
  36347. if you change the default mappings (in a new version of your app, for
  36348. example), then these will be merged into a user's saved preferences.
  36349. @see restoreFromXml
  36350. */
  36351. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  36352. /** @internal */
  36353. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  36354. /** @internal */
  36355. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  36356. /** @internal */
  36357. void globalFocusChanged (Component* focusedComponent);
  36358. juce_UseDebuggingNewOperator
  36359. private:
  36360. ApplicationCommandManager* commandManager;
  36361. struct CommandMapping
  36362. {
  36363. CommandID commandID;
  36364. Array <KeyPress> keypresses;
  36365. bool wantsKeyUpDownCallbacks;
  36366. };
  36367. OwnedArray <CommandMapping> mappings;
  36368. struct KeyPressTime
  36369. {
  36370. KeyPress key;
  36371. uint32 timeWhenPressed;
  36372. };
  36373. OwnedArray <KeyPressTime> keysDown;
  36374. void handleMessage (const Message& message);
  36375. void invokeCommand (const CommandID commandID,
  36376. const KeyPress& keyPress,
  36377. const bool isKeyDown,
  36378. const int millisecsSinceKeyPressed,
  36379. Component* const originatingComponent) const;
  36380. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  36381. };
  36382. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  36383. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  36384. /**
  36385. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  36386. object.
  36387. @see KeyPressMappingSet
  36388. */
  36389. class JUCE_API KeyMappingEditorComponent : public Component,
  36390. public TreeViewItem,
  36391. public ChangeListener,
  36392. private ButtonListener
  36393. {
  36394. public:
  36395. /** Creates a KeyMappingEditorComponent.
  36396. @param mappingSet this is the set of mappings to display and
  36397. edit. Make sure the mappings object is not
  36398. deleted before this component!
  36399. @param showResetToDefaultButton if true, then at the bottom of the
  36400. list, the component will include a 'reset to
  36401. defaults' button.
  36402. */
  36403. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  36404. const bool showResetToDefaultButton);
  36405. /** Destructor. */
  36406. virtual ~KeyMappingEditorComponent();
  36407. /** Sets up the colours to use for parts of the component.
  36408. @param mainBackground colour to use for most of the background
  36409. @param textColour colour to use for the text
  36410. */
  36411. void setColours (const Colour& mainBackground,
  36412. const Colour& textColour);
  36413. /** Returns the KeyPressMappingSet that this component is acting upon.
  36414. */
  36415. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  36416. /** Can be overridden if some commands need to be excluded from the list.
  36417. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  36418. method to decide what to return, but you can override it to handle special cases.
  36419. */
  36420. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  36421. /** Can be overridden to indicate that some commands are shown as read-only.
  36422. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  36423. method to decide what to return, but you can override it to handle special cases.
  36424. */
  36425. virtual bool isCommandReadOnly (const CommandID commandID);
  36426. /** This can be overridden to let you change the format of the string used
  36427. to describe a keypress.
  36428. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  36429. keys that are triggered by something else externally. If you override the
  36430. method, be sure to let the base class's method handle keys you're not
  36431. interested in.
  36432. */
  36433. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  36434. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  36435. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36436. methods.
  36437. To change the colours of the menu that pops up
  36438. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36439. */
  36440. enum ColourIds
  36441. {
  36442. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  36443. textColourId = 0x100ad01, /**< The colour for the text. */
  36444. };
  36445. /** @internal */
  36446. void parentHierarchyChanged();
  36447. /** @internal */
  36448. void resized();
  36449. /** @internal */
  36450. void changeListenerCallback (void*);
  36451. /** @internal */
  36452. bool mightContainSubItems();
  36453. /** @internal */
  36454. const String getUniqueName() const;
  36455. /** @internal */
  36456. void buttonClicked (Button* button);
  36457. juce_UseDebuggingNewOperator
  36458. private:
  36459. KeyPressMappingSet* mappings;
  36460. TreeView* tree;
  36461. friend class KeyMappingTreeViewItem;
  36462. friend class KeyCategoryTreeViewItem;
  36463. friend class KeyMappingItemComponent;
  36464. friend class KeyMappingChangeButton;
  36465. TextButton* resetButton;
  36466. void assignNewKey (const CommandID commandID, int index);
  36467. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  36468. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  36469. };
  36470. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  36471. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  36472. #endif
  36473. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  36474. #endif
  36475. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  36476. #endif
  36477. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  36478. #endif
  36479. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  36480. #endif
  36481. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36482. #endif
  36483. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36484. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  36485. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36486. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36487. /** An object that watches for any movement of a component or any of its parent components.
  36488. This makes it easy to check when a component is moved relative to its top-level
  36489. peer window. The normal Component::moved() method is only called when a component
  36490. moves relative to its immediate parent, and sometimes you want to know if any of
  36491. components higher up the tree have moved (which of course will affect the overall
  36492. position of all their sub-components).
  36493. It also includes a callback that lets you know when the top-level peer is changed.
  36494. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  36495. because they need to keep their custom windows in the right place and respond to
  36496. changes in the peer.
  36497. */
  36498. class JUCE_API ComponentMovementWatcher : public ComponentListener
  36499. {
  36500. public:
  36501. /** Creates a ComponentMovementWatcher to watch a given target component. */
  36502. ComponentMovementWatcher (Component* const component);
  36503. /** Destructor. */
  36504. ~ComponentMovementWatcher();
  36505. /** This callback happens when the component that is being watched is moved
  36506. relative to its top-level peer window, or when it is resized.
  36507. */
  36508. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  36509. /** This callback happens when the component's top-level peer is changed.
  36510. */
  36511. virtual void componentPeerChanged() = 0;
  36512. juce_UseDebuggingNewOperator
  36513. /** @internal */
  36514. void componentParentHierarchyChanged (Component& component);
  36515. /** @internal */
  36516. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36517. private:
  36518. Component* const component;
  36519. ComponentPeer* lastPeer;
  36520. VoidArray registeredParentComps;
  36521. bool reentrant;
  36522. int lastX, lastY, lastWidth, lastHeight;
  36523. #ifdef JUCE_DEBUG
  36524. ScopedPointer <ComponentDeletionWatcher> deletionWatcher;
  36525. #endif
  36526. void unregister() throw();
  36527. void registerWithParentComps() throw();
  36528. ComponentMovementWatcher (const ComponentMovementWatcher&);
  36529. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  36530. };
  36531. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36532. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  36533. #endif
  36534. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36535. /********* Start of inlined file: juce_GroupComponent.h *********/
  36536. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36537. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36538. /**
  36539. A component that draws an outline around itself and has an optional title at
  36540. the top, for drawing an outline around a group of controls.
  36541. */
  36542. class JUCE_API GroupComponent : public Component
  36543. {
  36544. public:
  36545. /** Creates a GroupComponent.
  36546. @param componentName the name to give the component
  36547. @param labelText the text to show at the top of the outline
  36548. */
  36549. GroupComponent (const String& componentName,
  36550. const String& labelText);
  36551. /** Destructor. */
  36552. ~GroupComponent();
  36553. /** Changes the text that's shown at the top of the component. */
  36554. void setText (const String& newText) throw();
  36555. /** Returns the currently displayed text label. */
  36556. const String getText() const throw();
  36557. /** Sets the positioning of the text label.
  36558. (The default is Justification::left)
  36559. @see getTextLabelPosition
  36560. */
  36561. void setTextLabelPosition (const Justification& justification);
  36562. /** Returns the current text label position.
  36563. @see setTextLabelPosition
  36564. */
  36565. const Justification getTextLabelPosition() const throw() { return justification; }
  36566. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36567. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36568. methods.
  36569. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36570. */
  36571. enum ColourIds
  36572. {
  36573. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  36574. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  36575. };
  36576. /** @internal */
  36577. void paint (Graphics& g);
  36578. /** @internal */
  36579. void enablementChanged();
  36580. /** @internal */
  36581. void colourChanged();
  36582. private:
  36583. String text;
  36584. Justification justification;
  36585. GroupComponent (const GroupComponent&);
  36586. const GroupComponent& operator= (const GroupComponent&);
  36587. };
  36588. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36589. /********* End of inlined file: juce_GroupComponent.h *********/
  36590. #endif
  36591. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36592. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  36593. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36594. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36595. /********* Start of inlined file: juce_TabbedComponent.h *********/
  36596. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36597. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36598. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  36599. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36600. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36601. class TabbedButtonBar;
  36602. /** In a TabbedButtonBar, this component is used for each of the buttons.
  36603. If you want to create a TabbedButtonBar with custom tab components, derive
  36604. your component from this class, and override the TabbedButtonBar::createTabButton()
  36605. method to create it instead of the default one.
  36606. @see TabbedButtonBar
  36607. */
  36608. class JUCE_API TabBarButton : public Button
  36609. {
  36610. public:
  36611. /** Creates the tab button. */
  36612. TabBarButton (const String& name,
  36613. TabbedButtonBar* const ownerBar,
  36614. const int tabIndex);
  36615. /** Destructor. */
  36616. ~TabBarButton();
  36617. /** Chooses the best length for the tab, given the specified depth.
  36618. If the tab is horizontal, this should return its width, and the depth
  36619. specifies its height. If it's vertical, it should return the height, and
  36620. the depth is actually its width.
  36621. */
  36622. virtual int getBestTabLength (const int depth);
  36623. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  36624. void clicked (const ModifierKeys& mods);
  36625. bool hitTest (int x, int y);
  36626. juce_UseDebuggingNewOperator
  36627. protected:
  36628. friend class TabbedButtonBar;
  36629. TabbedButtonBar* const owner;
  36630. int tabIndex, overlapPixels;
  36631. DropShadowEffect shadow;
  36632. /** Returns an area of the component that's safe to draw in.
  36633. This deals with the orientation of the tabs, which affects which side is
  36634. touching the tabbed box's content component.
  36635. */
  36636. void getActiveArea (int& x, int& y, int& w, int& h);
  36637. private:
  36638. TabBarButton (const TabBarButton&);
  36639. const TabBarButton& operator= (const TabBarButton&);
  36640. };
  36641. /**
  36642. A vertical or horizontal bar containing tabs that you can select.
  36643. You can use one of these to generate things like a dialog box that has
  36644. tabbed pages you can flip between. Attach a ChangeListener to the
  36645. button bar to be told when the user changes the page.
  36646. An easier method than doing this is to use a TabbedComponent, which
  36647. contains its own TabbedButtonBar and which takes care of the layout
  36648. and other housekeeping.
  36649. @see TabbedComponent
  36650. */
  36651. class JUCE_API TabbedButtonBar : public Component,
  36652. public ChangeBroadcaster,
  36653. public ButtonListener
  36654. {
  36655. public:
  36656. /** The placement of the tab-bar
  36657. @see setOrientation, getOrientation
  36658. */
  36659. enum Orientation
  36660. {
  36661. TabsAtTop,
  36662. TabsAtBottom,
  36663. TabsAtLeft,
  36664. TabsAtRight
  36665. };
  36666. /** Creates a TabbedButtonBar with a given placement.
  36667. You can change the orientation later if you need to.
  36668. */
  36669. TabbedButtonBar (const Orientation orientation);
  36670. /** Destructor. */
  36671. ~TabbedButtonBar();
  36672. /** Changes the bar's orientation.
  36673. This won't change the bar's actual size - you'll need to do that yourself,
  36674. but this determines which direction the tabs go in, and which side they're
  36675. stuck to.
  36676. */
  36677. void setOrientation (const Orientation orientation);
  36678. /** Returns the current orientation.
  36679. @see setOrientation
  36680. */
  36681. Orientation getOrientation() const throw() { return orientation; }
  36682. /** Deletes all the tabs from the bar.
  36683. @see addTab
  36684. */
  36685. void clearTabs();
  36686. /** Adds a tab to the bar.
  36687. Tabs are added in left-to-right reading order.
  36688. If this is the first tab added, it'll also be automatically selected.
  36689. */
  36690. void addTab (const String& tabName,
  36691. const Colour& tabBackgroundColour,
  36692. int insertIndex = -1);
  36693. /** Changes the name of one of the tabs. */
  36694. void setTabName (const int tabIndex,
  36695. const String& newName);
  36696. /** Gets rid of one of the tabs. */
  36697. void removeTab (const int tabIndex);
  36698. /** Moves a tab to a new index in the list.
  36699. Pass -1 as the index to move it to the end of the list.
  36700. */
  36701. void moveTab (const int currentIndex,
  36702. const int newIndex);
  36703. /** Returns the number of tabs in the bar. */
  36704. int getNumTabs() const;
  36705. /** Returns a list of all the tab names in the bar. */
  36706. const StringArray getTabNames() const;
  36707. /** Changes the currently selected tab.
  36708. This will send a change message and cause a synchronous callback to
  36709. the currentTabChanged() method. (But if the given tab is already selected,
  36710. nothing will be done).
  36711. To deselect all the tabs, use an index of -1.
  36712. */
  36713. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  36714. /** Returns the name of the currently selected tab.
  36715. This could be an empty string if none are selected.
  36716. */
  36717. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  36718. /** Returns the index of the currently selected tab.
  36719. This could return -1 if none are selected.
  36720. */
  36721. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  36722. /** Returns the button for a specific tab.
  36723. The button that is returned may be deleted later by this component, so don't hang
  36724. on to the pointer that is returned. A null pointer may be returned if the index is
  36725. out of range.
  36726. */
  36727. TabBarButton* getTabButton (const int index) const;
  36728. /** Callback method to indicate the selected tab has been changed.
  36729. @see setCurrentTabIndex
  36730. */
  36731. virtual void currentTabChanged (const int newCurrentTabIndex,
  36732. const String& newCurrentTabName);
  36733. /** Callback method to indicate that the user has right-clicked on a tab.
  36734. (Or ctrl-clicked on the Mac)
  36735. */
  36736. virtual void popupMenuClickOnTab (const int tabIndex,
  36737. const String& tabName);
  36738. /** Returns the colour of a tab.
  36739. This is the colour that was specified in addTab().
  36740. */
  36741. const Colour getTabBackgroundColour (const int tabIndex);
  36742. /** Changes the background colour of a tab.
  36743. @see addTab, getTabBackgroundColour
  36744. */
  36745. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36746. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36747. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36748. methods.
  36749. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36750. */
  36751. enum ColourIds
  36752. {
  36753. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  36754. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  36755. the look and feel will choose an appropriate colour. */
  36756. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  36757. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  36758. this isn't specified, the look and feel will choose an appropriate
  36759. colour. */
  36760. };
  36761. /** @internal */
  36762. void resized();
  36763. /** @internal */
  36764. void buttonClicked (Button* button);
  36765. /** @internal */
  36766. void lookAndFeelChanged();
  36767. juce_UseDebuggingNewOperator
  36768. protected:
  36769. /** This creates one of the tabs.
  36770. If you need to use custom tab components, you can override this method and
  36771. return your own class instead of the default.
  36772. */
  36773. virtual TabBarButton* createTabButton (const String& tabName,
  36774. const int tabIndex);
  36775. private:
  36776. Orientation orientation;
  36777. StringArray tabs;
  36778. Array <Colour> tabColours;
  36779. int currentTabIndex;
  36780. Component* behindFrontTab;
  36781. Button* extraTabsButton;
  36782. TabbedButtonBar (const TabbedButtonBar&);
  36783. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  36784. };
  36785. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36786. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  36787. /**
  36788. A component with a TabbedButtonBar along one of its sides.
  36789. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  36790. with addTab(), and this will take care of showing the pages for you when the
  36791. user clicks on a different tab.
  36792. @see TabbedButtonBar
  36793. */
  36794. class JUCE_API TabbedComponent : public Component
  36795. {
  36796. public:
  36797. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  36798. Once created, add some tabs with the addTab() method.
  36799. */
  36800. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  36801. /** Destructor. */
  36802. ~TabbedComponent();
  36803. /** Changes the placement of the tabs.
  36804. This will rearrange the layout to place the tabs along the appropriate
  36805. side of this component, and will shift the content component accordingly.
  36806. @see TabbedButtonBar::setOrientation
  36807. */
  36808. void setOrientation (const TabbedButtonBar::Orientation orientation);
  36809. /** Returns the current tab placement.
  36810. @see setOrientation, TabbedButtonBar::getOrientation
  36811. */
  36812. TabbedButtonBar::Orientation getOrientation() const throw();
  36813. /** Specifies how many pixels wide or high the tab-bar should be.
  36814. If the tabs are placed along the top or bottom, this specified the height
  36815. of the bar; if they're along the left or right edges, it'll be the width
  36816. of the bar.
  36817. */
  36818. void setTabBarDepth (const int newDepth);
  36819. /** Returns the current thickness of the tab bar.
  36820. @see setTabBarDepth
  36821. */
  36822. int getTabBarDepth() const throw() { return tabDepth; }
  36823. /** Specifies the thickness of an outline that should be drawn around the content component.
  36824. If this thickness is > 0, a line will be drawn around the three sides of the content
  36825. component which don't touch the tab-bar, and the content component will be inset by this amount.
  36826. To set the colour of the line, use setColour (outlineColourId, ...).
  36827. */
  36828. void setOutline (const int newThickness);
  36829. /** Specifies a gap to leave around the edge of the content component.
  36830. Each edge of the content component will be indented by the given number of pixels.
  36831. */
  36832. void setIndent (const int indentThickness);
  36833. /** Removes all the tabs from the bar.
  36834. @see TabbedButtonBar::clearTabs
  36835. */
  36836. void clearTabs();
  36837. /** Adds a tab to the tab-bar.
  36838. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  36839. is true, it will be deleted when the tab is removed or when this object is
  36840. deleted.
  36841. @see TabbedButtonBar::addTab
  36842. */
  36843. void addTab (const String& tabName,
  36844. const Colour& tabBackgroundColour,
  36845. Component* const contentComponent,
  36846. const bool deleteComponentWhenNotNeeded,
  36847. const int insertIndex = -1);
  36848. /** Changes the name of one of the tabs. */
  36849. void setTabName (const int tabIndex,
  36850. const String& newName);
  36851. /** Gets rid of one of the tabs. */
  36852. void removeTab (const int tabIndex);
  36853. /** Returns the number of tabs in the bar. */
  36854. int getNumTabs() const;
  36855. /** Returns a list of all the tab names in the bar. */
  36856. const StringArray getTabNames() const;
  36857. /** Returns the content component that was added for the given index.
  36858. Be sure not to use or delete the components that are returned, as this may interfere
  36859. with the TabbedComponent's use of them.
  36860. */
  36861. Component* getTabContentComponent (const int tabIndex) const throw();
  36862. /** Returns the colour of one of the tabs. */
  36863. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  36864. /** Changes the background colour of one of the tabs. */
  36865. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36866. /** Changes the currently-selected tab.
  36867. To deselect all the tabs, pass -1 as the index.
  36868. @see TabbedButtonBar::setCurrentTabIndex
  36869. */
  36870. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  36871. /** Returns the index of the currently selected tab.
  36872. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  36873. */
  36874. int getCurrentTabIndex() const;
  36875. /** Returns the name of the currently selected tab.
  36876. @see addTab, TabbedButtonBar::getCurrentTabName()
  36877. */
  36878. const String& getCurrentTabName() const;
  36879. /** Returns the current component that's filling the panel.
  36880. This will return 0 if there isn't one.
  36881. */
  36882. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  36883. /** Callback method to indicate the selected tab has been changed.
  36884. @see setCurrentTabIndex
  36885. */
  36886. virtual void currentTabChanged (const int newCurrentTabIndex,
  36887. const String& newCurrentTabName);
  36888. /** Callback method to indicate that the user has right-clicked on a tab.
  36889. (Or ctrl-clicked on the Mac)
  36890. */
  36891. virtual void popupMenuClickOnTab (const int tabIndex,
  36892. const String& tabName);
  36893. /** Returns the tab button bar component that is being used.
  36894. */
  36895. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  36896. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36897. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36898. methods.
  36899. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36900. */
  36901. enum ColourIds
  36902. {
  36903. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  36904. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  36905. (See setOutline) */
  36906. };
  36907. /** @internal */
  36908. void paint (Graphics& g);
  36909. /** @internal */
  36910. void resized();
  36911. /** @internal */
  36912. void lookAndFeelChanged();
  36913. juce_UseDebuggingNewOperator
  36914. protected:
  36915. TabbedButtonBar* tabs;
  36916. /** This creates one of the tab buttons.
  36917. If you need to use custom tab components, you can override this method and
  36918. return your own class instead of the default.
  36919. */
  36920. virtual TabBarButton* createTabButton (const String& tabName,
  36921. const int tabIndex);
  36922. private:
  36923. Array <Component*> contentComponents;
  36924. Component* panelComponent;
  36925. int tabDepth;
  36926. int outlineThickness, edgeIndent;
  36927. friend class TabCompButtonBar;
  36928. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  36929. TabbedComponent (const TabbedComponent&);
  36930. const TabbedComponent& operator= (const TabbedComponent&);
  36931. };
  36932. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36933. /********* End of inlined file: juce_TabbedComponent.h *********/
  36934. /********* Start of inlined file: juce_DocumentWindow.h *********/
  36935. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36936. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36937. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  36938. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  36939. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  36940. /********* Start of inlined file: juce_MenuBarModel.h *********/
  36941. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  36942. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  36943. class MenuBarModel;
  36944. /**
  36945. A class to receive callbacks when a MenuBarModel changes.
  36946. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  36947. */
  36948. class JUCE_API MenuBarModelListener
  36949. {
  36950. public:
  36951. /** Destructor. */
  36952. virtual ~MenuBarModelListener() {}
  36953. /** This callback is made when items are changed in the menu bar model.
  36954. */
  36955. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  36956. /** This callback is made when an application command is invoked that
  36957. is represented by one of the items in the menu bar model.
  36958. */
  36959. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  36960. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  36961. };
  36962. /**
  36963. A class for controlling MenuBar components.
  36964. This class is used to tell a MenuBar what menus to show, and to respond
  36965. to a menu being selected.
  36966. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  36967. */
  36968. class JUCE_API MenuBarModel : private AsyncUpdater,
  36969. private ApplicationCommandManagerListener
  36970. {
  36971. public:
  36972. MenuBarModel() throw();
  36973. /** Destructor. */
  36974. virtual ~MenuBarModel();
  36975. /** Call this when some of your menu items have changed.
  36976. This method will cause a callback to any MenuBarListener objects that
  36977. are registered with this model.
  36978. If this model is displaying items from an ApplicationCommandManager, you
  36979. can use the setApplicationCommandManagerToWatch() method to cause
  36980. change messages to be sent automatically when the ApplicationCommandManager
  36981. is changed.
  36982. @see addListener, removeListener, MenuBarListener
  36983. */
  36984. void menuItemsChanged();
  36985. /** Tells the menu bar to listen to the specified command manager, and to update
  36986. itself when the commands change.
  36987. This will also allow it to flash a menu name when a command from that menu
  36988. is invoked using a keystroke.
  36989. */
  36990. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  36991. /** Registers a listener for callbacks when the menu items in this model change.
  36992. The listener object will get callbacks when this object's menuItemsChanged()
  36993. method is called.
  36994. @see removeListener
  36995. */
  36996. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  36997. /** Removes a listener.
  36998. @see addListener
  36999. */
  37000. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  37001. /** This method must return a list of the names of the menus. */
  37002. virtual const StringArray getMenuBarNames() = 0;
  37003. /** This should return the popup menu to display for a given top-level menu.
  37004. @param topLevelMenuIndex the index of the top-level menu to show
  37005. @param menuName the name of the top-level menu item to show
  37006. */
  37007. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  37008. const String& menuName) = 0;
  37009. /** This is called when a menu item has been clicked on.
  37010. @param menuItemID the item ID of the PopupMenu item that was selected
  37011. @param topLevelMenuIndex the index of the top-level menu from which the item was
  37012. chosen (just in case you've used duplicate ID numbers
  37013. on more than one of the popup menus)
  37014. */
  37015. virtual void menuItemSelected (int menuItemID,
  37016. int topLevelMenuIndex) = 0;
  37017. #if JUCE_MAC || DOXYGEN
  37018. /** MAC ONLY - Sets the model that is currently being shown as the main
  37019. menu bar at the top of the screen on the Mac.
  37020. You can pass 0 to stop the current model being displayed. Be careful
  37021. not to delete a model while it is being used.
  37022. An optional extra menu can be specified, containing items to add to the top of
  37023. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  37024. an apple, it's the one next to it, with your application's name at the top
  37025. and the services menu etc on it). When one of these items is selected, the
  37026. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  37027. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  37028. object then newMenuBarModel must be non-null.
  37029. */
  37030. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  37031. const PopupMenu* extraAppleMenuItems = 0);
  37032. /** MAC ONLY - Returns the menu model that is currently being shown as
  37033. the main menu bar.
  37034. */
  37035. static MenuBarModel* getMacMainMenu();
  37036. #endif
  37037. /** @internal */
  37038. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  37039. /** @internal */
  37040. void applicationCommandListChanged();
  37041. /** @internal */
  37042. void handleAsyncUpdate();
  37043. juce_UseDebuggingNewOperator
  37044. private:
  37045. ApplicationCommandManager* manager;
  37046. SortedSet <void*> listeners;
  37047. MenuBarModel (const MenuBarModel&);
  37048. const MenuBarModel& operator= (const MenuBarModel&);
  37049. };
  37050. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  37051. /********* End of inlined file: juce_MenuBarModel.h *********/
  37052. /**
  37053. A menu bar component.
  37054. @see MenuBarModel
  37055. */
  37056. class JUCE_API MenuBarComponent : public Component,
  37057. private MenuBarModelListener,
  37058. private Timer
  37059. {
  37060. public:
  37061. /** Creates a menu bar.
  37062. @param model the model object to use to control this bar. You can
  37063. pass 0 into this if you like, and set the model later
  37064. using the setModel() method
  37065. */
  37066. MenuBarComponent (MenuBarModel* const model);
  37067. /** Destructor. */
  37068. ~MenuBarComponent();
  37069. /** Changes the model object to use to control the bar.
  37070. This can be 0, in which case the bar will be empty. Don't delete the object
  37071. that is passed-in while it's still being used by this MenuBar.
  37072. */
  37073. void setModel (MenuBarModel* const newModel);
  37074. /** Pops up one of the menu items.
  37075. This lets you manually open one of the menus - it could be triggered by a
  37076. key shortcut, for example.
  37077. */
  37078. void showMenu (const int menuIndex);
  37079. /** @internal */
  37080. void paint (Graphics& g);
  37081. /** @internal */
  37082. void resized();
  37083. /** @internal */
  37084. void mouseEnter (const MouseEvent& e);
  37085. /** @internal */
  37086. void mouseExit (const MouseEvent& e);
  37087. /** @internal */
  37088. void mouseDown (const MouseEvent& e);
  37089. /** @internal */
  37090. void mouseDrag (const MouseEvent& e);
  37091. /** @internal */
  37092. void mouseUp (const MouseEvent& e);
  37093. /** @internal */
  37094. void mouseMove (const MouseEvent& e);
  37095. /** @internal */
  37096. void inputAttemptWhenModal();
  37097. /** @internal */
  37098. void handleCommandMessage (int commandId);
  37099. /** @internal */
  37100. bool keyPressed (const KeyPress& key);
  37101. /** @internal */
  37102. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  37103. /** @internal */
  37104. void menuCommandInvoked (MenuBarModel* menuBarModel,
  37105. const ApplicationCommandTarget::InvocationInfo& info);
  37106. juce_UseDebuggingNewOperator
  37107. private:
  37108. MenuBarModel* model;
  37109. StringArray menuNames;
  37110. Array <int> xPositions;
  37111. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  37112. int lastMouseX, lastMouseY;
  37113. bool inModalState;
  37114. ScopedPointer <Component> currentPopup;
  37115. int getItemAt (int x, int y);
  37116. void updateItemUnderMouse (const int x, const int y);
  37117. void hideCurrentMenu();
  37118. void timerCallback();
  37119. void repaintMenuItem (int index);
  37120. MenuBarComponent (const MenuBarComponent&);
  37121. const MenuBarComponent& operator= (const MenuBarComponent&);
  37122. };
  37123. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  37124. /********* End of inlined file: juce_MenuBarComponent.h *********/
  37125. /**
  37126. A resizable window with a title bar and maximise, minimise and close buttons.
  37127. This subclass of ResizableWindow creates a fairly standard type of window with
  37128. a title bar and various buttons. The name of the component is shown in the
  37129. title bar, and an icon can optionally be specified with setIcon().
  37130. All the methods available to a ResizableWindow are also available to this,
  37131. so it can easily be made resizable, minimised, maximised, etc.
  37132. It's not advisable to add child components directly to a DocumentWindow: put them
  37133. inside your content component instead. And overriding methods like resized(), moved(), etc
  37134. is also not recommended - instead override these methods for your content component.
  37135. (If for some obscure reason you do need to override these methods, always remember to
  37136. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37137. decorations correctly).
  37138. You can also automatically add a menu bar to the window, using the setMenuBar()
  37139. method.
  37140. @see ResizableWindow, DialogWindow
  37141. */
  37142. class JUCE_API DocumentWindow : public ResizableWindow
  37143. {
  37144. public:
  37145. /** The set of available button-types that can be put on the title bar.
  37146. @see setTitleBarButtonsRequired
  37147. */
  37148. enum TitleBarButtons
  37149. {
  37150. minimiseButton = 1,
  37151. maximiseButton = 2,
  37152. closeButton = 4,
  37153. /** A combination of all the buttons above. */
  37154. allButtons = 7
  37155. };
  37156. /** Creates a DocumentWindow.
  37157. @param name the name to give the component - this is also
  37158. the title shown at the top of the window. To change
  37159. this later, use setName()
  37160. @param backgroundColour the colour to use for filling the window's background.
  37161. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  37162. should be shown on the title bar. This value is a bitwise
  37163. combination of values from the TitleBarButtons enum. Note
  37164. that it can be "allButtons" to get them all. You
  37165. can change this later with the setTitleBarButtonsRequired()
  37166. method, which can also specify where they are positioned.
  37167. @param addToDesktop if true, the window will be automatically added to the
  37168. desktop; if false, you can use it as a child component
  37169. @see TitleBarButtons
  37170. */
  37171. DocumentWindow (const String& name,
  37172. const Colour& backgroundColour,
  37173. const int requiredButtons,
  37174. const bool addToDesktop = true);
  37175. /** Destructor.
  37176. If a content component has been set with setContentComponent(), it
  37177. will be deleted.
  37178. */
  37179. ~DocumentWindow();
  37180. /** Changes the component's name.
  37181. (This is overridden from Component::setName() to cause a repaint, as
  37182. the name is what gets drawn across the window's title bar).
  37183. */
  37184. void setName (const String& newName);
  37185. /** Sets an icon to show in the title bar, next to the title.
  37186. A copy is made internally of the image, so the caller can delete the
  37187. image after calling this. If 0 is passed-in, any existing icon will be
  37188. removed.
  37189. */
  37190. void setIcon (const Image* imageToUse);
  37191. /** Changes the height of the title-bar. */
  37192. void setTitleBarHeight (const int newHeight);
  37193. /** Returns the current title bar height. */
  37194. int getTitleBarHeight() const;
  37195. /** Changes the set of title-bar buttons being shown.
  37196. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  37197. should be shown on the title bar. This value is a bitwise
  37198. combination of values from the TitleBarButtons enum. Note
  37199. that it can be "allButtons" to get them all.
  37200. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  37201. left side of the bar; if false, they'll be placed at the right
  37202. */
  37203. void setTitleBarButtonsRequired (const int requiredButtons,
  37204. const bool positionTitleBarButtonsOnLeft);
  37205. /** Sets whether the title should be centred within the window.
  37206. If true, the title text is shown in the middle of the title-bar; if false,
  37207. it'll be shown at the left of the bar.
  37208. */
  37209. void setTitleBarTextCentred (const bool textShouldBeCentred);
  37210. /** Creates a menu inside this window.
  37211. @param menuBarModel this specifies a MenuBarModel that should be used to
  37212. generate the contents of a menu bar that will be placed
  37213. just below the title bar, and just above any content
  37214. component. If this value is zero, any existing menu bar
  37215. will be removed from the component; if non-zero, one will
  37216. be added if it's required.
  37217. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  37218. or less to use the look-and-feel's default size.
  37219. */
  37220. void setMenuBar (MenuBarModel* menuBarModel,
  37221. const int menuBarHeight = 0);
  37222. /** This method is called when the user tries to close the window.
  37223. This is triggered by the user clicking the close button, or using some other
  37224. OS-specific key shortcut or OS menu for getting rid of a window.
  37225. If the window is just a pop-up, you should override this closeButtonPressed()
  37226. method and make it delete the window in whatever way is appropriate for your
  37227. app. E.g. you might just want to call "delete this".
  37228. If your app is centred around this window such that the whole app should quit when
  37229. the window is closed, then you will probably want to use this method as an opportunity
  37230. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  37231. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  37232. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  37233. or closing it via the taskbar icon on Windows).
  37234. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  37235. redirects it to call this method, so any methods of closing the window that are
  37236. caught by userTriedToCloseWindow() will also end up here).
  37237. */
  37238. virtual void closeButtonPressed();
  37239. /** Callback that is triggered when the minimise button is pressed.
  37240. The default implementation of this calls ResizableWindow::setMinimised(), but
  37241. you can override it to do more customised behaviour.
  37242. */
  37243. virtual void minimiseButtonPressed();
  37244. /** Callback that is triggered when the maximise button is pressed, or when the
  37245. title-bar is double-clicked.
  37246. The default implementation of this calls ResizableWindow::setFullScreen(), but
  37247. you can override it to do more customised behaviour.
  37248. */
  37249. virtual void maximiseButtonPressed();
  37250. /** Returns the close button, (or 0 if there isn't one). */
  37251. Button* getCloseButton() const throw();
  37252. /** Returns the minimise button, (or 0 if there isn't one). */
  37253. Button* getMinimiseButton() const throw();
  37254. /** Returns the maximise button, (or 0 if there isn't one). */
  37255. Button* getMaximiseButton() const throw();
  37256. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37257. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37258. methods.
  37259. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37260. */
  37261. enum ColourIds
  37262. {
  37263. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  37264. and feel class how this is used. */
  37265. };
  37266. /** @internal */
  37267. void paint (Graphics& g);
  37268. /** @internal */
  37269. void resized();
  37270. /** @internal */
  37271. void lookAndFeelChanged();
  37272. /** @internal */
  37273. const BorderSize getBorderThickness();
  37274. /** @internal */
  37275. const BorderSize getContentComponentBorder();
  37276. /** @internal */
  37277. void mouseDoubleClick (const MouseEvent& e);
  37278. /** @internal */
  37279. void userTriedToCloseWindow();
  37280. /** @internal */
  37281. void activeWindowStatusChanged();
  37282. /** @internal */
  37283. int getDesktopWindowStyleFlags() const;
  37284. /** @internal */
  37285. void parentHierarchyChanged();
  37286. /** @internal */
  37287. const Rectangle getTitleBarArea();
  37288. juce_UseDebuggingNewOperator
  37289. private:
  37290. int titleBarHeight, menuBarHeight, requiredButtons;
  37291. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  37292. ScopedPointer <Button> titleBarButtons [3];
  37293. ScopedPointer <Image> titleBarIcon;
  37294. ScopedPointer <MenuBarComponent> menuBar;
  37295. MenuBarModel* menuBarModel;
  37296. class ButtonListenerProxy : public ButtonListener
  37297. {
  37298. public:
  37299. ButtonListenerProxy();
  37300. void buttonClicked (Button* button);
  37301. DocumentWindow* owner;
  37302. } buttonListener;
  37303. void repaintTitleBar();
  37304. DocumentWindow (const DocumentWindow&);
  37305. const DocumentWindow& operator= (const DocumentWindow&);
  37306. };
  37307. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37308. /********* End of inlined file: juce_DocumentWindow.h *********/
  37309. class MultiDocumentPanel;
  37310. class MDITabbedComponentInternal;
  37311. /**
  37312. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  37313. component.
  37314. It's like a normal DocumentWindow but has some extra functionality to make sure
  37315. everything works nicely inside a MultiDocumentPanel.
  37316. @see MultiDocumentPanel
  37317. */
  37318. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  37319. {
  37320. public:
  37321. /**
  37322. */
  37323. MultiDocumentPanelWindow (const Colour& backgroundColour);
  37324. /** Destructor. */
  37325. ~MultiDocumentPanelWindow();
  37326. /** @internal */
  37327. void maximiseButtonPressed();
  37328. /** @internal */
  37329. void closeButtonPressed();
  37330. /** @internal */
  37331. void activeWindowStatusChanged();
  37332. /** @internal */
  37333. void broughtToFront();
  37334. juce_UseDebuggingNewOperator
  37335. private:
  37336. void updateOrder();
  37337. MultiDocumentPanel* getOwner() const throw();
  37338. };
  37339. /**
  37340. A component that contains a set of other components either in floating windows
  37341. or tabs.
  37342. This acts as a panel that can be used to hold a set of open document windows, with
  37343. different layout modes.
  37344. Use addDocument() and closeDocument() to add or remove components from the
  37345. panel - never use any of the Component methods to access the panel's child
  37346. components directly, as these are managed internally.
  37347. */
  37348. class JUCE_API MultiDocumentPanel : public Component,
  37349. private ComponentListener
  37350. {
  37351. public:
  37352. /** Creates an empty panel.
  37353. Use addDocument() and closeDocument() to add or remove components from the
  37354. panel - never use any of the Component methods to access the panel's child
  37355. components directly, as these are managed internally.
  37356. */
  37357. MultiDocumentPanel();
  37358. /** Destructor.
  37359. When deleted, this will call closeAllDocuments (false) to make sure all its
  37360. components are deleted. If you need to make sure all documents are saved
  37361. before closing, then you should call closeAllDocuments (true) and check that
  37362. it returns true before deleting the panel.
  37363. */
  37364. ~MultiDocumentPanel();
  37365. /** Tries to close all the documents.
  37366. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37367. be called for each open document, and any of these calls fails, this method
  37368. will stop and return false, leaving some documents still open.
  37369. If checkItsOkToCloseFirst is false, then all documents will be closed
  37370. unconditionally.
  37371. @see closeDocument
  37372. */
  37373. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  37374. /** Adds a document component to the panel.
  37375. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  37376. this will fail and return false. (If it does fail, the component passed-in will not be
  37377. deleted, even if deleteWhenRemoved was set to true).
  37378. The MultiDocumentPanel will deal with creating a window border to go around your component,
  37379. so just pass in the bare content component here, no need to give it a ResizableWindow
  37380. or DocumentWindow.
  37381. @param component the component to add
  37382. @param backgroundColour the background colour to use to fill the component's
  37383. window or tab
  37384. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  37385. or closeAllDocuments(), then it will be deleted. If false, then
  37386. the caller must handle the component's deletion
  37387. */
  37388. bool addDocument (Component* const component,
  37389. const Colour& backgroundColour,
  37390. const bool deleteWhenRemoved);
  37391. /** Closes one of the documents.
  37392. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37393. be called, and if it fails, this method will return false without closing the
  37394. document.
  37395. If checkItsOkToCloseFirst is false, then the documents will be closed
  37396. unconditionally.
  37397. The component will be deleted if the deleteWhenRemoved parameter was set to
  37398. true when it was added with addDocument.
  37399. @see addDocument, closeAllDocuments
  37400. */
  37401. bool closeDocument (Component* component,
  37402. const bool checkItsOkToCloseFirst);
  37403. /** Returns the number of open document windows.
  37404. @see getDocument
  37405. */
  37406. int getNumDocuments() const throw();
  37407. /** Returns one of the open documents.
  37408. The order of the documents in this array may change when they are added, removed
  37409. or moved around.
  37410. @see getNumDocuments
  37411. */
  37412. Component* getDocument (const int index) const throw();
  37413. /** Returns the document component that is currently focused or on top.
  37414. If currently using floating windows, then this will be the component in the currently
  37415. active window, or the top component if none are active.
  37416. If it's currently in tabbed mode, then it'll return the component in the active tab.
  37417. @see setActiveDocument
  37418. */
  37419. Component* getActiveDocument() const throw();
  37420. /** Makes one of the components active and brings it to the top.
  37421. @see getActiveDocument
  37422. */
  37423. void setActiveDocument (Component* component);
  37424. /** Callback which gets invoked when the currently-active document changes. */
  37425. virtual void activeDocumentChanged();
  37426. /** Sets a limit on how many windows can be open at once.
  37427. If this is zero or less there's no limit (the default). addDocument() will fail
  37428. if this number is exceeded.
  37429. */
  37430. void setMaximumNumDocuments (const int maximumNumDocuments);
  37431. /** Sets an option to make the document fullscreen if there's only one document open.
  37432. If set to true, then if there's only one document, it'll fill the whole of this
  37433. component without tabs or a window border. If false, then tabs or a window
  37434. will always be shown, even if there's only one document. If there's more than
  37435. one document open, then this option makes no difference.
  37436. */
  37437. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  37438. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  37439. */
  37440. bool isFullscreenWhenOneDocument() const throw();
  37441. /** The different layout modes available. */
  37442. enum LayoutMode
  37443. {
  37444. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  37445. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  37446. };
  37447. /** Changes the panel's mode.
  37448. @see LayoutMode, getLayoutMode
  37449. */
  37450. void setLayoutMode (const LayoutMode newLayoutMode);
  37451. /** Returns the current layout mode. */
  37452. LayoutMode getLayoutMode() const throw() { return mode; }
  37453. /** Sets the background colour for the whole panel.
  37454. Each document has its own background colour, but this is the one used to fill the areas
  37455. behind them.
  37456. */
  37457. void setBackgroundColour (const Colour& newBackgroundColour);
  37458. /** Returns the current background colour.
  37459. @see setBackgroundColour
  37460. */
  37461. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  37462. /** A subclass must override this to say whether its currently ok for a document
  37463. to be closed.
  37464. This method is called by closeDocument() and closeAllDocuments() to indicate that
  37465. a document should be saved if possible, ready for it to be closed.
  37466. If this method returns true, then it means the document is ok and can be closed.
  37467. If it returns false, then it means that the closeDocument() method should stop
  37468. and not close.
  37469. Normally, you'd use this method to ask the user if they want to save any changes,
  37470. then return true if the save operation went ok. If the user cancelled the save
  37471. operation you could return false here to abort the close operation.
  37472. If your component is based on the FileBasedDocument class, then you'd probably want
  37473. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  37474. FileBasedDocument::savedOk
  37475. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  37476. */
  37477. virtual bool tryToCloseDocument (Component* component) = 0;
  37478. /** Creates a new window to be used for a document.
  37479. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  37480. but you might want to override it to return a custom component.
  37481. */
  37482. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  37483. /** @internal */
  37484. void paint (Graphics& g);
  37485. /** @internal */
  37486. void resized();
  37487. /** @internal */
  37488. void componentNameChanged (Component&);
  37489. juce_UseDebuggingNewOperator
  37490. private:
  37491. LayoutMode mode;
  37492. Array <Component*> components;
  37493. TabbedComponent* tabComponent;
  37494. Colour backgroundColour;
  37495. int maximumNumDocuments, numDocsBeforeTabsUsed;
  37496. friend class MultiDocumentPanelWindow;
  37497. friend class MDITabbedComponentInternal;
  37498. Component* getContainerComp (Component* c) const;
  37499. void updateOrder();
  37500. void addWindow (Component* component);
  37501. };
  37502. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  37503. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  37504. #endif
  37505. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37506. #endif
  37507. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37508. #endif
  37509. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  37510. #endif
  37511. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37512. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  37513. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37514. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37515. /**
  37516. For laying out a set of components, where the components have preferred sizes
  37517. and size limits, but where they are allowed to stretch to fill the available
  37518. space.
  37519. For example, if you have a component containing several other components, and
  37520. each one should be given a share of the total size, you could use one of these
  37521. to resize the child components when the parent component is resized. Then
  37522. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  37523. A StretchableLayoutManager operates only in one dimension, so if you have a set
  37524. of components stacked vertically on top of each other, you'd use one to manage their
  37525. heights. To build up complex arrangements of components, e.g. for applications
  37526. with multiple nested panels, you would use more than one StretchableLayoutManager.
  37527. E.g. by using two (one vertical, one horizontal), you could create a resizable
  37528. spreadsheet-style table.
  37529. E.g.
  37530. @code
  37531. class MyComp : public Component
  37532. {
  37533. StretchableLayoutManager myLayout;
  37534. MyComp()
  37535. {
  37536. myLayout.setItemLayout (0, // for item 0
  37537. 50, 100, // must be between 50 and 100 pixels in size
  37538. -0.6); // and its preferred size is 60% of the total available space
  37539. myLayout.setItemLayout (1, // for item 1
  37540. -0.2, -0.6, // size must be between 20% and 60% of the available space
  37541. 50); // and its preferred size is 50 pixels
  37542. }
  37543. void resized()
  37544. {
  37545. // make a list of two of our child components that we want to reposition
  37546. Component* comps[] = { myComp1, myComp2 };
  37547. // this will position the 2 components, one above the other, to fit
  37548. // vertically into the rectangle provided.
  37549. myLayout.layOutComponents (comps, 2,
  37550. 0, 0, getWidth(), getHeight(),
  37551. true);
  37552. }
  37553. };
  37554. @endcode
  37555. @see StretchableLayoutResizerBar
  37556. */
  37557. class JUCE_API StretchableLayoutManager
  37558. {
  37559. public:
  37560. /** Creates an empty layout.
  37561. You'll need to add some item properties to the layout before it can be used
  37562. to resize things - see setItemLayout().
  37563. */
  37564. StretchableLayoutManager();
  37565. /** Destructor. */
  37566. ~StretchableLayoutManager();
  37567. /** For a numbered item, this sets its size limits and preferred size.
  37568. @param itemIndex the index of the item to change.
  37569. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37570. indicates an absolute size in pixels. A negative number indicates a
  37571. proportion of the available space (e.g -0.5 is 50%)
  37572. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37573. indicates an absolute size in pixels. A negative number indicates a
  37574. proportion of the available space
  37575. @param preferredSize the size that this item would like to be, if there's enough room. A
  37576. positive number indicates an absolute size in pixels. A negative number
  37577. indicates a proportion of the available space
  37578. @see getItemLayout
  37579. */
  37580. void setItemLayout (const int itemIndex,
  37581. const double minimumSize,
  37582. const double maximumSize,
  37583. const double preferredSize);
  37584. /** For a numbered item, this returns its size limits and preferred size.
  37585. @param itemIndex the index of the item.
  37586. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37587. indicates an absolute size in pixels. A negative number indicates a
  37588. proportion of the available space (e.g -0.5 is 50%)
  37589. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37590. indicates an absolute size in pixels. A negative number indicates a
  37591. proportion of the available space
  37592. @param preferredSize the size that this item would like to be, if there's enough room. A
  37593. positive number indicates an absolute size in pixels. A negative number
  37594. indicates a proportion of the available space
  37595. @returns false if the item's properties hadn't been set
  37596. @see setItemLayout
  37597. */
  37598. bool getItemLayout (const int itemIndex,
  37599. double& minimumSize,
  37600. double& maximumSize,
  37601. double& preferredSize) const;
  37602. /** Clears all the properties that have been set with setItemLayout() and resets
  37603. this object to its initial state.
  37604. */
  37605. void clearAllItems();
  37606. /** Takes a set of components that correspond to the layout's items, and positions
  37607. them to fill a space.
  37608. This will try to give each item its preferred size, whether that's a relative size
  37609. or an absolute one.
  37610. @param components an array of components that correspond to each of the
  37611. numbered items that the StretchableLayoutManager object
  37612. has been told about with setItemLayout()
  37613. @param numComponents the number of components in the array that is passed-in. This
  37614. should be the same as the number of items this object has been
  37615. told about.
  37616. @param x the left of the rectangle in which the components should
  37617. be laid out
  37618. @param y the top of the rectangle in which the components should
  37619. be laid out
  37620. @param width the width of the rectangle in which the components should
  37621. be laid out
  37622. @param height the height of the rectangle in which the components should
  37623. be laid out
  37624. @param vertically if true, the components will be positioned in a vertical stack,
  37625. so that they fill the height of the rectangle. If false, they
  37626. will be placed side-by-side in a horizontal line, filling the
  37627. available width
  37628. @param resizeOtherDimension if true, this means that the components will have their
  37629. other dimension resized to fit the space - i.e. if the 'vertically'
  37630. parameter is true, their x-positions and widths are adjusted to fit
  37631. the x and width parameters; if 'vertically' is false, their y-positions
  37632. and heights are adjusted to fit the y and height parameters.
  37633. */
  37634. void layOutComponents (Component** const components,
  37635. int numComponents,
  37636. int x, int y, int width, int height,
  37637. const bool vertically,
  37638. const bool resizeOtherDimension);
  37639. /** Returns the current position of one of the items.
  37640. This is only a valid call after layOutComponents() has been called, as it
  37641. returns the last position that this item was placed at. If the layout was
  37642. vertical, the value returned will be the y position of the top of the item,
  37643. relative to the top of the rectangle in which the items were placed (so for
  37644. example, item 0 will always have position of 0, even in the rectangle passed
  37645. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  37646. the position returned is the item's left-hand position, again relative to the
  37647. x position of the rectangle used.
  37648. @see getItemCurrentSize, setItemPosition
  37649. */
  37650. int getItemCurrentPosition (const int itemIndex) const;
  37651. /** Returns the current size of one of the items.
  37652. This is only meaningful after layOutComponents() has been called, as it
  37653. returns the last size that this item was given. If the layout was done
  37654. vertically, it'll return the item's height in pixels; if it was horizontal,
  37655. it'll return its width.
  37656. @see getItemCurrentRelativeSize
  37657. */
  37658. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  37659. /** Returns the current size of one of the items.
  37660. This is only meaningful after layOutComponents() has been called, as it
  37661. returns the last size that this item was given. If the layout was done
  37662. vertically, it'll return a negative value representing the item's height relative
  37663. to the last size used for laying the components out; if the layout was done
  37664. horizontally it'll be the proportion of its width.
  37665. @see getItemCurrentAbsoluteSize
  37666. */
  37667. double getItemCurrentRelativeSize (const int itemIndex) const;
  37668. /** Moves one of the items, shifting along any other items as necessary in
  37669. order to get it to the desired position.
  37670. Calling this method will also update the preferred sizes of the items it
  37671. shuffles along, so that they reflect their new positions.
  37672. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  37673. about when it's dragged).
  37674. @param itemIndex the item to move
  37675. @param newPosition the absolute position that you'd like this item to move
  37676. to. The item might not be able to always reach exactly this position,
  37677. because other items may have minimum sizes that constrain how
  37678. far it can go
  37679. */
  37680. void setItemPosition (const int itemIndex,
  37681. int newPosition);
  37682. juce_UseDebuggingNewOperator
  37683. private:
  37684. struct ItemLayoutProperties
  37685. {
  37686. int itemIndex;
  37687. int currentSize;
  37688. double minSize, maxSize, preferredSize;
  37689. };
  37690. OwnedArray <ItemLayoutProperties> items;
  37691. int totalSize;
  37692. static int sizeToRealSize (double size, int totalSpace);
  37693. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  37694. void setTotalSize (const int newTotalSize);
  37695. int fitComponentsIntoSpace (const int startIndex,
  37696. const int endIndex,
  37697. const int availableSpace,
  37698. int startPos);
  37699. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  37700. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  37701. void updatePrefSizesToMatchCurrentPositions();
  37702. StretchableLayoutManager (const StretchableLayoutManager&);
  37703. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  37704. };
  37705. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37706. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  37707. #endif
  37708. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37709. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37710. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37711. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37712. /**
  37713. A component that acts as one of the vertical or horizontal bars you see being
  37714. used to resize panels in a window.
  37715. One of these acts with a StretchableLayoutManager to resize the other components.
  37716. @see StretchableLayoutManager
  37717. */
  37718. class JUCE_API StretchableLayoutResizerBar : public Component
  37719. {
  37720. public:
  37721. /** Creates a resizer bar for use on a specified layout.
  37722. @param layoutToUse the layout that will be affected when this bar
  37723. is dragged
  37724. @param itemIndexInLayout the item index in the layout that corresponds to
  37725. this bar component. You'll need to set up the item
  37726. properties in a suitable way for a divider bar, e.g.
  37727. for an 8-pixel wide bar which, you could call
  37728. myLayout->setItemLayout (barIndex, 8, 8, 8)
  37729. @param isBarVertical true if it's an upright bar that you drag left and
  37730. right; false for a horizontal one that you drag up and
  37731. down
  37732. */
  37733. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  37734. const int itemIndexInLayout,
  37735. const bool isBarVertical);
  37736. /** Destructor. */
  37737. ~StretchableLayoutResizerBar();
  37738. /** This is called when the bar is dragged.
  37739. This method must update the positions of any components whose position is
  37740. determined by the StretchableLayoutManager, because they might have just
  37741. moved.
  37742. The default implementation calls the resized() method of this component's
  37743. parent component, because that's often where you're likely to apply the
  37744. layout, but it can be overridden for more specific needs.
  37745. */
  37746. virtual void hasBeenMoved();
  37747. /** @internal */
  37748. void paint (Graphics& g);
  37749. /** @internal */
  37750. void mouseDown (const MouseEvent& e);
  37751. /** @internal */
  37752. void mouseDrag (const MouseEvent& e);
  37753. juce_UseDebuggingNewOperator
  37754. private:
  37755. StretchableLayoutManager* layout;
  37756. int itemIndex, mouseDownPos;
  37757. bool isVertical;
  37758. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  37759. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  37760. };
  37761. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37762. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37763. #endif
  37764. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37765. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  37766. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37767. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37768. /**
  37769. A utility class for fitting a set of objects whose sizes can vary between
  37770. a minimum and maximum size, into a space.
  37771. This is a trickier algorithm than it would first seem, so I've put it in this
  37772. class to allow it to be shared by various bits of code.
  37773. To use it, create one of these objects, call addItem() to add the list of items
  37774. you need, then call resizeToFit(), which will change all their sizes. You can
  37775. then retrieve the new sizes with getItemSize() and getNumItems().
  37776. It's currently used by the TableHeaderComponent for stretching out the table
  37777. headings to fill the table's width.
  37778. */
  37779. class StretchableObjectResizer
  37780. {
  37781. public:
  37782. /** Creates an empty object resizer. */
  37783. StretchableObjectResizer();
  37784. /** Destructor. */
  37785. ~StretchableObjectResizer();
  37786. /** Adds an item to the list.
  37787. The order parameter lets you specify groups of items that are resized first when some
  37788. space needs to be found. Those items with an order of 0 will be the first ones to be
  37789. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  37790. will then try resizing the items with an order of 1, then 2, and so on.
  37791. */
  37792. void addItem (const double currentSize,
  37793. const double minSize,
  37794. const double maxSize,
  37795. const int order = 0);
  37796. /** Resizes all the items to fit this amount of space.
  37797. This will attempt to fit them in without exceeding each item's miniumum and
  37798. maximum sizes. In cases where none of the items can be expanded or enlarged any
  37799. further, the final size may be greater or less than the size passed in.
  37800. After calling this method, you can retrieve the new sizes with the getItemSize()
  37801. method.
  37802. */
  37803. void resizeToFit (const double targetSize);
  37804. /** Returns the number of items that have been added. */
  37805. int getNumItems() const throw() { return items.size(); }
  37806. /** Returns the size of one of the items. */
  37807. double getItemSize (const int index) const throw();
  37808. juce_UseDebuggingNewOperator
  37809. private:
  37810. struct Item
  37811. {
  37812. double size;
  37813. double minSize;
  37814. double maxSize;
  37815. int order;
  37816. };
  37817. OwnedArray <Item> items;
  37818. StretchableObjectResizer (const StretchableObjectResizer&);
  37819. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  37820. };
  37821. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37822. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  37823. #endif
  37824. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  37825. #endif
  37826. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  37827. #endif
  37828. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  37829. #endif
  37830. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  37831. /********* Start of inlined file: juce_LookAndFeel.h *********/
  37832. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  37833. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  37834. /********* Start of inlined file: juce_AlertWindow.h *********/
  37835. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37836. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37837. /********* Start of inlined file: juce_TextLayout.h *********/
  37838. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  37839. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  37840. class Graphics;
  37841. /**
  37842. A laid-out arrangement of text.
  37843. You can add text in different fonts to a TextLayout object, then call its
  37844. layout() method to word-wrap it into lines. The layout can then be drawn
  37845. using a graphics context.
  37846. It's handy if you've got a message to display, because you can format it,
  37847. measure the extent of the layout, and then create a suitably-sized window
  37848. to show it in.
  37849. @see Font, Graphics::drawFittedText, GlyphArrangement
  37850. */
  37851. class JUCE_API TextLayout
  37852. {
  37853. public:
  37854. /** Creates an empty text layout.
  37855. Text can then be appended using the appendText() method.
  37856. */
  37857. TextLayout() throw();
  37858. /** Creates a copy of another layout object. */
  37859. TextLayout (const TextLayout& other) throw();
  37860. /** Creates a text layout from an initial string and font. */
  37861. TextLayout (const String& text, const Font& font) throw();
  37862. /** Destructor. */
  37863. ~TextLayout() throw();
  37864. /** Copies another layout onto this one. */
  37865. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  37866. /** Clears the layout, removing all its text. */
  37867. void clear() throw();
  37868. /** Adds a string to the end of the arrangement.
  37869. The string will be broken onto new lines wherever it contains
  37870. carriage-returns or linefeeds. After adding it, you can call layout()
  37871. to wrap long lines into a paragraph and justify it.
  37872. */
  37873. void appendText (const String& textToAppend,
  37874. const Font& fontToUse) throw();
  37875. /** Replaces all the text with a new string.
  37876. This is equivalent to calling clear() followed by appendText().
  37877. */
  37878. void setText (const String& newText,
  37879. const Font& fontToUse) throw();
  37880. /** Breaks the text up to form a paragraph with the given width.
  37881. @param maximumWidth any text wider than this will be split
  37882. across multiple lines
  37883. @param justification how the lines are to be laid-out horizontally
  37884. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  37885. width that keeps all the lines of text at a
  37886. similar length - this is good when you're displaying
  37887. a short message and don't want it to get split
  37888. onto two lines with only a couple of words on
  37889. the second line, which looks untidy.
  37890. */
  37891. void layout (int maximumWidth,
  37892. const Justification& justification,
  37893. const bool attemptToBalanceLineLengths) throw();
  37894. /** Returns the overall width of the entire text layout. */
  37895. int getWidth() const throw();
  37896. /** Returns the overall height of the entire text layout. */
  37897. int getHeight() const throw();
  37898. /** Returns the total number of lines of text. */
  37899. int getNumLines() const throw() { return totalLines; }
  37900. /** Returns the width of a particular line of text.
  37901. @param lineNumber the line, from 0 to (getNumLines() - 1)
  37902. */
  37903. int getLineWidth (const int lineNumber) const throw();
  37904. /** Renders the text at a specified position using a graphics context.
  37905. */
  37906. void draw (Graphics& g,
  37907. const int topLeftX,
  37908. const int topLeftY) const throw();
  37909. /** Renders the text within a specified rectangle using a graphics context.
  37910. The justification flags dictate how the block of text should be positioned
  37911. within the rectangle.
  37912. */
  37913. void drawWithin (Graphics& g,
  37914. int x, int y, int w, int h,
  37915. const Justification& layoutFlags) const throw();
  37916. juce_UseDebuggingNewOperator
  37917. private:
  37918. VoidArray tokens;
  37919. int totalLines;
  37920. };
  37921. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  37922. /********* End of inlined file: juce_TextLayout.h *********/
  37923. /** A window that displays a message and has buttons for the user to react to it.
  37924. For simple dialog boxes with just a couple of buttons on them, there are
  37925. some static methods for running these.
  37926. For more complex dialogs, an AlertWindow can be created, then it can have some
  37927. buttons and components added to it, and its runModalLoop() method is then used to
  37928. show it. The value returned by runModalLoop() shows which button the
  37929. user pressed to dismiss the box.
  37930. @see ThreadWithProgressWindow
  37931. */
  37932. class JUCE_API AlertWindow : public TopLevelWindow,
  37933. private ButtonListener
  37934. {
  37935. public:
  37936. /** The type of icon to show in the dialog box. */
  37937. enum AlertIconType
  37938. {
  37939. NoIcon, /**< No icon will be shown on the dialog box. */
  37940. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37941. user to answer a question. */
  37942. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37943. warning about something and shouldn't be ignored. */
  37944. InfoIcon /**< An icon that indicates that the dialog box is just
  37945. giving the user some information, which doesn't require
  37946. a response from them. */
  37947. };
  37948. /** Creates an AlertWindow.
  37949. @param title the headline to show at the top of the dialog box
  37950. @param message a longer, more descriptive message to show underneath the
  37951. headline
  37952. @param iconType the type of icon to display
  37953. @param associatedComponent if this is non-zero, it specifies the component that the
  37954. alert window should be associated with. Depending on the look
  37955. and feel, this might be used for positioning of the alert window.
  37956. */
  37957. AlertWindow (const String& title,
  37958. const String& message,
  37959. AlertIconType iconType,
  37960. Component* associatedComponent = 0);
  37961. /** Destroys the AlertWindow */
  37962. ~AlertWindow();
  37963. /** Returns the type of alert icon that was specified when the window
  37964. was created. */
  37965. AlertIconType getAlertType() const throw() { return alertIconType; }
  37966. /** Changes the dialog box's message.
  37967. This will also resize the window to fit the new message if required.
  37968. */
  37969. void setMessage (const String& message);
  37970. /** Adds a button to the window.
  37971. @param name the text to show on the button
  37972. @param returnValue the value that should be returned from runModalLoop()
  37973. if this is the button that the user presses.
  37974. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37975. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37976. */
  37977. void addButton (const String& name,
  37978. const int returnValue,
  37979. const KeyPress& shortcutKey1 = KeyPress(),
  37980. const KeyPress& shortcutKey2 = KeyPress());
  37981. /** Returns the number of buttons that the window currently has. */
  37982. int getNumButtons() const;
  37983. /** Adds a textbox to the window for entering strings.
  37984. @param name an internal name for the text-box. This is the name to pass to
  37985. the getTextEditorContents() method to find out what the
  37986. user typed-in.
  37987. @param initialContents a string to show in the text box when it's first shown
  37988. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37989. text-box to label it.
  37990. @param isPasswordBox if true, the text editor will display asterisks instead of
  37991. the actual text
  37992. @see getTextEditorContents
  37993. */
  37994. void addTextEditor (const String& name,
  37995. const String& initialContents,
  37996. const String& onScreenLabel = String::empty,
  37997. const bool isPasswordBox = false);
  37998. /** Returns the contents of a named textbox.
  37999. After showing an AlertWindow that contains a text editor, this can be
  38000. used to find out what the user has typed into it.
  38001. @param nameOfTextEditor the name of the text box that you're interested in
  38002. @see addTextEditor
  38003. */
  38004. const String getTextEditorContents (const String& nameOfTextEditor) const;
  38005. /** Adds a drop-down list of choices to the box.
  38006. After the box has been shown, the getComboBoxComponent() method can
  38007. be used to find out which item the user picked.
  38008. @param name the label to use for the drop-down list
  38009. @param items the list of items to show in it
  38010. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38011. combo-box to label it.
  38012. @see getComboBoxComponent
  38013. */
  38014. void addComboBox (const String& name,
  38015. const StringArray& items,
  38016. const String& onScreenLabel = String::empty);
  38017. /** Returns a drop-down list that was added to the AlertWindow.
  38018. @param nameOfList the name that was passed into the addComboBox() method
  38019. when creating the drop-down
  38020. @returns the ComboBox component, or 0 if none was found for the given name.
  38021. */
  38022. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  38023. /** Adds a block of text.
  38024. This is handy for adding a multi-line note next to a textbox or combo-box,
  38025. to provide more details about what's going on.
  38026. */
  38027. void addTextBlock (const String& text);
  38028. /** Adds a progress-bar to the window.
  38029. @param progressValue a variable that will be repeatedly checked while the
  38030. dialog box is visible, to see how far the process has
  38031. got. The value should be in the range 0 to 1.0
  38032. */
  38033. void addProgressBarComponent (double& progressValue);
  38034. /** Adds a user-defined component to the dialog box.
  38035. @param component the component to add - its size should be set up correctly
  38036. before it is passed in. The caller is responsible for deleting
  38037. the component later on - the AlertWindow won't delete it.
  38038. */
  38039. void addCustomComponent (Component* const component);
  38040. /** Returns the number of custom components in the dialog box.
  38041. @see getCustomComponent, addCustomComponent
  38042. */
  38043. int getNumCustomComponents() const;
  38044. /** Returns one of the custom components in the dialog box.
  38045. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38046. will return 0
  38047. @see getNumCustomComponents, addCustomComponent
  38048. */
  38049. Component* getCustomComponent (const int index) const;
  38050. /** Removes one of the custom components in the dialog box.
  38051. Note that this won't delete it, it just removes the component from the window
  38052. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38053. will return 0
  38054. @returns the component that was removed (or zero)
  38055. @see getNumCustomComponents, addCustomComponent
  38056. */
  38057. Component* removeCustomComponent (const int index);
  38058. /** Returns true if the window contains any components other than just buttons.*/
  38059. bool containsAnyExtraComponents() const;
  38060. // easy-to-use message box functions:
  38061. /** Shows a dialog box that just has a message and a single button to get rid of it.
  38062. The box is shown modally, and the method returns after the user
  38063. has clicked the button (or pressed the escape or return keys).
  38064. @param iconType the type of icon to show
  38065. @param title the headline to show at the top of the box
  38066. @param message a longer, more descriptive message to show underneath the
  38067. headline
  38068. @param buttonText the text to show in the button - if this string is empty, the
  38069. default string "ok" (or a localised version) will be used.
  38070. @param associatedComponent if this is non-zero, it specifies the component that the
  38071. alert window should be associated with. Depending on the look
  38072. and feel, this might be used for positioning of the alert window.
  38073. */
  38074. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  38075. const String& title,
  38076. const String& message,
  38077. const String& buttonText = String::empty,
  38078. Component* associatedComponent = 0);
  38079. /** Shows a dialog box with two buttons.
  38080. Ideal for ok/cancel or yes/no choices. The return key can also be used
  38081. to trigger the first button, and the escape key for the second button.
  38082. @param iconType the type of icon to show
  38083. @param title the headline to show at the top of the box
  38084. @param message a longer, more descriptive message to show underneath the
  38085. headline
  38086. @param button1Text the text to show in the first button - if this string is
  38087. empty, the default string "ok" (or a localised version of it)
  38088. will be used.
  38089. @param button2Text the text to show in the second button - if this string is
  38090. empty, the default string "cancel" (or a localised version of it)
  38091. will be used.
  38092. @param associatedComponent if this is non-zero, it specifies the component that the
  38093. alert window should be associated with. Depending on the look
  38094. and feel, this might be used for positioning of the alert window.
  38095. @returns true if button 1 was clicked, false if it was button 2
  38096. */
  38097. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  38098. const String& title,
  38099. const String& message,
  38100. const String& button1Text = String::empty,
  38101. const String& button2Text = String::empty,
  38102. Component* associatedComponent = 0);
  38103. /** Shows a dialog box with three buttons.
  38104. Ideal for yes/no/cancel boxes.
  38105. The escape key can be used to trigger the third button.
  38106. @param iconType the type of icon to show
  38107. @param title the headline to show at the top of the box
  38108. @param message a longer, more descriptive message to show underneath the
  38109. headline
  38110. @param button1Text the text to show in the first button - if an empty string, then
  38111. "yes" will be used (or a localised version of it)
  38112. @param button2Text the text to show in the first button - if an empty string, then
  38113. "no" will be used (or a localised version of it)
  38114. @param button3Text the text to show in the first button - if an empty string, then
  38115. "cancel" will be used (or a localised version of it)
  38116. @param associatedComponent if this is non-zero, it specifies the component that the
  38117. alert window should be associated with. Depending on the look
  38118. and feel, this might be used for positioning of the alert window.
  38119. @returns one of the following values:
  38120. - 0 if the third button was pressed (normally used for 'cancel')
  38121. - 1 if the first button was pressed (normally used for 'yes')
  38122. - 2 if the middle button was pressed (normally used for 'no')
  38123. */
  38124. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  38125. const String& title,
  38126. const String& message,
  38127. const String& button1Text = String::empty,
  38128. const String& button2Text = String::empty,
  38129. const String& button3Text = String::empty,
  38130. Component* associatedComponent = 0);
  38131. /** Shows an operating-system native dialog box.
  38132. @param title the title to use at the top
  38133. @param bodyText the longer message to show
  38134. @param isOkCancel if true, this will show an ok/cancel box, if false,
  38135. it'll show a box with just an ok button
  38136. @returns true if the ok button was pressed, false if they pressed cancel.
  38137. */
  38138. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  38139. const String& bodyText,
  38140. bool isOkCancel);
  38141. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  38142. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38143. methods.
  38144. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38145. */
  38146. enum ColourIds
  38147. {
  38148. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  38149. textColourId = 0x1001810, /**< The colour for the text. */
  38150. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  38151. };
  38152. juce_UseDebuggingNewOperator
  38153. protected:
  38154. /** @internal */
  38155. void paint (Graphics& g);
  38156. /** @internal */
  38157. void mouseDown (const MouseEvent& e);
  38158. /** @internal */
  38159. void mouseDrag (const MouseEvent& e);
  38160. /** @internal */
  38161. bool keyPressed (const KeyPress& key);
  38162. /** @internal */
  38163. void buttonClicked (Button* button);
  38164. /** @internal */
  38165. void lookAndFeelChanged();
  38166. /** @internal */
  38167. void userTriedToCloseWindow();
  38168. /** @internal */
  38169. int getDesktopWindowStyleFlags() const;
  38170. private:
  38171. String text;
  38172. TextLayout textLayout;
  38173. AlertIconType alertIconType;
  38174. ComponentBoundsConstrainer constrainer;
  38175. ComponentDragger dragger;
  38176. Rectangle textArea;
  38177. VoidArray buttons, textBoxes, comboBoxes;
  38178. VoidArray progressBars, customComps, textBlocks, allComps;
  38179. StringArray textboxNames, comboBoxNames;
  38180. Font font;
  38181. Component* associatedComponent;
  38182. void updateLayout (const bool onlyIncreaseSize);
  38183. // disable copy constructor
  38184. AlertWindow (const AlertWindow&);
  38185. const AlertWindow& operator= (const AlertWindow&);
  38186. };
  38187. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  38188. /********* End of inlined file: juce_AlertWindow.h *********/
  38189. class ToggleButton;
  38190. class TextButton;
  38191. class AlertWindow;
  38192. class TextLayout;
  38193. class ScrollBar;
  38194. class BubbleComponent;
  38195. class ComboBox;
  38196. class Button;
  38197. class FilenameComponent;
  38198. class DocumentWindow;
  38199. class ResizableWindow;
  38200. class GroupComponent;
  38201. class MenuBarComponent;
  38202. class DropShadower;
  38203. class GlyphArrangement;
  38204. class PropertyComponent;
  38205. class TableHeaderComponent;
  38206. class Toolbar;
  38207. class ToolbarItemComponent;
  38208. class PopupMenu;
  38209. class ProgressBar;
  38210. class FileBrowserComponent;
  38211. class DirectoryContentsDisplayComponent;
  38212. class FilePreviewComponent;
  38213. class ImageButton;
  38214. /**
  38215. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  38216. can be used to apply different 'skins' to the application.
  38217. */
  38218. class JUCE_API LookAndFeel
  38219. {
  38220. public:
  38221. /** Creates the default JUCE look and feel. */
  38222. LookAndFeel();
  38223. /** Destructor. */
  38224. virtual ~LookAndFeel();
  38225. /** Returns the current default look-and-feel for a component to use when it
  38226. hasn't got one explicitly set.
  38227. @see setDefaultLookAndFeel
  38228. */
  38229. static LookAndFeel& getDefaultLookAndFeel() throw();
  38230. /** Changes the default look-and-feel.
  38231. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  38232. set to 0, it will revert to using the default one. The
  38233. object passed-in must be deleted by the caller when
  38234. it's no longer needed.
  38235. @see getDefaultLookAndFeel
  38236. */
  38237. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  38238. /** Looks for a colour that has been registered with the given colour ID number.
  38239. If a colour has been set for this ID number using setColour(), then it is
  38240. returned. If none has been set, it will just return Colours::black.
  38241. The colour IDs for various purposes are stored as enums in the components that
  38242. they are relevent to - for an example, see Slider::ColourIds,
  38243. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  38244. If you're looking up a colour for use in drawing a component, it's usually
  38245. best not to call this directly, but to use the Component::findColour() method
  38246. instead. That will first check whether a suitable colour has been registered
  38247. directly with the component, and will fall-back on calling the component's
  38248. LookAndFeel's findColour() method if none is found.
  38249. @see setColour, Component::findColour, Component::setColour
  38250. */
  38251. const Colour findColour (const int colourId) const throw();
  38252. /** Registers a colour to be used for a particular purpose.
  38253. For more details, see the comments for findColour().
  38254. @see findColour, Component::findColour, Component::setColour
  38255. */
  38256. void setColour (const int colourId, const Colour& colour) throw();
  38257. /** Returns true if the specified colour ID has been explicitly set using the
  38258. setColour() method.
  38259. */
  38260. bool isColourSpecified (const int colourId) const throw();
  38261. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  38262. /** Allows you to change the default sans-serif font.
  38263. If you need to supply your own Typeface object for any of the default fonts, rather
  38264. than just supplying the name (e.g. if you want to use an embedded font), then
  38265. you should instead override getTypefaceForFont() to create and return the typeface.
  38266. */
  38267. void setDefaultSansSerifTypefaceName (const String& newName);
  38268. /** Override this to get the chance to swap a component's mouse cursor for a
  38269. customised one.
  38270. */
  38271. virtual const MouseCursor getMouseCursorFor (Component& component);
  38272. /** Draws the lozenge-shaped background for a standard button. */
  38273. virtual void drawButtonBackground (Graphics& g,
  38274. Button& button,
  38275. const Colour& backgroundColour,
  38276. bool isMouseOverButton,
  38277. bool isButtonDown);
  38278. virtual const Font getFontForTextButton (TextButton& button);
  38279. /** Draws the text for a TextButton. */
  38280. virtual void drawButtonText (Graphics& g,
  38281. TextButton& button,
  38282. bool isMouseOverButton,
  38283. bool isButtonDown);
  38284. /** Draws the contents of a standard ToggleButton. */
  38285. virtual void drawToggleButton (Graphics& g,
  38286. ToggleButton& button,
  38287. bool isMouseOverButton,
  38288. bool isButtonDown);
  38289. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  38290. virtual void drawTickBox (Graphics& g,
  38291. Component& component,
  38292. int x, int y, int w, int h,
  38293. const bool ticked,
  38294. const bool isEnabled,
  38295. const bool isMouseOverButton,
  38296. const bool isButtonDown);
  38297. /* AlertWindow handling..
  38298. */
  38299. virtual AlertWindow* createAlertWindow (const String& title,
  38300. const String& message,
  38301. const String& button1,
  38302. const String& button2,
  38303. const String& button3,
  38304. AlertWindow::AlertIconType iconType,
  38305. int numButtons,
  38306. Component* associatedComponent);
  38307. virtual void drawAlertBox (Graphics& g,
  38308. AlertWindow& alert,
  38309. const Rectangle& textArea,
  38310. TextLayout& textLayout);
  38311. virtual int getAlertBoxWindowFlags();
  38312. virtual int getAlertWindowButtonHeight();
  38313. virtual const Font getAlertWindowFont();
  38314. /** Draws a progress bar.
  38315. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  38316. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  38317. isn't known). It can use the current time as a basis for playing an animation.
  38318. (Used by progress bars in AlertWindow).
  38319. */
  38320. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  38321. int width, int height,
  38322. double progress, const String& textToShow);
  38323. // Draws a small image that spins to indicate that something's happening..
  38324. // This method should use the current time to animate itself, so just keep
  38325. // repainting it every so often.
  38326. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  38327. int x, int y, int w, int h);
  38328. /** Draws one of the buttons on a scrollbar.
  38329. @param g the context to draw into
  38330. @param scrollbar the bar itself
  38331. @param width the width of the button
  38332. @param height the height of the button
  38333. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  38334. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  38335. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  38336. @param isButtonDown whether the mouse button's held down
  38337. */
  38338. virtual void drawScrollbarButton (Graphics& g,
  38339. ScrollBar& scrollbar,
  38340. int width, int height,
  38341. int buttonDirection,
  38342. bool isScrollbarVertical,
  38343. bool isMouseOverButton,
  38344. bool isButtonDown);
  38345. /** Draws the thumb area of a scrollbar.
  38346. @param g the context to draw into
  38347. @param scrollbar the bar itself
  38348. @param x the x position of the left edge of the thumb area to draw in
  38349. @param y the y position of the top edge of the thumb area to draw in
  38350. @param width the width of the thumb area to draw in
  38351. @param height the height of the thumb area to draw in
  38352. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  38353. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  38354. thumb, or its x position for horizontal bars
  38355. @param thumbSize for vertical bars, the height of the thumb, or its width for
  38356. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  38357. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  38358. currently dragging the thumb
  38359. @param isMouseDown whether the mouse is currently dragging the scrollbar
  38360. */
  38361. virtual void drawScrollbar (Graphics& g,
  38362. ScrollBar& scrollbar,
  38363. int x, int y,
  38364. int width, int height,
  38365. bool isScrollbarVertical,
  38366. int thumbStartPosition,
  38367. int thumbSize,
  38368. bool isMouseOver,
  38369. bool isMouseDown);
  38370. /** Returns the component effect to use for a scrollbar */
  38371. virtual ImageEffectFilter* getScrollbarEffect();
  38372. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  38373. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  38374. /** Returns the default thickness to use for a scrollbar. */
  38375. virtual int getDefaultScrollbarWidth();
  38376. /** Returns the length in pixels to use for a scrollbar button. */
  38377. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  38378. /** Returns a tick shape for use in yes/no boxes, etc. */
  38379. virtual const Path getTickShape (const float height);
  38380. /** Returns a cross shape for use in yes/no boxes, etc. */
  38381. virtual const Path getCrossShape (const float height);
  38382. /** Draws the + or - box in a treeview. */
  38383. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  38384. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  38385. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  38386. // these return an image from the ImageCache, so use ImageCache::release() to free it
  38387. virtual Image* getDefaultFolderImage();
  38388. virtual Image* getDefaultDocumentFileImage();
  38389. virtual void createFileChooserHeaderText (const String& title,
  38390. const String& instructions,
  38391. GlyphArrangement& destArrangement,
  38392. int width);
  38393. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  38394. const String& filename, Image* icon,
  38395. const String& fileSizeDescription,
  38396. const String& fileTimeDescription,
  38397. const bool isDirectory,
  38398. const bool isItemSelected,
  38399. const int itemIndex);
  38400. virtual Button* createFileBrowserGoUpButton();
  38401. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  38402. DirectoryContentsDisplayComponent* fileListComponent,
  38403. FilePreviewComponent* previewComp,
  38404. ComboBox* currentPathBox,
  38405. TextEditor* filenameBox,
  38406. Button* goUpButton);
  38407. virtual void drawBubble (Graphics& g,
  38408. float tipX, float tipY,
  38409. float boxX, float boxY, float boxW, float boxH);
  38410. /** Fills the background of a popup menu component. */
  38411. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  38412. /** Draws one of the items in a popup menu. */
  38413. virtual void drawPopupMenuItem (Graphics& g,
  38414. int width, int height,
  38415. const bool isSeparator,
  38416. const bool isActive,
  38417. const bool isHighlighted,
  38418. const bool isTicked,
  38419. const bool hasSubMenu,
  38420. const String& text,
  38421. const String& shortcutKeyText,
  38422. Image* image,
  38423. const Colour* const textColour);
  38424. /** Returns the size and style of font to use in popup menus. */
  38425. virtual const Font getPopupMenuFont();
  38426. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  38427. int width, int height,
  38428. bool isScrollUpArrow);
  38429. /** Finds the best size for an item in a popup menu. */
  38430. virtual void getIdealPopupMenuItemSize (const String& text,
  38431. const bool isSeparator,
  38432. int standardMenuItemHeight,
  38433. int& idealWidth,
  38434. int& idealHeight);
  38435. virtual int getMenuWindowFlags();
  38436. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  38437. bool isMouseOverBar,
  38438. MenuBarComponent& menuBar);
  38439. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  38440. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  38441. virtual void drawMenuBarItem (Graphics& g,
  38442. int width, int height,
  38443. int itemIndex,
  38444. const String& itemText,
  38445. bool isMouseOverItem,
  38446. bool isMenuOpen,
  38447. bool isMouseOverBar,
  38448. MenuBarComponent& menuBar);
  38449. virtual void drawComboBox (Graphics& g, int width, int height,
  38450. const bool isButtonDown,
  38451. int buttonX, int buttonY,
  38452. int buttonW, int buttonH,
  38453. ComboBox& box);
  38454. virtual const Font getComboBoxFont (ComboBox& box);
  38455. virtual Label* createComboBoxTextBox (ComboBox& box);
  38456. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  38457. virtual void drawLabel (Graphics& g, Label& label);
  38458. virtual void drawLinearSlider (Graphics& g,
  38459. int x, int y,
  38460. int width, int height,
  38461. float sliderPos,
  38462. float minSliderPos,
  38463. float maxSliderPos,
  38464. const Slider::SliderStyle style,
  38465. Slider& slider);
  38466. virtual void drawLinearSliderBackground (Graphics& g,
  38467. int x, int y,
  38468. int width, int height,
  38469. float sliderPos,
  38470. float minSliderPos,
  38471. float maxSliderPos,
  38472. const Slider::SliderStyle style,
  38473. Slider& slider);
  38474. virtual void drawLinearSliderThumb (Graphics& g,
  38475. int x, int y,
  38476. int width, int height,
  38477. float sliderPos,
  38478. float minSliderPos,
  38479. float maxSliderPos,
  38480. const Slider::SliderStyle style,
  38481. Slider& slider);
  38482. virtual int getSliderThumbRadius (Slider& slider);
  38483. virtual void drawRotarySlider (Graphics& g,
  38484. int x, int y,
  38485. int width, int height,
  38486. float sliderPosProportional,
  38487. const float rotaryStartAngle,
  38488. const float rotaryEndAngle,
  38489. Slider& slider);
  38490. virtual Button* createSliderButton (const bool isIncrement);
  38491. virtual Label* createSliderTextBox (Slider& slider);
  38492. virtual ImageEffectFilter* getSliderEffect();
  38493. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  38494. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  38495. virtual Button* createFilenameComponentBrowseButton (const String& text);
  38496. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  38497. ComboBox* filenameBox, Button* browseButton);
  38498. virtual void drawCornerResizer (Graphics& g,
  38499. int w, int h,
  38500. bool isMouseOver,
  38501. bool isMouseDragging);
  38502. virtual void drawResizableFrame (Graphics& g,
  38503. int w, int h,
  38504. const BorderSize& borders);
  38505. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  38506. const BorderSize& border,
  38507. ResizableWindow& window);
  38508. virtual void drawResizableWindowBorder (Graphics& g,
  38509. int w, int h,
  38510. const BorderSize& border,
  38511. ResizableWindow& window);
  38512. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  38513. Graphics& g, int w, int h,
  38514. int titleSpaceX, int titleSpaceW,
  38515. const Image* icon,
  38516. bool drawTitleTextOnLeft);
  38517. virtual Button* createDocumentWindowButton (int buttonType);
  38518. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  38519. int titleBarX, int titleBarY,
  38520. int titleBarW, int titleBarH,
  38521. Button* minimiseButton,
  38522. Button* maximiseButton,
  38523. Button* closeButton,
  38524. bool positionTitleBarButtonsOnLeft);
  38525. virtual int getDefaultMenuBarHeight();
  38526. virtual DropShadower* createDropShadowerForComponent (Component* component);
  38527. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  38528. int w, int h,
  38529. bool isVerticalBar,
  38530. bool isMouseOver,
  38531. bool isMouseDragging);
  38532. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  38533. const String& text,
  38534. const Justification& position,
  38535. GroupComponent& group);
  38536. virtual void createTabButtonShape (Path& p,
  38537. int width, int height,
  38538. int tabIndex,
  38539. const String& text,
  38540. Button& button,
  38541. TabbedButtonBar::Orientation orientation,
  38542. const bool isMouseOver,
  38543. const bool isMouseDown,
  38544. const bool isFrontTab);
  38545. virtual void fillTabButtonShape (Graphics& g,
  38546. const Path& path,
  38547. const Colour& preferredBackgroundColour,
  38548. int tabIndex,
  38549. const String& text,
  38550. Button& button,
  38551. TabbedButtonBar::Orientation orientation,
  38552. const bool isMouseOver,
  38553. const bool isMouseDown,
  38554. const bool isFrontTab);
  38555. virtual void drawTabButtonText (Graphics& g,
  38556. int x, int y, int w, int h,
  38557. const Colour& preferredBackgroundColour,
  38558. int tabIndex,
  38559. const String& text,
  38560. Button& button,
  38561. TabbedButtonBar::Orientation orientation,
  38562. const bool isMouseOver,
  38563. const bool isMouseDown,
  38564. const bool isFrontTab);
  38565. virtual int getTabButtonOverlap (int tabDepth);
  38566. virtual int getTabButtonSpaceAroundImage();
  38567. virtual int getTabButtonBestWidth (int tabIndex,
  38568. const String& text,
  38569. int tabDepth,
  38570. Button& button);
  38571. virtual void drawTabButton (Graphics& g,
  38572. int w, int h,
  38573. const Colour& preferredColour,
  38574. int tabIndex,
  38575. const String& text,
  38576. Button& button,
  38577. TabbedButtonBar::Orientation orientation,
  38578. const bool isMouseOver,
  38579. const bool isMouseDown,
  38580. const bool isFrontTab);
  38581. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  38582. int w, int h,
  38583. TabbedButtonBar& tabBar,
  38584. TabbedButtonBar::Orientation orientation);
  38585. virtual Button* createTabBarExtrasButton();
  38586. virtual void drawImageButton (Graphics& g, Image* image,
  38587. int imageX, int imageY, int imageW, int imageH,
  38588. const Colour& overlayColour,
  38589. float imageOpacity,
  38590. ImageButton& button);
  38591. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  38592. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  38593. int width, int height,
  38594. bool isMouseOver, bool isMouseDown,
  38595. int columnFlags);
  38596. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  38597. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  38598. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  38599. bool isMouseOver, bool isMouseDown,
  38600. ToolbarItemComponent& component);
  38601. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  38602. const String& text, ToolbarItemComponent& component);
  38603. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  38604. bool isOpen, int width, int height);
  38605. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  38606. PropertyComponent& component);
  38607. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  38608. PropertyComponent& component);
  38609. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  38610. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  38611. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  38612. /**
  38613. */
  38614. virtual void playAlertSound();
  38615. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  38616. static void drawGlassSphere (Graphics& g,
  38617. const float x, const float y,
  38618. const float diameter,
  38619. const Colour& colour,
  38620. const float outlineThickness) throw();
  38621. static void drawGlassPointer (Graphics& g,
  38622. const float x, const float y,
  38623. const float diameter,
  38624. const Colour& colour, const float outlineThickness,
  38625. const int direction) throw();
  38626. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  38627. static void drawGlassLozenge (Graphics& g,
  38628. const float x, const float y,
  38629. const float width, const float height,
  38630. const Colour& colour,
  38631. const float outlineThickness,
  38632. const float cornerSize,
  38633. const bool flatOnLeft, const bool flatOnRight,
  38634. const bool flatOnTop, const bool flatOnBottom) throw();
  38635. juce_UseDebuggingNewOperator
  38636. protected:
  38637. // xxx the following methods are only here to cause a compiler error, because they've been
  38638. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  38639. // error if you try to build a subclass with the old versions.
  38640. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  38641. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  38642. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  38643. virtual void getTabButtonBestWidth (int, const String&, int) {}
  38644. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  38645. private:
  38646. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  38647. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  38648. Array <int> colourIds;
  38649. Array <Colour> colours;
  38650. // default typeface names
  38651. String defaultSans, defaultSerif, defaultFixed;
  38652. void drawShinyButtonShape (Graphics& g,
  38653. float x, float y, float w, float h, float maxCornerSize,
  38654. const Colour& baseColour,
  38655. const float strokeWidth,
  38656. const bool flatOnLeft,
  38657. const bool flatOnRight,
  38658. const bool flatOnTop,
  38659. const bool flatOnBottom) throw();
  38660. LookAndFeel (const LookAndFeel&);
  38661. const LookAndFeel& operator= (const LookAndFeel&);
  38662. };
  38663. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  38664. /********* End of inlined file: juce_LookAndFeel.h *********/
  38665. #endif
  38666. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38667. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  38668. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38669. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38670. /**
  38671. The original Juce look-and-feel.
  38672. */
  38673. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  38674. {
  38675. public:
  38676. /** Creates the default JUCE look and feel. */
  38677. OldSchoolLookAndFeel();
  38678. /** Destructor. */
  38679. virtual ~OldSchoolLookAndFeel();
  38680. /** Draws the lozenge-shaped background for a standard button. */
  38681. virtual void drawButtonBackground (Graphics& g,
  38682. Button& button,
  38683. const Colour& backgroundColour,
  38684. bool isMouseOverButton,
  38685. bool isButtonDown);
  38686. /** Draws the contents of a standard ToggleButton. */
  38687. virtual void drawToggleButton (Graphics& g,
  38688. ToggleButton& button,
  38689. bool isMouseOverButton,
  38690. bool isButtonDown);
  38691. virtual void drawTickBox (Graphics& g,
  38692. Component& component,
  38693. int x, int y, int w, int h,
  38694. const bool ticked,
  38695. const bool isEnabled,
  38696. const bool isMouseOverButton,
  38697. const bool isButtonDown);
  38698. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  38699. int width, int height,
  38700. double progress, const String& textToShow);
  38701. virtual void drawScrollbarButton (Graphics& g,
  38702. ScrollBar& scrollbar,
  38703. int width, int height,
  38704. int buttonDirection,
  38705. bool isScrollbarVertical,
  38706. bool isMouseOverButton,
  38707. bool isButtonDown);
  38708. virtual void drawScrollbar (Graphics& g,
  38709. ScrollBar& scrollbar,
  38710. int x, int y,
  38711. int width, int height,
  38712. bool isScrollbarVertical,
  38713. int thumbStartPosition,
  38714. int thumbSize,
  38715. bool isMouseOver,
  38716. bool isMouseDown);
  38717. virtual ImageEffectFilter* getScrollbarEffect();
  38718. virtual void drawTextEditorOutline (Graphics& g,
  38719. int width, int height,
  38720. TextEditor& textEditor);
  38721. /** Fills the background of a popup menu component. */
  38722. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  38723. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  38724. bool isMouseOverBar,
  38725. MenuBarComponent& menuBar);
  38726. virtual void drawComboBox (Graphics& g, int width, int height,
  38727. const bool isButtonDown,
  38728. int buttonX, int buttonY,
  38729. int buttonW, int buttonH,
  38730. ComboBox& box);
  38731. virtual const Font getComboBoxFont (ComboBox& box);
  38732. virtual void drawLinearSlider (Graphics& g,
  38733. int x, int y,
  38734. int width, int height,
  38735. float sliderPos,
  38736. float minSliderPos,
  38737. float maxSliderPos,
  38738. const Slider::SliderStyle style,
  38739. Slider& slider);
  38740. virtual int getSliderThumbRadius (Slider& slider);
  38741. virtual Button* createSliderButton (const bool isIncrement);
  38742. virtual ImageEffectFilter* getSliderEffect();
  38743. virtual void drawCornerResizer (Graphics& g,
  38744. int w, int h,
  38745. bool isMouseOver,
  38746. bool isMouseDragging);
  38747. virtual Button* createDocumentWindowButton (int buttonType);
  38748. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  38749. int titleBarX, int titleBarY,
  38750. int titleBarW, int titleBarH,
  38751. Button* minimiseButton,
  38752. Button* maximiseButton,
  38753. Button* closeButton,
  38754. bool positionTitleBarButtonsOnLeft);
  38755. juce_UseDebuggingNewOperator
  38756. private:
  38757. DropShadowEffect scrollbarShadow;
  38758. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  38759. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  38760. };
  38761. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38762. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  38763. #endif
  38764. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38765. #endif
  38766. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  38767. #endif
  38768. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  38769. #endif
  38770. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  38771. #endif
  38772. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  38773. #endif
  38774. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38775. #endif
  38776. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38777. #endif
  38778. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  38779. #endif
  38780. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38781. /********* Start of inlined file: juce_LassoComponent.h *********/
  38782. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38783. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38784. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  38785. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  38786. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  38787. /** Manages a list of selectable items.
  38788. Use one of these to keep a track of things that the user has highlighted, like
  38789. icons or things in a list.
  38790. The class is templated so that you can use it to hold either a set of pointers
  38791. to objects, or a set of ID numbers or handles, for cases where each item may
  38792. not always have a corresponding object.
  38793. To be informed when items are selected/deselected, register a ChangeListener with
  38794. this object.
  38795. @see SelectableObject
  38796. */
  38797. template <class SelectableItemType>
  38798. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  38799. {
  38800. public:
  38801. /** Creates an empty set. */
  38802. SelectedItemSet()
  38803. {
  38804. }
  38805. /** Creates a set based on an array of items. */
  38806. SelectedItemSet (const Array <SelectableItemType>& items)
  38807. : selectedItems (items)
  38808. {
  38809. }
  38810. /** Creates a copy of another set. */
  38811. SelectedItemSet (const SelectedItemSet& other)
  38812. : selectedItems (other.selectedItems)
  38813. {
  38814. }
  38815. /** Creates a copy of another set. */
  38816. const SelectedItemSet& operator= (const SelectedItemSet& other)
  38817. {
  38818. if (selectedItems != other.selectedItems)
  38819. {
  38820. selectedItems = other.selectedItems;
  38821. changed();
  38822. }
  38823. return *this;
  38824. }
  38825. /** Destructor. */
  38826. ~SelectedItemSet()
  38827. {
  38828. }
  38829. /** Clears any other currently selected items, and selects this item.
  38830. If this item is already the only thing selected, no change notification
  38831. will be sent out.
  38832. @see addToSelection, addToSelectionBasedOnModifiers
  38833. */
  38834. void selectOnly (SelectableItemType item)
  38835. {
  38836. if (isSelected (item))
  38837. {
  38838. for (int i = selectedItems.size(); --i >= 0;)
  38839. {
  38840. if (selectedItems.getUnchecked(i) != item)
  38841. {
  38842. deselect (selectedItems.getUnchecked(i));
  38843. i = jmin (i, selectedItems.size());
  38844. }
  38845. }
  38846. }
  38847. else
  38848. {
  38849. deselectAll();
  38850. changed();
  38851. selectedItems.add (item);
  38852. itemSelected (item);
  38853. }
  38854. }
  38855. /** Selects an item.
  38856. If the item is already selected, no change notification will be sent out.
  38857. @see selectOnly, addToSelectionBasedOnModifiers
  38858. */
  38859. void addToSelection (SelectableItemType item)
  38860. {
  38861. if (! isSelected (item))
  38862. {
  38863. changed();
  38864. selectedItems.add (item);
  38865. itemSelected (item);
  38866. }
  38867. }
  38868. /** Selects or deselects an item.
  38869. This will use the modifier keys to decide whether to deselect other items
  38870. first.
  38871. So if the shift key is held down, the item will be added without deselecting
  38872. anything (same as calling addToSelection() )
  38873. If no modifiers are down, the current selection will be cleared first (same
  38874. as calling selectOnly() )
  38875. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  38876. so it'll be added to the set unless it's already there, in which case it'll be
  38877. deselected.
  38878. If the items that you're selecting can also be dragged, you may need to use the
  38879. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  38880. subtleties of this kind of usage.
  38881. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  38882. */
  38883. void addToSelectionBasedOnModifiers (SelectableItemType item,
  38884. const ModifierKeys& modifiers)
  38885. {
  38886. if (modifiers.isShiftDown())
  38887. {
  38888. addToSelection (item);
  38889. }
  38890. else if (modifiers.isCommandDown())
  38891. {
  38892. if (isSelected (item))
  38893. deselect (item);
  38894. else
  38895. addToSelection (item);
  38896. }
  38897. else
  38898. {
  38899. selectOnly (item);
  38900. }
  38901. }
  38902. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  38903. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  38904. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  38905. makes it easy to handle multiple-selection of sets of objects that can also
  38906. be dragged.
  38907. For example, if you have several items already selected, and you click on
  38908. one of them (without dragging), then you'd expect this to deselect the other, and
  38909. just select the item you clicked on. But if you had clicked on this item and
  38910. dragged it, you'd have expected them all to stay selected.
  38911. When you call this method, you'll need to store the boolean result, because the
  38912. addToSelectionOnMouseUp() method will need to be know this value.
  38913. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  38914. */
  38915. bool addToSelectionOnMouseDown (SelectableItemType item,
  38916. const ModifierKeys& modifiers)
  38917. {
  38918. if (isSelected (item))
  38919. {
  38920. return ! modifiers.isPopupMenu();
  38921. }
  38922. else
  38923. {
  38924. addToSelectionBasedOnModifiers (item, modifiers);
  38925. return false;
  38926. }
  38927. }
  38928. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  38929. Call this during a mouseUp callback, when you have previously called the
  38930. addToSelectionOnMouseDown() method during your mouseDown event.
  38931. See addToSelectionOnMouseDown() for more info
  38932. @param item the item to select (or deselect)
  38933. @param modifiers the modifiers from the mouse-up event
  38934. @param wasItemDragged true if your item was dragged during the mouse click
  38935. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  38936. back from the addToSelectionOnMouseDown() call that you
  38937. should have made during the matching mouseDown event
  38938. */
  38939. void addToSelectionOnMouseUp (SelectableItemType item,
  38940. const ModifierKeys& modifiers,
  38941. const bool wasItemDragged,
  38942. const bool resultOfMouseDownSelectMethod)
  38943. {
  38944. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  38945. addToSelectionBasedOnModifiers (item, modifiers);
  38946. }
  38947. /** Deselects an item. */
  38948. void deselect (SelectableItemType item)
  38949. {
  38950. const int i = selectedItems.indexOf (item);
  38951. if (i >= 0)
  38952. {
  38953. changed();
  38954. itemDeselected (selectedItems.remove (i));
  38955. }
  38956. }
  38957. /** Deselects all items. */
  38958. void deselectAll()
  38959. {
  38960. if (selectedItems.size() > 0)
  38961. {
  38962. changed();
  38963. for (int i = selectedItems.size(); --i >= 0;)
  38964. {
  38965. itemDeselected (selectedItems.remove (i));
  38966. i = jmin (i, selectedItems.size());
  38967. }
  38968. }
  38969. }
  38970. /** Returns the number of currently selected items.
  38971. @see getSelectedItem
  38972. */
  38973. int getNumSelected() const throw()
  38974. {
  38975. return selectedItems.size();
  38976. }
  38977. /** Returns one of the currently selected items.
  38978. Returns 0 if the index is out-of-range.
  38979. @see getNumSelected
  38980. */
  38981. SelectableItemType getSelectedItem (const int index) const throw()
  38982. {
  38983. return selectedItems [index];
  38984. }
  38985. /** True if this item is currently selected. */
  38986. bool isSelected (const SelectableItemType item) const throw()
  38987. {
  38988. return selectedItems.contains (item);
  38989. }
  38990. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  38991. /** Can be overridden to do special handling when an item is selected.
  38992. For example, if the item is an object, you might want to call it and tell
  38993. it that it's being selected.
  38994. */
  38995. virtual void itemSelected (SelectableItemType item) {}
  38996. /** Can be overridden to do special handling when an item is deselected.
  38997. For example, if the item is an object, you might want to call it and tell
  38998. it that it's being deselected.
  38999. */
  39000. virtual void itemDeselected (SelectableItemType item) {}
  39001. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  39002. */
  39003. void changed (const bool synchronous = false)
  39004. {
  39005. if (synchronous)
  39006. sendSynchronousChangeMessage (this);
  39007. else
  39008. sendChangeMessage (this);
  39009. }
  39010. juce_UseDebuggingNewOperator
  39011. private:
  39012. Array <SelectableItemType> selectedItems;
  39013. };
  39014. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  39015. /********* End of inlined file: juce_SelectedItemSet.h *********/
  39016. /**
  39017. A class used by the LassoComponent to manage the things that it selects.
  39018. This allows the LassoComponent to find out which items are within the lasso,
  39019. and to change the list of selected items.
  39020. @see LassoComponent, SelectedItemSet
  39021. */
  39022. template <class SelectableItemType>
  39023. class LassoSource
  39024. {
  39025. public:
  39026. /** Destructor. */
  39027. virtual ~LassoSource() {}
  39028. /** Returns the set of items that lie within a given lassoable region.
  39029. Your implementation of this method must find all the relevent items that lie
  39030. within the given rectangle. and add them to the itemsFound array.
  39031. The co-ordinates are relative to the top-left of the lasso component's parent
  39032. component. (i.e. they are the same as the size and position of the lasso
  39033. component itself).
  39034. */
  39035. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  39036. int x, int y, int width, int height) = 0;
  39037. /** Returns the SelectedItemSet that the lasso should update.
  39038. This set will be continuously updated by the LassoComponent as it gets
  39039. dragged around, so make sure that you've got a ChangeListener attached to
  39040. the set so that your UI objects will know when the selection changes and
  39041. be able to update themselves appropriately.
  39042. */
  39043. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  39044. };
  39045. /**
  39046. A component that acts as a rectangular selection region, which you drag with
  39047. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  39048. To use one of these:
  39049. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  39050. component, and call its beginLasso() method, giving it a
  39051. suitable LassoSource object that it can use to find out which items are in
  39052. the active area.
  39053. - Each time your parent component gets a mouseDrag event, call dragLasso()
  39054. to update the lasso's position - it will use its LassoSource to calculate and
  39055. update the current selection.
  39056. - After the drag has finished and you get a mouseUp callback, you should call
  39057. endLasso() to clean up. This will make the lasso component invisible, and you
  39058. can remove it from the parent component, or delete it.
  39059. The class takes into account the modifier keys that are being held down while
  39060. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  39061. be added to the original selection; if ctrl or command is pressed, they will be
  39062. xor'ed with any previously selected items.
  39063. @see LassoSource, SelectedItemSet
  39064. */
  39065. template <class SelectableItemType>
  39066. class LassoComponent : public Component
  39067. {
  39068. public:
  39069. /** Creates a Lasso component.
  39070. The fill colour is used to fill the lasso'ed rectangle, and the outline
  39071. colour is used to draw a line around its edge.
  39072. */
  39073. LassoComponent (const int outlineThickness_ = 1)
  39074. : source (0),
  39075. outlineThickness (outlineThickness_)
  39076. {
  39077. }
  39078. /** Destructor. */
  39079. ~LassoComponent()
  39080. {
  39081. }
  39082. /** Call this in your mouseDown event, to initialise a drag.
  39083. Pass in a suitable LassoSource object which the lasso will use to find
  39084. the items and change the selection.
  39085. After using this method to initialise the lasso, repeatedly call dragLasso()
  39086. in your component's mouseDrag callback.
  39087. @see dragLasso, endLasso, LassoSource
  39088. */
  39089. void beginLasso (const MouseEvent& e,
  39090. LassoSource <SelectableItemType>* const lassoSource)
  39091. {
  39092. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  39093. jassert (lassoSource != 0); // the source can't be null!
  39094. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  39095. source = lassoSource;
  39096. if (lassoSource != 0)
  39097. originalSelection = lassoSource->getLassoSelection().getItemArray();
  39098. setSize (0, 0);
  39099. }
  39100. /** Call this in your mouseDrag event, to update the lasso's position.
  39101. This must be repeatedly calling when the mouse is dragged, after you've
  39102. first initialised the lasso with beginLasso().
  39103. This method takes into account the modifier keys that are being held down, so
  39104. if shift is pressed, then the lassoed items will be added to any that were
  39105. previously selected; if ctrl or command is pressed, then they will be xor'ed
  39106. with previously selected items.
  39107. @see beginLasso, endLasso
  39108. */
  39109. void dragLasso (const MouseEvent& e)
  39110. {
  39111. if (source != 0)
  39112. {
  39113. const int x1 = e.getMouseDownX();
  39114. const int y1 = e.getMouseDownY();
  39115. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  39116. setVisible (true);
  39117. Array <SelectableItemType> itemsInLasso;
  39118. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  39119. if (e.mods.isShiftDown())
  39120. {
  39121. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  39122. itemsInLasso.addArray (originalSelection);
  39123. }
  39124. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  39125. {
  39126. Array <SelectableItemType> originalMinusNew (originalSelection);
  39127. originalMinusNew.removeValuesIn (itemsInLasso);
  39128. itemsInLasso.removeValuesIn (originalSelection);
  39129. itemsInLasso.addArray (originalMinusNew);
  39130. }
  39131. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  39132. }
  39133. }
  39134. /** Call this in your mouseUp event, after the lasso has been dragged.
  39135. @see beginLasso, dragLasso
  39136. */
  39137. void endLasso()
  39138. {
  39139. source = 0;
  39140. originalSelection.clear();
  39141. setVisible (false);
  39142. }
  39143. /** A set of colour IDs to use to change the colour of various aspects of the label.
  39144. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39145. methods.
  39146. Note that you can also use the constants from TextEditor::ColourIds to change the
  39147. colour of the text editor that is opened when a label is editable.
  39148. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39149. */
  39150. enum ColourIds
  39151. {
  39152. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  39153. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  39154. };
  39155. /** @internal */
  39156. void paint (Graphics& g)
  39157. {
  39158. g.fillAll (findColour (lassoFillColourId));
  39159. g.setColour (findColour (lassoOutlineColourId));
  39160. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39161. // this suggests that you've left a lasso comp lying around after the
  39162. // mouse drag has finished.. Be careful to call endLasso() when you get a
  39163. // mouse-up event.
  39164. jassert (isMouseButtonDownAnywhere());
  39165. }
  39166. /** @internal */
  39167. bool hitTest (int x, int y) { return false; }
  39168. juce_UseDebuggingNewOperator
  39169. private:
  39170. Array <SelectableItemType> originalSelection;
  39171. LassoSource <SelectableItemType>* source;
  39172. int outlineThickness;
  39173. };
  39174. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  39175. /********* End of inlined file: juce_LassoComponent.h *********/
  39176. #endif
  39177. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  39178. #endif
  39179. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  39180. #endif
  39181. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  39182. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  39183. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  39184. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  39185. /**
  39186. Monitors a component for mouse activity, and triggers a callback
  39187. when the mouse hovers in one place for a specified length of time.
  39188. To use a hover-detector, just create one and call its setHoverComponent()
  39189. method to start it watching a component. You can call setHoverComponent (0)
  39190. to make it inactive.
  39191. (Be careful not to delete a component that's being monitored without first
  39192. stopping or deleting the hover detector).
  39193. */
  39194. class JUCE_API MouseHoverDetector
  39195. {
  39196. public:
  39197. /** Creates a hover detector.
  39198. Initially the object is inactive, and you need to tell it which component
  39199. to monitor, using the setHoverComponent() method.
  39200. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  39201. needs to stay still before the mouseHovered() method
  39202. is invoked. You can change this setting later with
  39203. the setHoverTimeMillisecs() method
  39204. */
  39205. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  39206. /** Destructor. */
  39207. virtual ~MouseHoverDetector();
  39208. /** Changes the time for which the mouse has to stay still before it's considered
  39209. to be hovering.
  39210. */
  39211. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  39212. /** Changes the component that's being monitored for hovering.
  39213. Be careful not to delete a component that's being monitored without first
  39214. stopping or deleting the hover detector.
  39215. */
  39216. void setHoverComponent (Component* const newSourceComponent);
  39217. protected:
  39218. /** Called back when the mouse hovers.
  39219. After the mouse has stayed still over the component for the length of time
  39220. specified by setHoverTimeMillisecs(), this method will be invoked.
  39221. When the mouse is first moved after this callback has occurred, the
  39222. mouseMovedAfterHover() method will be called.
  39223. @param mouseX the mouse's X position relative to the component being monitored
  39224. @param mouseY the mouse's Y position relative to the component being monitored
  39225. */
  39226. virtual void mouseHovered (int mouseX,
  39227. int mouseY) = 0;
  39228. /** Called when the mouse is moved away after just having hovered. */
  39229. virtual void mouseMovedAfterHover() = 0;
  39230. private:
  39231. class JUCE_API HoverDetectorInternal : public MouseListener,
  39232. public Timer
  39233. {
  39234. public:
  39235. MouseHoverDetector* owner;
  39236. int lastX, lastY;
  39237. void timerCallback();
  39238. void mouseEnter (const MouseEvent&);
  39239. void mouseExit (const MouseEvent&);
  39240. void mouseDown (const MouseEvent&);
  39241. void mouseUp (const MouseEvent&);
  39242. void mouseMove (const MouseEvent&);
  39243. void mouseWheelMove (const MouseEvent&, float, float);
  39244. } internalTimer;
  39245. friend class HoverDetectorInternal;
  39246. Component* source;
  39247. int hoverTimeMillisecs;
  39248. bool hasJustHovered;
  39249. void hoverTimerCallback();
  39250. void checkJustHoveredCallback();
  39251. };
  39252. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  39253. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  39254. #endif
  39255. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  39256. #endif
  39257. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  39258. #endif
  39259. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39260. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  39261. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39262. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39263. /**
  39264. A PropertyComponent that contains an on/off toggle button.
  39265. This type of property component can be used if you have a boolean value to
  39266. toggle on/off.
  39267. @see PropertyComponent
  39268. */
  39269. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  39270. private ButtonListener
  39271. {
  39272. public:
  39273. /** Creates a button component.
  39274. @param propertyName the property name to be passed to the PropertyComponent
  39275. @param buttonTextWhenTrue the text shown in the button when the value is true
  39276. @param buttonTextWhenFalse the text shown in the button when the value is false
  39277. */
  39278. BooleanPropertyComponent (const String& propertyName,
  39279. const String& buttonTextWhenTrue,
  39280. const String& buttonTextWhenFalse);
  39281. /** Destructor. */
  39282. ~BooleanPropertyComponent();
  39283. /** Called to change the state of the boolean value. */
  39284. virtual void setState (const bool newState) = 0;
  39285. /** Must return the current value of the property. */
  39286. virtual bool getState() const = 0;
  39287. /** @internal */
  39288. void paint (Graphics& g);
  39289. /** @internal */
  39290. void refresh();
  39291. /** @internal */
  39292. void buttonClicked (Button*);
  39293. juce_UseDebuggingNewOperator
  39294. private:
  39295. ToggleButton* button;
  39296. String onText, offText;
  39297. };
  39298. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39299. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  39300. #endif
  39301. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39302. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  39303. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39304. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39305. /**
  39306. A PropertyComponent that contains a button.
  39307. This type of property component can be used if you need a button to trigger some
  39308. kind of action.
  39309. @see PropertyComponent
  39310. */
  39311. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  39312. private ButtonListener
  39313. {
  39314. public:
  39315. /** Creates a button component.
  39316. @param propertyName the property name to be passed to the PropertyComponent
  39317. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  39318. */
  39319. ButtonPropertyComponent (const String& propertyName,
  39320. const bool triggerOnMouseDown);
  39321. /** Destructor. */
  39322. ~ButtonPropertyComponent();
  39323. /** Called when the user clicks the button.
  39324. */
  39325. virtual void buttonClicked() = 0;
  39326. /** Returns the string that should be displayed in the button.
  39327. If you need to change this string, call refresh() to update the component.
  39328. */
  39329. virtual const String getButtonText() const = 0;
  39330. /** @internal */
  39331. void refresh();
  39332. /** @internal */
  39333. void buttonClicked (Button*);
  39334. juce_UseDebuggingNewOperator
  39335. private:
  39336. TextButton* button;
  39337. };
  39338. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39339. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  39340. #endif
  39341. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39342. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  39343. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39344. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39345. /**
  39346. A PropertyComponent that shows its value as a combo box.
  39347. This type of property component contains a list of options and has a
  39348. combo box to choose one.
  39349. Your subclass's constructor must add some strings to the choices StringArray
  39350. and these are shown in the list.
  39351. The getIndex() method will be called to find out which option is the currently
  39352. selected one. If you call refresh() it will call getIndex() to check whether
  39353. the value has changed, and will update the combo box if needed.
  39354. If the user selects a different item from the list, setIndex() will be
  39355. called to let your class process this.
  39356. @see PropertyComponent, PropertyPanel
  39357. */
  39358. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  39359. private ComboBoxListener
  39360. {
  39361. public:
  39362. /** Creates the component.
  39363. Your subclass's constructor must add a list of options to the choices
  39364. member variable.
  39365. */
  39366. ChoicePropertyComponent (const String& propertyName);
  39367. /** Destructor. */
  39368. ~ChoicePropertyComponent();
  39369. /** Called when the user selects an item from the combo box.
  39370. Your subclass must use this callback to update the value that this component
  39371. represents. The index is the index of the chosen item in the choices
  39372. StringArray.
  39373. */
  39374. virtual void setIndex (const int newIndex) = 0;
  39375. /** Returns the index of the item that should currently be shown.
  39376. This is the index of the item in the choices StringArray that will be
  39377. shown.
  39378. */
  39379. virtual int getIndex() const = 0;
  39380. /** Returns the list of options. */
  39381. const StringArray& getChoices() const;
  39382. /** @internal */
  39383. void refresh();
  39384. /** @internal */
  39385. void comboBoxChanged (ComboBox*);
  39386. juce_UseDebuggingNewOperator
  39387. protected:
  39388. /** The list of options that will be shown in the combo box.
  39389. Your subclass must populate this array in its constructor. If any empty
  39390. strings are added, these will be replaced with horizontal separators (see
  39391. ComboBox::addSeparator() for more info).
  39392. */
  39393. StringArray choices;
  39394. private:
  39395. ComboBox* comboBox;
  39396. };
  39397. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39398. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  39399. #endif
  39400. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  39401. #endif
  39402. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  39403. #endif
  39404. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39405. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  39406. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39407. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39408. /**
  39409. A PropertyComponent that shows its value as a slider.
  39410. @see PropertyComponent, Slider
  39411. */
  39412. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  39413. private SliderListener
  39414. {
  39415. public:
  39416. /** Creates the property component.
  39417. The ranges, interval and skew factor are passed to the Slider component.
  39418. If you need to customise the slider in other ways, your constructor can
  39419. access the slider member variable and change it directly.
  39420. */
  39421. SliderPropertyComponent (const String& propertyName,
  39422. const double rangeMin,
  39423. const double rangeMax,
  39424. const double interval,
  39425. const double skewFactor = 1.0);
  39426. /** Destructor. */
  39427. ~SliderPropertyComponent();
  39428. /** Called when the user moves the slider to change its value.
  39429. Your subclass must use this method to update whatever item this property
  39430. represents.
  39431. */
  39432. virtual void setValue (const double newValue) = 0;
  39433. /** Returns the value that the slider should show. */
  39434. virtual const double getValue() const = 0;
  39435. /** @internal */
  39436. void refresh();
  39437. /** @internal */
  39438. void changeListenerCallback (void*);
  39439. /** @internal */
  39440. void sliderValueChanged (Slider*);
  39441. juce_UseDebuggingNewOperator
  39442. protected:
  39443. /** The slider component being used in this component.
  39444. Your subclass has access to this in case it needs to customise it in some way.
  39445. */
  39446. Slider* slider;
  39447. };
  39448. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39449. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  39450. #endif
  39451. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39452. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  39453. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39454. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39455. /**
  39456. A PropertyComponent that shows its value as editable text.
  39457. @see PropertyComponent
  39458. */
  39459. class JUCE_API TextPropertyComponent : public PropertyComponent
  39460. {
  39461. public:
  39462. /** Creates a text property component.
  39463. The maxNumChars is used to set the length of string allowable, and isMultiLine
  39464. sets whether the text editor allows carriage returns.
  39465. @see TextEditor
  39466. */
  39467. TextPropertyComponent (const String& propertyName,
  39468. const int maxNumChars,
  39469. const bool isMultiLine);
  39470. /** Destructor. */
  39471. ~TextPropertyComponent();
  39472. /** Called when the user edits the text.
  39473. Your subclass must use this callback to change the value of whatever item
  39474. this property component represents.
  39475. */
  39476. virtual void setText (const String& newText) = 0;
  39477. /** Returns the text that should be shown in the text editor.
  39478. */
  39479. virtual const String getText() const = 0;
  39480. /** @internal */
  39481. void refresh();
  39482. /** @internal */
  39483. void textWasEdited();
  39484. juce_UseDebuggingNewOperator
  39485. private:
  39486. Label* textEditor;
  39487. };
  39488. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39489. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  39490. #endif
  39491. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39492. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  39493. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39494. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39495. #if JUCE_WINDOWS || DOXYGEN
  39496. /**
  39497. A Windows-specific class that can create and embed an ActiveX control inside
  39498. itself.
  39499. To use it, create one of these, put it in place and make sure it's visible in a
  39500. window, then use createControl() to instantiate an ActiveX control. The control
  39501. will then be moved and resized to follow the movements of this component.
  39502. Of course, since the control is a heavyweight window, it'll obliterate any
  39503. juce components that may overlap this component, but that's life.
  39504. */
  39505. class JUCE_API ActiveXControlComponent : public Component
  39506. {
  39507. public:
  39508. /** Create an initially-empty container. */
  39509. ActiveXControlComponent();
  39510. /** Destructor. */
  39511. ~ActiveXControlComponent();
  39512. /** Tries to create an ActiveX control and embed it in this peer.
  39513. The peer controlIID is a pointer to an IID structure - it's treated
  39514. as a void* because when including the Juce headers, you might not always
  39515. have included windows.h first, in which case IID wouldn't be defined.
  39516. e.g. @code
  39517. const IID myIID = __uuidof (QTControl);
  39518. myControlComp->createControl (&myIID);
  39519. @endcode
  39520. */
  39521. bool createControl (const void* controlIID);
  39522. /** Deletes the ActiveX control, if one has been created.
  39523. */
  39524. void deleteControl();
  39525. /** Returns true if a control is currently in use. */
  39526. bool isControlOpen() const throw() { return control != 0; }
  39527. /** Does a QueryInterface call on the embedded control object.
  39528. This allows you to cast the control to whatever type of COM object you need.
  39529. The iid parameter is a pointer to an IID structure - it's treated
  39530. as a void* because when including the Juce headers, you might not always
  39531. have included windows.h first, in which case IID wouldn't be defined, but
  39532. you should just pass a pointer to an IID.
  39533. e.g. @code
  39534. const IID iid = __uuidof (IOleWindow);
  39535. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  39536. if (oleWindow != 0)
  39537. {
  39538. HWND hwnd;
  39539. oleWindow->GetWindow (&hwnd);
  39540. ...
  39541. oleWindow->Release();
  39542. }
  39543. @endcode
  39544. */
  39545. void* queryInterface (const void* iid) const;
  39546. /** Set this to false to stop mouse events being allowed through to the control.
  39547. */
  39548. void setMouseEventsAllowed (const bool eventsCanReachControl);
  39549. /** Returns true if mouse events are allowed to get through to the control.
  39550. */
  39551. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  39552. /** @internal */
  39553. void paint (Graphics& g);
  39554. /** @internal */
  39555. void* originalWndProc;
  39556. juce_UseDebuggingNewOperator
  39557. private:
  39558. friend class ActiveXControlData;
  39559. void* control;
  39560. bool mouseEventsAllowed;
  39561. ActiveXControlComponent (const ActiveXControlComponent&);
  39562. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  39563. void setControlBounds (const Rectangle& bounds) const;
  39564. void setControlVisible (const bool b) const;
  39565. };
  39566. #endif
  39567. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39568. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  39569. #endif
  39570. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39571. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39572. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39573. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39574. class MidiInputSelectorComponentListBox;
  39575. /**
  39576. A component containing controls to let the user change the audio settings of
  39577. an AudioDeviceManager object.
  39578. Very easy to use - just create one of these and show it to the user.
  39579. @see AudioDeviceManager
  39580. */
  39581. class JUCE_API AudioDeviceSelectorComponent : public Component,
  39582. public ComboBoxListener,
  39583. public ButtonListener,
  39584. public ChangeListener
  39585. {
  39586. public:
  39587. /** Creates the component.
  39588. If your app needs only output channels, you might ask for a maximum of 0 input
  39589. channels, and the component won't display any options for choosing the input
  39590. channels. And likewise if you're doing an input-only app.
  39591. @param deviceManager the device manager that this component should control
  39592. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  39593. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  39594. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  39595. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  39596. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  39597. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  39598. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  39599. treated as a set of separate mono channels.
  39600. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  39601. are shown, with an "advanced" button that shows the rest of them
  39602. */
  39603. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  39604. const int minAudioInputChannels,
  39605. const int maxAudioInputChannels,
  39606. const int minAudioOutputChannels,
  39607. const int maxAudioOutputChannels,
  39608. const bool showMidiInputOptions,
  39609. const bool showMidiOutputSelector,
  39610. const bool showChannelsAsStereoPairs,
  39611. const bool hideAdvancedOptionsWithButton);
  39612. /** Destructor */
  39613. ~AudioDeviceSelectorComponent();
  39614. /** @internal */
  39615. void resized();
  39616. /** @internal */
  39617. void comboBoxChanged (ComboBox*);
  39618. /** @internal */
  39619. void buttonClicked (Button*);
  39620. /** @internal */
  39621. void changeListenerCallback (void*);
  39622. /** @internal */
  39623. void childBoundsChanged (Component*);
  39624. juce_UseDebuggingNewOperator
  39625. private:
  39626. AudioDeviceManager& deviceManager;
  39627. ComboBox* deviceTypeDropDown;
  39628. Label* deviceTypeDropDownLabel;
  39629. Component* audioDeviceSettingsComp;
  39630. String audioDeviceSettingsCompType;
  39631. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  39632. const bool showChannelsAsStereoPairs;
  39633. const bool hideAdvancedOptionsWithButton;
  39634. MidiInputSelectorComponentListBox* midiInputsList;
  39635. Label* midiInputsLabel;
  39636. ComboBox* midiOutputSelector;
  39637. Label* midiOutputLabel;
  39638. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  39639. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  39640. };
  39641. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39642. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39643. #endif
  39644. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39645. /********* Start of inlined file: juce_BubbleComponent.h *********/
  39646. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39647. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39648. /**
  39649. A component for showing a message or other graphics inside a speech-bubble-shaped
  39650. outline, pointing at a location on the screen.
  39651. This is a base class that just draws and positions the bubble shape, but leaves
  39652. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  39653. that draws a text message.
  39654. To use it, create your subclass, then either add it to a parent component or
  39655. put it on the desktop with addToDesktop (0), use setPosition() to
  39656. resize and position it, then make it visible.
  39657. @see BubbleMessageComponent
  39658. */
  39659. class JUCE_API BubbleComponent : public Component
  39660. {
  39661. protected:
  39662. /** Creates a BubbleComponent.
  39663. Your subclass will need to implement the getContentSize() and paintContent()
  39664. methods to draw the bubble's contents.
  39665. */
  39666. BubbleComponent();
  39667. public:
  39668. /** Destructor. */
  39669. ~BubbleComponent();
  39670. /** A list of permitted placements for the bubble, relative to the co-ordinates
  39671. at which it should be pointing.
  39672. @see setAllowedPlacement
  39673. */
  39674. enum BubblePlacement
  39675. {
  39676. above = 1,
  39677. below = 2,
  39678. left = 4,
  39679. right = 8
  39680. };
  39681. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  39682. point at which it's pointing.
  39683. By default when setPosition() is called, the bubble will place itself either
  39684. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  39685. the values in BubblePlacement to restrict this choice.
  39686. E.g. if you only want your bubble to appear above or below the target area,
  39687. use setAllowedPlacement (above | below);
  39688. @see BubblePlacement
  39689. */
  39690. void setAllowedPlacement (const int newPlacement);
  39691. /** Moves and resizes the bubble to point at a given component.
  39692. This will resize the bubble to fit its content, then find a position for it
  39693. so that it's next to, but doesn't overlap the given component.
  39694. It'll put itself either above, below, or to the side of the component depending
  39695. on where there's the most space, honouring any restrictions that were set
  39696. with setAllowedPlacement().
  39697. */
  39698. void setPosition (Component* componentToPointTo);
  39699. /** Moves and resizes the bubble to point at a given point.
  39700. This will resize the bubble to fit its content, then position it
  39701. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  39702. are relative to either the bubble component's parent component if it has one, or
  39703. they are screen co-ordinates if not.
  39704. It'll put itself either above, below, or to the side of this point, depending
  39705. on where there's the most space, honouring any restrictions that were set
  39706. with setAllowedPlacement().
  39707. */
  39708. void setPosition (const int arrowTipX,
  39709. const int arrowTipY);
  39710. /** Moves and resizes the bubble to point at a given rectangle.
  39711. This will resize the bubble to fit its content, then find a position for it
  39712. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  39713. co-ordinates are relative to either the bubble component's parent component
  39714. if it has one, or they are screen co-ordinates if not.
  39715. It'll put itself either above, below, or to the side of the component depending
  39716. on where there's the most space, honouring any restrictions that were set
  39717. with setAllowedPlacement().
  39718. */
  39719. void setPosition (const Rectangle& rectangleToPointTo);
  39720. protected:
  39721. /** Subclasses should override this to return the size of the content they
  39722. want to draw inside the bubble.
  39723. */
  39724. virtual void getContentSize (int& width, int& height) = 0;
  39725. /** Subclasses should override this to draw their bubble's contents.
  39726. The graphics object's clip region and the dimensions passed in here are
  39727. set up to paint just the rectangle inside the bubble.
  39728. */
  39729. virtual void paintContent (Graphics& g, int width, int height) = 0;
  39730. public:
  39731. /** @internal */
  39732. void paint (Graphics& g);
  39733. juce_UseDebuggingNewOperator
  39734. private:
  39735. Rectangle content;
  39736. int side, allowablePlacements;
  39737. float arrowTipX, arrowTipY;
  39738. DropShadowEffect shadow;
  39739. BubbleComponent (const BubbleComponent&);
  39740. const BubbleComponent& operator= (const BubbleComponent&);
  39741. };
  39742. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39743. /********* End of inlined file: juce_BubbleComponent.h *********/
  39744. #endif
  39745. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39746. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  39747. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39748. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39749. /**
  39750. A speech-bubble component that displays a short message.
  39751. This can be used to show a message with the tail of the speech bubble
  39752. pointing to a particular component or location on the screen.
  39753. @see BubbleComponent
  39754. */
  39755. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  39756. private Timer
  39757. {
  39758. public:
  39759. /** Creates a bubble component.
  39760. After creating one a BubbleComponent, do the following:
  39761. - add it to an appropriate parent component, or put it on the
  39762. desktop with Component::addToDesktop (0).
  39763. - use the showAt() method to show a message.
  39764. - it will make itself invisible after it times-out (and can optionally
  39765. also delete itself), or you can reuse it somewhere else by calling
  39766. showAt() again.
  39767. */
  39768. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  39769. /** Destructor. */
  39770. ~BubbleMessageComponent();
  39771. /** Shows a message bubble at a particular position.
  39772. This shows the bubble with its stem pointing to the given location
  39773. (co-ordinates being relative to its parent component).
  39774. For details about exactly how it decides where to position itself, see
  39775. BubbleComponent::updatePosition().
  39776. @param x the x co-ordinate of end of the bubble's tail
  39777. @param y the y co-ordinate of end of the bubble's tail
  39778. @param message the text to display
  39779. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39780. from its parent compnent. If this is 0 or less, it
  39781. will stay there until manually removed.
  39782. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39783. mouse button is pressed (anywhere on the screen)
  39784. @param deleteSelfAfterUse if true, then the component will delete itself after
  39785. it becomes invisible
  39786. */
  39787. void showAt (int x, int y,
  39788. const String& message,
  39789. const int numMillisecondsBeforeRemoving,
  39790. const bool removeWhenMouseClicked = true,
  39791. const bool deleteSelfAfterUse = false);
  39792. /** Shows a message bubble next to a particular component.
  39793. This shows the bubble with its stem pointing at the given component.
  39794. For details about exactly how it decides where to position itself, see
  39795. BubbleComponent::updatePosition().
  39796. @param component the component that you want to point at
  39797. @param message the text to display
  39798. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39799. from its parent compnent. If this is 0 or less, it
  39800. will stay there until manually removed.
  39801. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39802. mouse button is pressed (anywhere on the screen)
  39803. @param deleteSelfAfterUse if true, then the component will delete itself after
  39804. it becomes invisible
  39805. */
  39806. void showAt (Component* const component,
  39807. const String& message,
  39808. const int numMillisecondsBeforeRemoving,
  39809. const bool removeWhenMouseClicked = true,
  39810. const bool deleteSelfAfterUse = false);
  39811. /** @internal */
  39812. void getContentSize (int& w, int& h);
  39813. /** @internal */
  39814. void paintContent (Graphics& g, int w, int h);
  39815. /** @internal */
  39816. void timerCallback();
  39817. juce_UseDebuggingNewOperator
  39818. private:
  39819. int fadeOutLength, mouseClickCounter;
  39820. TextLayout textLayout;
  39821. int64 expiryTime;
  39822. bool deleteAfterUse;
  39823. void init (const int numMillisecondsBeforeRemoving,
  39824. const bool removeWhenMouseClicked,
  39825. const bool deleteSelfAfterUse);
  39826. BubbleMessageComponent (const BubbleMessageComponent&);
  39827. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  39828. };
  39829. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39830. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  39831. #endif
  39832. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39833. /********* Start of inlined file: juce_ColourSelector.h *********/
  39834. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39835. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  39836. /**
  39837. A component that lets the user choose a colour.
  39838. This shows RGB sliders and a colourspace that the user can pick colours from.
  39839. This class is also a ChangeBroadcaster, so listeners can register to be told
  39840. when the colour changes.
  39841. */
  39842. class JUCE_API ColourSelector : public Component,
  39843. public ChangeBroadcaster,
  39844. protected SliderListener
  39845. {
  39846. public:
  39847. /** Options for the type of selector to show. These are passed into the constructor. */
  39848. enum ColourSelectorOptions
  39849. {
  39850. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  39851. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  39852. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  39853. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  39854. };
  39855. /** Creates a ColourSelector object.
  39856. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  39857. which of the selector's features should be visible.
  39858. The edgeGap value specifies the amount of space to leave around the edge.
  39859. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  39860. colourspace and hue selector components.
  39861. */
  39862. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  39863. const int edgeGap = 4,
  39864. const int gapAroundColourSpaceComponent = 7);
  39865. /** Destructor. */
  39866. ~ColourSelector();
  39867. /** Returns the colour that the user has currently selected.
  39868. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  39869. register to be told when the colour changes.
  39870. @see setCurrentColour
  39871. */
  39872. const Colour getCurrentColour() const;
  39873. /** Changes the colour that is currently being shown.
  39874. */
  39875. void setCurrentColour (const Colour& newColour);
  39876. /** Tells the selector how many preset colour swatches you want to have on the component.
  39877. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39878. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39879. their values.
  39880. */
  39881. virtual int getNumSwatches() const;
  39882. /** Called by the selector to find out the colour of one of the swatches.
  39883. Your subclass should return the colour of the swatch with the given index.
  39884. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39885. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39886. their values.
  39887. */
  39888. virtual const Colour getSwatchColour (const int index) const;
  39889. /** Called by the selector when the user puts a new colour into one of the swatches.
  39890. Your subclass should change the colour of the swatch with the given index.
  39891. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39892. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39893. their values.
  39894. */
  39895. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  39896. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39897. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39898. methods.
  39899. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39900. */
  39901. enum ColourIds
  39902. {
  39903. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  39904. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  39905. };
  39906. juce_UseDebuggingNewOperator
  39907. private:
  39908. friend class ColourSpaceView;
  39909. friend class HueSelectorComp;
  39910. Colour colour;
  39911. float h, s, v;
  39912. Slider* sliders[4];
  39913. Component* colourSpace;
  39914. Component* hueSelector;
  39915. VoidArray swatchComponents;
  39916. const int flags;
  39917. int topSpace, edgeGap;
  39918. void setHue (float newH);
  39919. void setSV (float newS, float newV);
  39920. void updateHSV();
  39921. void update();
  39922. void sliderValueChanged (Slider*);
  39923. void paint (Graphics& g);
  39924. void resized();
  39925. ColourSelector (const ColourSelector&);
  39926. const ColourSelector& operator= (const ColourSelector&);
  39927. // this constructor is here temporarily to prevent old code compiling, because the parameters
  39928. // have changed - if you get an error here, update your code to use the new constructor instead..
  39929. // (xxx - note to self: remember to remove this at some point in the future)
  39930. ColourSelector (const bool);
  39931. };
  39932. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  39933. /********* End of inlined file: juce_ColourSelector.h *********/
  39934. #endif
  39935. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39936. #endif
  39937. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39938. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  39939. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39940. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39941. /**
  39942. A component that contains another component, and can magnify or shrink it.
  39943. This component will continually update its size so that it fits the zoomed
  39944. version of the content component that you put inside it, so don't try to
  39945. change the size of this component directly - instead change that of the
  39946. content component.
  39947. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  39948. to remap mouse events correctly. This means that the content component won't
  39949. appear to be a direct child of this component, and instead will think its
  39950. on the desktop.
  39951. */
  39952. class JUCE_API MagnifierComponent : public Component
  39953. {
  39954. public:
  39955. /** Creates a MagnifierComponent.
  39956. This component will continually update its size so that it fits the zoomed
  39957. version of the content component that you put inside it, so don't try to
  39958. change the size of this component directly - instead change that of the
  39959. content component.
  39960. @param contentComponent the component to add as the magnified one
  39961. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  39962. be deleted when this component is deleted. If false,
  39963. it's the caller's responsibility to delete it later.
  39964. */
  39965. MagnifierComponent (Component* const contentComponent,
  39966. const bool deleteContentCompWhenNoLongerNeeded);
  39967. /** Destructor. */
  39968. ~MagnifierComponent();
  39969. /** Returns the current content component. */
  39970. Component* getContentComponent() const { return content; }
  39971. /** Changes the zoom level.
  39972. The scale factor must be greater than zero. Values less than 1 will shrink the
  39973. image; values greater than 1 will multiply its size by this amount.
  39974. When this is called, this component will change its size to fit the full extent
  39975. of the newly zoomed content.
  39976. */
  39977. void setScaleFactor (double newScaleFactor);
  39978. /** Returns the current zoom factor. */
  39979. double getScaleFactor() const { return scaleFactor; }
  39980. /** Changes the quality setting used to rescale the graphics.
  39981. */
  39982. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  39983. juce_UseDebuggingNewOperator
  39984. /** @internal */
  39985. void childBoundsChanged (Component*);
  39986. private:
  39987. Component* content;
  39988. Component* holderComp;
  39989. double scaleFactor;
  39990. ComponentPeer* peer;
  39991. bool deleteContent;
  39992. Graphics::ResamplingQuality quality;
  39993. void paint (Graphics& g);
  39994. void mouseDown (const MouseEvent& e);
  39995. void mouseUp (const MouseEvent& e);
  39996. void mouseDrag (const MouseEvent& e);
  39997. void mouseMove (const MouseEvent& e);
  39998. void mouseEnter (const MouseEvent& e);
  39999. void mouseExit (const MouseEvent& e);
  40000. void mouseWheelMove (const MouseEvent& e, float, float);
  40001. int scaleInt (const int n) const;
  40002. MagnifierComponent (const MagnifierComponent&);
  40003. const MagnifierComponent& operator= (const MagnifierComponent&);
  40004. };
  40005. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  40006. /********* End of inlined file: juce_MagnifierComponent.h *********/
  40007. #endif
  40008. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40009. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  40010. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40011. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40012. /**
  40013. A component that displays a piano keyboard, whose notes can be clicked on.
  40014. This component will mimic a physical midi keyboard, showing the current state of
  40015. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  40016. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  40017. Another feature is that the computer keyboard can also be used to play notes. By
  40018. default it maps the top two rows of a standard querty keyboard to the notes, but
  40019. these can be remapped if needed. It will only respond to keypresses when it has
  40020. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  40021. The component is also a ChangeBroadcaster, so if you want to be informed when the
  40022. keyboard is scrolled, you can register a ChangeListener for callbacks.
  40023. @see MidiKeyboardState
  40024. */
  40025. class JUCE_API MidiKeyboardComponent : public Component,
  40026. public MidiKeyboardStateListener,
  40027. public ChangeBroadcaster,
  40028. private Timer,
  40029. private AsyncUpdater
  40030. {
  40031. public:
  40032. /** The direction of the keyboard.
  40033. @see setOrientation
  40034. */
  40035. enum Orientation
  40036. {
  40037. horizontalKeyboard,
  40038. verticalKeyboardFacingLeft,
  40039. verticalKeyboardFacingRight,
  40040. };
  40041. /** Creates a MidiKeyboardComponent.
  40042. @param state the midi keyboard model that this component will represent
  40043. @param orientation whether the keyboard is horizonal or vertical
  40044. */
  40045. MidiKeyboardComponent (MidiKeyboardState& state,
  40046. const Orientation orientation);
  40047. /** Destructor. */
  40048. ~MidiKeyboardComponent();
  40049. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  40050. on the component.
  40051. Values are 0 to 1.0, where 1.0 is the heaviest.
  40052. @see setMidiChannel
  40053. */
  40054. void setVelocity (const float velocity, const bool useMousePositionForVelocity);
  40055. /** Changes the midi channel number that will be used for events triggered by clicking
  40056. on the component.
  40057. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  40058. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  40059. Although this is the channel used for outgoing events, the component can display
  40060. incoming events from more than one channel - see setMidiChannelsToDisplay()
  40061. @see setVelocity
  40062. */
  40063. void setMidiChannel (const int midiChannelNumber);
  40064. /** Returns the midi channel that the keyboard is using for midi messages.
  40065. @see setMidiChannel
  40066. */
  40067. int getMidiChannel() const throw() { return midiChannel; }
  40068. /** Sets a mask to indicate which incoming midi channels should be represented by
  40069. key movements.
  40070. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  40071. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  40072. in this mask, the on-screen keys will also go down.
  40073. By default, this mask is set to 0xffff (all channels displayed).
  40074. @see setMidiChannel
  40075. */
  40076. void setMidiChannelsToDisplay (const int midiChannelMask);
  40077. /** Returns the current set of midi channels represented by the component.
  40078. This is the value that was set with setMidiChannelsToDisplay().
  40079. */
  40080. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  40081. /** Changes the width used to draw the white keys. */
  40082. void setKeyWidth (const float widthInPixels);
  40083. /** Returns the width that was set by setKeyWidth(). */
  40084. float getKeyWidth() const throw() { return keyWidth; }
  40085. /** Changes the keyboard's current direction. */
  40086. void setOrientation (const Orientation newOrientation);
  40087. /** Returns the keyboard's current direction. */
  40088. const Orientation getOrientation() const throw() { return orientation; }
  40089. /** Sets the range of midi notes that the keyboard will be limited to.
  40090. By default the range is 0 to 127 (inclusive), but you can limit this if you
  40091. only want a restricted set of the keys to be shown.
  40092. Note that the values here are inclusive and must be between 0 and 127.
  40093. */
  40094. void setAvailableRange (const int lowestNote,
  40095. const int highestNote);
  40096. /** Returns the first note in the available range.
  40097. @see setAvailableRange
  40098. */
  40099. int getRangeStart() const throw() { return rangeStart; }
  40100. /** Returns the last note in the available range.
  40101. @see setAvailableRange
  40102. */
  40103. int getRangeEnd() const throw() { return rangeEnd; }
  40104. /** If the keyboard extends beyond the size of the component, this will scroll
  40105. it to show the given key at the start.
  40106. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  40107. base class to send a callback to any ChangeListeners that have been registered.
  40108. */
  40109. void setLowestVisibleKey (int noteNumber);
  40110. /** Returns the number of the first key shown in the component.
  40111. @see setLowestVisibleKey
  40112. */
  40113. int getLowestVisibleKey() const throw() { return firstKey; }
  40114. /** Returns the length of the black notes.
  40115. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  40116. */
  40117. int getBlackNoteLength() const throw() { return blackNoteLength; }
  40118. /** If set to true, then scroll buttons will appear at either end of the keyboard
  40119. if there are too many notes to fit them all in the component at once.
  40120. */
  40121. void setScrollButtonsVisible (const bool canScroll);
  40122. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  40123. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40124. methods.
  40125. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40126. */
  40127. enum ColourIds
  40128. {
  40129. whiteNoteColourId = 0x1005000,
  40130. blackNoteColourId = 0x1005001,
  40131. keySeparatorLineColourId = 0x1005002,
  40132. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  40133. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  40134. textLabelColourId = 0x1005005,
  40135. upDownButtonBackgroundColourId = 0x1005006,
  40136. upDownButtonArrowColourId = 0x1005007
  40137. };
  40138. /** Returns the position within the component of the left-hand edge of a key.
  40139. Depending on the keyboard's orientation, this may be a horizontal or vertical
  40140. distance, in either direction.
  40141. */
  40142. int getKeyStartPosition (const int midiNoteNumber) const;
  40143. /** Deletes all key-mappings.
  40144. @see setKeyPressForNote
  40145. */
  40146. void clearKeyMappings();
  40147. /** Maps a key-press to a given note.
  40148. @param key the key that should trigger the note
  40149. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  40150. be. The actual midi note that gets played will be
  40151. this value + (12 * the current base octave). To change
  40152. the base octave, see setKeyPressBaseOctave()
  40153. */
  40154. void setKeyPressForNote (const KeyPress& key,
  40155. const int midiNoteOffsetFromC);
  40156. /** Removes any key-mappings for a given note.
  40157. For a description of what the note number means, see setKeyPressForNote().
  40158. */
  40159. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  40160. /** Changes the base note above which key-press-triggered notes are played.
  40161. The set of key-mappings that trigger notes can be moved up and down to cover
  40162. the entire scale using this method.
  40163. The value passed in is an octave number between 0 and 10 (inclusive), and
  40164. indicates which C is the base note to which the key-mapped notes are
  40165. relative.
  40166. */
  40167. void setKeyPressBaseOctave (const int newOctaveNumber);
  40168. /** This sets the octave number which is shown as the octave number for middle C.
  40169. This affects only the default implementation of getWhiteNoteText(), which
  40170. passes this octave number to MidiMessage::getMidiNoteName() in order to
  40171. get the note text. See MidiMessage::getMidiNoteName() for more info about
  40172. the parameter.
  40173. By default this value is set to 3.
  40174. @see getOctaveForMiddleC
  40175. */
  40176. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  40177. /** This returns the value set by setOctaveForMiddleC().
  40178. @see setOctaveForMiddleC
  40179. */
  40180. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  40181. /** @internal */
  40182. void paint (Graphics& g);
  40183. /** @internal */
  40184. void resized();
  40185. /** @internal */
  40186. void mouseMove (const MouseEvent& e);
  40187. /** @internal */
  40188. void mouseDrag (const MouseEvent& e);
  40189. /** @internal */
  40190. void mouseDown (const MouseEvent& e);
  40191. /** @internal */
  40192. void mouseUp (const MouseEvent& e);
  40193. /** @internal */
  40194. void mouseEnter (const MouseEvent& e);
  40195. /** @internal */
  40196. void mouseExit (const MouseEvent& e);
  40197. /** @internal */
  40198. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40199. /** @internal */
  40200. void timerCallback();
  40201. /** @internal */
  40202. bool keyStateChanged (const bool isKeyDown);
  40203. /** @internal */
  40204. void focusLost (FocusChangeType cause);
  40205. /** @internal */
  40206. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  40207. /** @internal */
  40208. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  40209. /** @internal */
  40210. void handleAsyncUpdate();
  40211. /** @internal */
  40212. void colourChanged();
  40213. juce_UseDebuggingNewOperator
  40214. protected:
  40215. friend class MidiKeyboardUpDownButton;
  40216. /** Draws a white note in the given rectangle.
  40217. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  40218. currently pressed down.
  40219. When doing this, be sure to note the keyboard's orientation.
  40220. */
  40221. virtual void drawWhiteNote (int midiNoteNumber,
  40222. Graphics& g,
  40223. int x, int y, int w, int h,
  40224. bool isDown, bool isOver,
  40225. const Colour& lineColour,
  40226. const Colour& textColour);
  40227. /** Draws a black note in the given rectangle.
  40228. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  40229. currently pressed down.
  40230. When doing this, be sure to note the keyboard's orientation.
  40231. */
  40232. virtual void drawBlackNote (int midiNoteNumber,
  40233. Graphics& g,
  40234. int x, int y, int w, int h,
  40235. bool isDown, bool isOver,
  40236. const Colour& noteFillColour);
  40237. /** Allows text to be drawn on the white notes.
  40238. By default this is used to label the C in each octave, but could be used for other things.
  40239. @see setOctaveForMiddleC
  40240. */
  40241. virtual const String getWhiteNoteText (const int midiNoteNumber);
  40242. /** Draws the up and down buttons that change the base note. */
  40243. virtual void drawUpDownButton (Graphics& g, int w, int h,
  40244. const bool isMouseOver,
  40245. const bool isButtonPressed,
  40246. const bool movesOctavesUp);
  40247. /** Callback when the mouse is clicked on a key.
  40248. You could use this to do things like handle right-clicks on keys, etc.
  40249. Return true if you want the click to trigger the note, or false if you
  40250. want to handle it yourself and not have the note played.
  40251. @see mouseDraggedToKey
  40252. */
  40253. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  40254. /** Callback when the mouse is dragged from one key onto another.
  40255. @see mouseDownOnKey
  40256. */
  40257. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  40258. /** Calculates the positon of a given midi-note.
  40259. This can be overridden to create layouts with custom key-widths.
  40260. @param midiNoteNumber the note to find
  40261. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  40262. @param x the x position of the left-hand edge of the key (this method
  40263. always works in terms of a horizontal keyboard)
  40264. @param w the width of the key
  40265. */
  40266. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  40267. int& x, int& w) const;
  40268. private:
  40269. MidiKeyboardState& state;
  40270. int xOffset, blackNoteLength;
  40271. float keyWidth;
  40272. Orientation orientation;
  40273. int midiChannel, midiInChannelMask;
  40274. float velocity;
  40275. int noteUnderMouse, mouseDownNote;
  40276. BitArray keysPressed, keysCurrentlyDrawnDown;
  40277. int rangeStart, rangeEnd, firstKey;
  40278. bool canScroll, mouseDragging, useMousePositionForVelocity;
  40279. Button* scrollDown;
  40280. Button* scrollUp;
  40281. Array <KeyPress> keyPresses;
  40282. Array <int> keyPressNotes;
  40283. int keyMappingOctave;
  40284. int octaveNumForMiddleC;
  40285. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  40286. int xyToNote (int x, int y, float& mousePositionVelocity);
  40287. int remappedXYToNote (int x, int y, float& mousePositionVelocity) const;
  40288. void resetAnyKeysInUse();
  40289. void updateNoteUnderMouse (int x, int y);
  40290. void repaintNote (const int midiNoteNumber);
  40291. MidiKeyboardComponent (const MidiKeyboardComponent&);
  40292. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  40293. };
  40294. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40295. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  40296. #endif
  40297. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40298. /********* Start of inlined file: juce_NSViewComponent.h *********/
  40299. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40300. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40301. #if ! DOXYGEN
  40302. class NSViewComponentInternal;
  40303. #endif
  40304. #if JUCE_MAC || DOXYGEN
  40305. /**
  40306. A Mac-specific class that can create and embed an NSView inside itself.
  40307. To use it, create one of these, put it in place and make sure it's visible in a
  40308. window, then use setView() to assign an NSView to it. The view will then be
  40309. moved and resized to follow the movements of this component.
  40310. Of course, since the view is a native object, it'll obliterate any
  40311. juce components that may overlap this component, but that's life.
  40312. */
  40313. class JUCE_API NSViewComponent : public Component
  40314. {
  40315. public:
  40316. /** Create an initially-empty container. */
  40317. NSViewComponent();
  40318. /** Destructor. */
  40319. ~NSViewComponent();
  40320. /** Assigns an NSView to this peer.
  40321. The view will be retained and released by this component for as long as
  40322. it is needed. To remove the current view, just call setView (0).
  40323. Note: a void* is used here to avoid including the cocoa headers as
  40324. part of the juce.h, but the method expects an NSView*.
  40325. */
  40326. void setView (void* nsView);
  40327. /** Returns the current NSView.
  40328. Note: a void* is returned here to avoid including the cocoa headers as
  40329. a requirement of juce.h, so you should just cast the object to an NSView*.
  40330. */
  40331. void* getView() const;
  40332. /** @internal */
  40333. void paint (Graphics& g);
  40334. juce_UseDebuggingNewOperator
  40335. private:
  40336. friend class NSViewComponentInternal;
  40337. ScopedPointer <NSViewComponentInternal> info;
  40338. NSViewComponent (const NSViewComponent&);
  40339. const NSViewComponent& operator= (const NSViewComponent&);
  40340. };
  40341. #endif
  40342. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40343. /********* End of inlined file: juce_NSViewComponent.h *********/
  40344. #endif
  40345. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40346. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  40347. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40348. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40349. // this is used to disable OpenGL, and is defined in juce_Config.h
  40350. #if JUCE_OPENGL || DOXYGEN
  40351. class OpenGLComponentWatcher;
  40352. /**
  40353. Represents the various properties of an OpenGL bitmap format.
  40354. @see OpenGLComponent::setPixelFormat
  40355. */
  40356. class JUCE_API OpenGLPixelFormat
  40357. {
  40358. public:
  40359. /** Creates an OpenGLPixelFormat.
  40360. The default constructor just initialises the object as a simple 8-bit
  40361. RGBA format.
  40362. */
  40363. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  40364. const int alphaBits = 8,
  40365. const int depthBufferBits = 16,
  40366. const int stencilBufferBits = 0) throw();
  40367. int redBits; /**< The number of bits per pixel to use for the red channel. */
  40368. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  40369. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  40370. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  40371. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  40372. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  40373. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  40374. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  40375. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  40376. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  40377. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  40378. /** Returns a list of all the pixel formats that can be used in this system.
  40379. A reference component is needed in case there are multiple screens with different
  40380. capabilities - in which case, the one that the component is on will be used.
  40381. */
  40382. static void getAvailablePixelFormats (Component* component,
  40383. OwnedArray <OpenGLPixelFormat>& results);
  40384. bool operator== (const OpenGLPixelFormat&) const throw();
  40385. juce_UseDebuggingNewOperator
  40386. };
  40387. /**
  40388. A base class for types of OpenGL context.
  40389. An OpenGLComponent will supply its own context for drawing in its window.
  40390. */
  40391. class JUCE_API OpenGLContext
  40392. {
  40393. public:
  40394. /** Destructor. */
  40395. virtual ~OpenGLContext();
  40396. /** Makes this context the currently active one. */
  40397. virtual bool makeActive() const throw() = 0;
  40398. /** If this context is currently active, it is disactivated. */
  40399. virtual bool makeInactive() const throw() = 0;
  40400. /** Returns true if this context is currently active. */
  40401. virtual bool isActive() const throw() = 0;
  40402. /** Swaps the buffers (if the context can do this). */
  40403. virtual void swapBuffers() = 0;
  40404. /** Sets whether the context checks the vertical sync before swapping.
  40405. The value is the number of frames to allow between buffer-swapping. This is
  40406. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  40407. and greater numbers indicate that it should swap less often.
  40408. Returns true if it sets the value successfully.
  40409. */
  40410. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  40411. /** Returns the current swap-sync interval.
  40412. See setSwapInterval() for info about the value returned.
  40413. */
  40414. virtual int getSwapInterval() const = 0;
  40415. /** Returns the pixel format being used by this context. */
  40416. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  40417. /** For windowed contexts, this moves the context within the bounds of
  40418. its parent window.
  40419. */
  40420. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  40421. /** For windowed contexts, this triggers a repaint of the window.
  40422. (Not relevent on all platforms).
  40423. */
  40424. virtual void repaint() = 0;
  40425. /** Returns an OS-dependent handle to the raw GL context.
  40426. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  40427. a GLXContext.
  40428. */
  40429. virtual void* getRawContext() const throw() = 0;
  40430. /** This tries to create a context that can be used for drawing into the
  40431. area occupied by the specified component.
  40432. Note that you probably shouldn't use this method directly unless you know what
  40433. you're doing - the OpenGLComponent calls this and manages the context for you.
  40434. */
  40435. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  40436. const OpenGLPixelFormat& pixelFormat,
  40437. const OpenGLContext* const contextToShareWith);
  40438. /** Returns the context that's currently in active use by the calling thread.
  40439. Returns 0 if there isn't an active context.
  40440. */
  40441. static OpenGLContext* getCurrentContext();
  40442. juce_UseDebuggingNewOperator
  40443. protected:
  40444. OpenGLContext() throw();
  40445. };
  40446. /**
  40447. A component that contains an OpenGL canvas.
  40448. Override this, add it to whatever component you want to, and use the renderOpenGL()
  40449. method to draw its contents.
  40450. */
  40451. class JUCE_API OpenGLComponent : public Component
  40452. {
  40453. public:
  40454. /** Creates an OpenGLComponent.
  40455. */
  40456. OpenGLComponent();
  40457. /** Destructor. */
  40458. ~OpenGLComponent();
  40459. /** Changes the pixel format used by this component.
  40460. @see OpenGLPixelFormat::getAvailablePixelFormats()
  40461. */
  40462. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  40463. /** Returns the pixel format that this component is currently using. */
  40464. const OpenGLPixelFormat getPixelFormat() const;
  40465. /** Specifies an OpenGL context which should be shared with the one that this
  40466. component is using.
  40467. This is an OpenGL feature that lets two contexts share their texture data.
  40468. Note that this pointer is stored by the component, and when the component
  40469. needs to recreate its internal context for some reason, the same context
  40470. will be used again to share lists. So if you pass a context in here,
  40471. don't delete the context while this component is still using it! You can
  40472. call shareWith (0) to stop this component from sharing with it.
  40473. */
  40474. void shareWith (OpenGLContext* contextToShareListsWith);
  40475. /** Returns the context that this component is sharing with.
  40476. @see shareWith
  40477. */
  40478. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  40479. /** Flips the openGL buffers over. */
  40480. void swapBuffers();
  40481. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  40482. When this is called, makeCurrentContextActive() will already have been called
  40483. for you, so you just need to draw.
  40484. */
  40485. virtual void renderOpenGL() = 0;
  40486. /** This method is called when the component creates a new OpenGL context.
  40487. A new context may be created when the component is first used, or when it
  40488. is moved to a different window, or when the window is hidden and re-shown,
  40489. etc.
  40490. You can use this callback as an opportunity to set up things like textures
  40491. that your context needs.
  40492. New contexts are created on-demand by the makeCurrentContextActive() method - so
  40493. if the context is deleted, e.g. by changing the pixel format or window, no context
  40494. will be created until the next call to makeCurrentContextActive(), which will
  40495. synchronously create one and call this method. This means that if you're using
  40496. a non-GUI thread for rendering, you can make sure this method is be called by
  40497. your renderer thread.
  40498. When this callback happens, the context will already have been made current
  40499. using the makeCurrentContextActive() method, so there's no need to call it
  40500. again in your code.
  40501. */
  40502. virtual void newOpenGLContextCreated() = 0;
  40503. /** Returns the context that will draw into this component.
  40504. This may return 0 if the component is currently invisible or hasn't currently
  40505. got a context. The context object can be deleted and a new one created during
  40506. the lifetime of this component, and there may be times when it doesn't have one.
  40507. @see newOpenGLContextCreated()
  40508. */
  40509. OpenGLContext* getCurrentContext() const throw() { return context; }
  40510. /** Makes this component the current openGL context.
  40511. You might want to use this in things like your resize() method, before calling
  40512. GL commands.
  40513. If this returns false, then the context isn't active, so you should avoid
  40514. making any calls.
  40515. This call may actually create a context if one isn't currently initialised. If
  40516. it does this, it will also synchronously call the newOpenGLContextCreated()
  40517. method to let you initialise it as necessary.
  40518. @see OpenGLContext::makeActive
  40519. */
  40520. bool makeCurrentContextActive();
  40521. /** Stops the current component being the active OpenGL context.
  40522. This is the opposite of makeCurrentContextActive()
  40523. @see OpenGLContext::makeInactive
  40524. */
  40525. void makeCurrentContextInactive();
  40526. /** Returns true if this component is the active openGL context for the
  40527. current thread.
  40528. @see OpenGLContext::isActive
  40529. */
  40530. bool isActiveContext() const throw();
  40531. /** Calls the rendering callback, and swaps the buffers afterwards.
  40532. This is called automatically by paint() when the component needs to be rendered.
  40533. It can be overridden if you need to decouple the rendering from the paint callback
  40534. and render with a custom thread.
  40535. Returns true if the operation succeeded.
  40536. */
  40537. virtual bool renderAndSwapBuffers();
  40538. /** This returns a critical section that can be used to lock the current context.
  40539. Because the context that is used by this component can change, e.g. when the
  40540. component is shown or hidden, then if you're rendering to it on a background
  40541. thread, this allows you to lock the context for the duration of your rendering
  40542. routine.
  40543. */
  40544. CriticalSection& getContextLock() throw() { return contextLock; }
  40545. /** @internal */
  40546. void paint (Graphics& g);
  40547. /** Returns the native handle of an embedded heavyweight window, if there is one.
  40548. E.g. On windows, this will return the HWND of the sub-window containing
  40549. the opengl context, on the mac it'll be the NSOpenGLView.
  40550. */
  40551. void* getNativeWindowHandle() const;
  40552. juce_UseDebuggingNewOperator
  40553. private:
  40554. friend class OpenGLComponentWatcher;
  40555. OpenGLComponentWatcher* componentWatcher;
  40556. OpenGLContext* context;
  40557. OpenGLContext* contextToShareListsWith;
  40558. CriticalSection contextLock;
  40559. OpenGLPixelFormat preferredPixelFormat;
  40560. bool needToUpdateViewport;
  40561. void deleteContext();
  40562. void updateContextPosition();
  40563. void internalRepaint (int x, int y, int w, int h);
  40564. OpenGLComponent (const OpenGLComponent&);
  40565. const OpenGLComponent& operator= (const OpenGLComponent&);
  40566. };
  40567. #endif
  40568. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40569. /********* End of inlined file: juce_OpenGLComponent.h *********/
  40570. #endif
  40571. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40572. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  40573. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40574. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40575. /**
  40576. A component with a set of buttons at the top for changing between pages of
  40577. preferences.
  40578. This is just a handy way of writing a Mac-style preferences panel where you
  40579. have a row of buttons along the top for the different preference categories,
  40580. each button having an icon above its name. Clicking these will show an
  40581. appropriate prefs page below it.
  40582. You can either put one of these inside your own component, or just use the
  40583. showInDialogBox() method to show it in a window and run it modally.
  40584. To use it, just add a set of named pages with the addSettingsPage() method,
  40585. and implement the createComponentForPage() method to create suitable components
  40586. for each of these pages.
  40587. */
  40588. class JUCE_API PreferencesPanel : public Component,
  40589. private ButtonListener
  40590. {
  40591. public:
  40592. /** Creates an empty panel.
  40593. Use addSettingsPage() to add some pages to it in your constructor.
  40594. */
  40595. PreferencesPanel();
  40596. /** Destructor. */
  40597. ~PreferencesPanel();
  40598. /** Creates a page using a set of drawables to define the page's icon.
  40599. Note that the other version of this method is much easier if you're using
  40600. an image instead of a custom drawable.
  40601. @param pageTitle the name of this preferences page - you'll need to
  40602. make sure your createComponentForPage() method creates
  40603. a suitable component when it is passed this name
  40604. @param normalIcon the drawable to display in the page's button normally
  40605. @param overIcon the drawable to display in the page's button when the mouse is over
  40606. @param downIcon the drawable to display in the page's button when the button is down
  40607. @see DrawableButton
  40608. */
  40609. void addSettingsPage (const String& pageTitle,
  40610. const Drawable* normalIcon,
  40611. const Drawable* overIcon,
  40612. const Drawable* downIcon);
  40613. /** Creates a page using a set of drawables to define the page's icon.
  40614. The other version of this method gives you more control over the icon, but this
  40615. one is much easier if you're just loading it from a file.
  40616. @param pageTitle the name of this preferences page - you'll need to
  40617. make sure your createComponentForPage() method creates
  40618. a suitable component when it is passed this name
  40619. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  40620. For this to look good, you'll probably want to use a nice
  40621. transparent png file.
  40622. @param imageDataSize the size of the image data, in bytes
  40623. */
  40624. void addSettingsPage (const String& pageTitle,
  40625. const char* imageData,
  40626. const int imageDataSize);
  40627. /** Utility method to display this panel in a DialogWindow.
  40628. Calling this will create a DialogWindow containing this panel with the
  40629. given size and title, and will run it modally, returning when the user
  40630. closes the dialog box.
  40631. */
  40632. void showInDialogBox (const String& dialogtitle,
  40633. int dialogWidth,
  40634. int dialogHeight,
  40635. const Colour& backgroundColour = Colours::white);
  40636. /** Subclasses must override this to return a component for each preferences page.
  40637. The subclass should return a pointer to a new component representing the named
  40638. page, which the panel will then display.
  40639. The panel will delete the component later when the user goes to another page
  40640. or deletes the panel.
  40641. */
  40642. virtual Component* createComponentForPage (const String& pageName) = 0;
  40643. /** Changes the current page being displayed. */
  40644. void setCurrentPage (const String& pageName);
  40645. /** @internal */
  40646. void resized();
  40647. /** @internal */
  40648. void paint (Graphics& g);
  40649. /** @internal */
  40650. void buttonClicked (Button* button);
  40651. juce_UseDebuggingNewOperator
  40652. private:
  40653. String currentPageName;
  40654. ScopedPointer <Component> currentPage;
  40655. int buttonSize;
  40656. PreferencesPanel (const PreferencesPanel&);
  40657. const PreferencesPanel& operator= (const PreferencesPanel&);
  40658. };
  40659. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40660. /********* End of inlined file: juce_PreferencesPanel.h *********/
  40661. #endif
  40662. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40663. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  40664. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40665. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40666. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  40667. // amalgamated build)
  40668. #if JUCE_WINDOWS
  40669. typedef ActiveXControlComponent QTCompBaseClass;
  40670. #elif JUCE_MAC
  40671. typedef NSViewComponent QTCompBaseClass;
  40672. #endif
  40673. // this is used to disable QuickTime, and is defined in juce_Config.h
  40674. #if JUCE_QUICKTIME || DOXYGEN
  40675. /**
  40676. A window that can play back a QuickTime movie.
  40677. */
  40678. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  40679. {
  40680. public:
  40681. /** Creates a QuickTimeMovieComponent, initially blank.
  40682. Use the loadMovie() method to load a movie once you've added the
  40683. component to a window, (or put it on the desktop as a heavyweight window).
  40684. Loading a movie when the component isn't visible can cause problems, as
  40685. QuickTime needs a window handle to initialise properly.
  40686. */
  40687. QuickTimeMovieComponent();
  40688. /** Destructor. */
  40689. ~QuickTimeMovieComponent();
  40690. /** Returns true if QT is installed and working on this machine.
  40691. */
  40692. static bool isQuickTimeAvailable() throw();
  40693. /** Tries to load a QuickTime movie from a file into the player.
  40694. It's best to call this function once you've added the component to a window,
  40695. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40696. component isn't visible can cause problems, because QuickTime needs a window
  40697. handle to do its stuff.
  40698. @param movieFile the .mov file to open
  40699. @param isControllerVisible whether to show a controller bar at the bottom
  40700. @returns true if the movie opens successfully
  40701. */
  40702. bool loadMovie (const File& movieFile,
  40703. const bool isControllerVisible);
  40704. /** Tries to load a QuickTime movie from a URL into the player.
  40705. It's best to call this function once you've added the component to a window,
  40706. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40707. component isn't visible can cause problems, because QuickTime needs a window
  40708. handle to do its stuff.
  40709. @param movieURL the .mov file to open
  40710. @param isControllerVisible whether to show a controller bar at the bottom
  40711. @returns true if the movie opens successfully
  40712. */
  40713. bool loadMovie (const URL& movieURL,
  40714. const bool isControllerVisible);
  40715. /** Tries to load a QuickTime movie from a stream into the player.
  40716. It's best to call this function once you've added the component to a window,
  40717. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40718. component isn't visible can cause problems, because QuickTime needs a window
  40719. handle to do its stuff.
  40720. @param movieStream a stream containing a .mov file. The component may try
  40721. to read the whole stream before playing, rather than
  40722. streaming from it.
  40723. @param isControllerVisible whether to show a controller bar at the bottom
  40724. @returns true if the movie opens successfully
  40725. */
  40726. bool loadMovie (InputStream* movieStream,
  40727. const bool isControllerVisible);
  40728. /** Closes the movie, if one is open. */
  40729. void closeMovie();
  40730. /** Returns the movie file that is currently open.
  40731. If there isn't one, this returns File::nonexistent
  40732. */
  40733. const File getCurrentMovieFile() const;
  40734. /** Returns true if there's currently a movie open. */
  40735. bool isMovieOpen() const;
  40736. /** Returns the length of the movie, in seconds. */
  40737. double getMovieDuration() const;
  40738. /** Returns the movie's natural size, in pixels.
  40739. You can use this to resize the component to show the movie at its preferred
  40740. scale.
  40741. If no movie is loaded, the size returned will be 0 x 0.
  40742. */
  40743. void getMovieNormalSize (int& width, int& height) const;
  40744. /** This will position the component within a given area, keeping its aspect
  40745. ratio correct according to the movie's normal size.
  40746. The component will be made as large as it can go within the space, and will
  40747. be aligned according to the justification value if this means there are gaps at
  40748. the top or sides.
  40749. */
  40750. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  40751. const RectanglePlacement& placement);
  40752. /** Starts the movie playing. */
  40753. void play();
  40754. /** Stops the movie playing. */
  40755. void stop();
  40756. /** Returns true if the movie is currently playing. */
  40757. bool isPlaying() const;
  40758. /** Moves the movie's position back to the start. */
  40759. void goToStart();
  40760. /** Sets the movie's position to a given time. */
  40761. void setPosition (const double seconds);
  40762. /** Returns the current play position of the movie. */
  40763. double getPosition() const;
  40764. /** Changes the movie playback rate.
  40765. A value of 1 is normal speed, greater values play it proportionately faster,
  40766. smaller values play it slower.
  40767. */
  40768. void setSpeed (const float newSpeed);
  40769. /** Changes the movie's playback volume.
  40770. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  40771. */
  40772. void setMovieVolume (const float newVolume);
  40773. /** Returns the movie's playback volume.
  40774. @returns the volume in the range 0 (silent) to 1.0 (full)
  40775. */
  40776. float getMovieVolume() const;
  40777. /** Tells the movie whether it should loop. */
  40778. void setLooping (const bool shouldLoop);
  40779. /** Returns true if the movie is currently looping.
  40780. @see setLooping
  40781. */
  40782. bool isLooping() const;
  40783. /** True if the native QuickTime controller bar is shown in the window.
  40784. @see loadMovie
  40785. */
  40786. bool isControllerVisible() const;
  40787. /** @internal */
  40788. void paint (Graphics& g);
  40789. juce_UseDebuggingNewOperator
  40790. private:
  40791. File movieFile;
  40792. bool movieLoaded, controllerVisible, looping;
  40793. #if JUCE_WINDOWS
  40794. /** @internal */
  40795. void parentHierarchyChanged();
  40796. /** @internal */
  40797. void visibilityChanged();
  40798. void createControlIfNeeded();
  40799. bool isControlCreated() const;
  40800. void* internal;
  40801. #else
  40802. void* movie;
  40803. #endif
  40804. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  40805. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  40806. };
  40807. #endif
  40808. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40809. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  40810. #endif
  40811. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40812. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  40813. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40814. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40815. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  40816. /**
  40817. On Windows only, this component sits in the taskbar tray as a small icon.
  40818. To use it, just create one of these components, but don't attempt to make it
  40819. visible, add it to a parent, or put it on the desktop.
  40820. You can then call setIconImage() to create an icon for it in the taskbar.
  40821. To change the icon's tooltip, you can use setIconTooltip().
  40822. To respond to mouse-events, you can override the normal mouseDown(),
  40823. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  40824. position will not be valid, you can use this to respond to clicks. Traditionally
  40825. you'd use a left-click to show your application's window, and a right-click
  40826. to show a pop-up menu.
  40827. */
  40828. class JUCE_API SystemTrayIconComponent : public Component
  40829. {
  40830. public:
  40831. SystemTrayIconComponent();
  40832. /** Destructor. */
  40833. ~SystemTrayIconComponent();
  40834. /** Changes the image shown in the taskbar.
  40835. */
  40836. void setIconImage (const Image& newImage);
  40837. /** Changes the tooltip that Windows shows above the icon. */
  40838. void setIconTooltip (const String& tooltip);
  40839. #if JUCE_LINUX
  40840. /** @internal */
  40841. void paint (Graphics& g);
  40842. #endif
  40843. juce_UseDebuggingNewOperator
  40844. private:
  40845. SystemTrayIconComponent (const SystemTrayIconComponent&);
  40846. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  40847. };
  40848. #endif
  40849. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40850. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  40851. #endif
  40852. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40853. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  40854. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40855. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40856. #if JUCE_WEB_BROWSER || DOXYGEN
  40857. #if ! DOXYGEN
  40858. class WebBrowserComponentInternal;
  40859. #endif
  40860. /**
  40861. A component that displays an embedded web browser.
  40862. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  40863. Windows, probably IE.
  40864. */
  40865. class JUCE_API WebBrowserComponent : public Component
  40866. {
  40867. public:
  40868. /** Creates a WebBrowserComponent.
  40869. Once it's created and visible, send the browser to a URL using goToURL().
  40870. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  40871. component is taken offscreen, it'll clear the current page
  40872. and replace it with a blank page - this can be handy to stop
  40873. the browser using resources in the background when it's not
  40874. actually being used.
  40875. */
  40876. WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden = true);
  40877. /** Destructor. */
  40878. ~WebBrowserComponent();
  40879. /** Sends the browser to a particular URL.
  40880. @param url the URL to go to.
  40881. @param headers an optional set of parameters to put in the HTTP header. If
  40882. you supply this, it should be a set of string in the form
  40883. "HeaderKey: HeaderValue"
  40884. @param postData an optional block of data that will be attached to the HTTP
  40885. POST request
  40886. */
  40887. void goToURL (const String& url,
  40888. const StringArray* headers = 0,
  40889. const MemoryBlock* postData = 0);
  40890. /** Stops the current page loading.
  40891. */
  40892. void stop();
  40893. /** Sends the browser back one page.
  40894. */
  40895. void goBack();
  40896. /** Sends the browser forward one page.
  40897. */
  40898. void goForward();
  40899. /** Refreshes the browser.
  40900. */
  40901. void refresh();
  40902. /** This callback is called when the browser is about to navigate
  40903. to a new location.
  40904. You can override this method to perform some action when the user
  40905. tries to go to a particular URL. To allow the operation to carry on,
  40906. return true, or return false to stop the navigation happening.
  40907. */
  40908. virtual bool pageAboutToLoad (const String& newURL);
  40909. /** @internal */
  40910. void paint (Graphics& g);
  40911. /** @internal */
  40912. void resized();
  40913. /** @internal */
  40914. void parentHierarchyChanged();
  40915. /** @internal */
  40916. void visibilityChanged();
  40917. juce_UseDebuggingNewOperator
  40918. private:
  40919. WebBrowserComponentInternal* browser;
  40920. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  40921. String lastURL;
  40922. StringArray lastHeaders;
  40923. MemoryBlock lastPostData;
  40924. void reloadLastURL();
  40925. void checkWindowAssociation();
  40926. WebBrowserComponent (const WebBrowserComponent&);
  40927. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  40928. };
  40929. #endif
  40930. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40931. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  40932. #endif
  40933. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  40934. #endif
  40935. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  40936. #endif
  40937. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  40938. /********* Start of inlined file: juce_DialogWindow.h *********/
  40939. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  40940. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  40941. /**
  40942. A dialog-box style window.
  40943. This class is a convenient way of creating a DocumentWindow with a close button
  40944. that can be triggered by pressing the escape key.
  40945. Any of the methods available to a DocumentWindow or ResizableWindow are also
  40946. available to this, so it can be made resizable, have a menu bar, etc.
  40947. To add items to the box, see the ResizableWindow::setContentComponent() method.
  40948. Don't add components directly to this class - always put them in a content component!
  40949. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  40950. the user clicking the close button - for more info, see the DocumentWindow
  40951. help.
  40952. @see DocumentWindow, ResizableWindow
  40953. */
  40954. class JUCE_API DialogWindow : public DocumentWindow
  40955. {
  40956. public:
  40957. /** Creates a DialogWindow.
  40958. @param name the name to give the component - this is also
  40959. the title shown at the top of the window. To change
  40960. this later, use setName()
  40961. @param backgroundColour the colour to use for filling the window's background.
  40962. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  40963. close button to be triggered
  40964. @param addToDesktop if true, the window will be automatically added to the
  40965. desktop; if false, you can use it as a child component
  40966. */
  40967. DialogWindow (const String& name,
  40968. const Colour& backgroundColour,
  40969. const bool escapeKeyTriggersCloseButton,
  40970. const bool addToDesktop = true);
  40971. /** Destructor.
  40972. If a content component has been set with setContentComponent(), it
  40973. will be deleted.
  40974. */
  40975. ~DialogWindow();
  40976. /** Easy way of quickly showing a dialog box containing a given component.
  40977. This will open and display a DialogWindow containing a given component, returning
  40978. when the user clicks its close button.
  40979. It returns the value that was returned by the dialog box's runModalLoop() call.
  40980. To close the dialog programatically, you should call exitModalState (returnValue) on
  40981. the DialogWindow that is created. To find a pointer to this window from your
  40982. contentComponent, you can do something like this:
  40983. @code
  40984. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  40985. if (dw != 0)
  40986. dw->exitModalState (1234);
  40987. @endcode
  40988. @param dialogTitle the dialog box's title
  40989. @param contentComponent the content component for the dialog box. Make sure
  40990. that this has been set to the size you want it to
  40991. be before calling this method. The component won't
  40992. be deleted by this call, so you can re-use it or delete
  40993. it afterwards
  40994. @param componentToCentreAround if this is non-zero, it indicates a component that
  40995. you'd like to show this dialog box in front of. See the
  40996. DocumentWindow::centreAroundComponent() method for more
  40997. info on this parameter
  40998. @param backgroundColour a colour to use for the dialog box's background colour
  40999. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  41000. close button to be triggered
  41001. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  41002. a corner resizer
  41003. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  41004. to use a border or corner resizer component. See ResizableWindow::setResizable()
  41005. */
  41006. static int showModalDialog (const String& dialogTitle,
  41007. Component* contentComponent,
  41008. Component* componentToCentreAround,
  41009. const Colour& backgroundColour,
  41010. const bool escapeKeyTriggersCloseButton,
  41011. const bool shouldBeResizable = false,
  41012. const bool useBottomRightCornerResizer = false);
  41013. juce_UseDebuggingNewOperator
  41014. protected:
  41015. /** @internal */
  41016. void resized();
  41017. private:
  41018. bool escapeKeyTriggersCloseButton;
  41019. DialogWindow (const DialogWindow&);
  41020. const DialogWindow& operator= (const DialogWindow&);
  41021. };
  41022. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  41023. /********* End of inlined file: juce_DialogWindow.h *********/
  41024. #endif
  41025. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  41026. #endif
  41027. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41028. #endif
  41029. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  41030. /********* Start of inlined file: juce_SplashScreen.h *********/
  41031. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  41032. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  41033. /** A component for showing a splash screen while your app starts up.
  41034. This will automatically position itself, and delete itself when the app has
  41035. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  41036. this).
  41037. To use it, just create one of these in your JUCEApplication::initialise() method,
  41038. call its show() method and let the object delete itself later.
  41039. E.g. @code
  41040. void MyApp::initialise (const String& commandLine)
  41041. {
  41042. SplashScreen* splash = new SplashScreen();
  41043. splash->show (T("welcome to my app"),
  41044. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  41045. 4000, false);
  41046. .. no need to delete the splash screen - it'll do that itself.
  41047. }
  41048. @endcode
  41049. */
  41050. class JUCE_API SplashScreen : public Component,
  41051. public Timer,
  41052. private DeletedAtShutdown
  41053. {
  41054. public:
  41055. /** Creates a SplashScreen object.
  41056. After creating one of these (or your subclass of it), call one of the show()
  41057. methods to display it.
  41058. */
  41059. SplashScreen();
  41060. /** Destructor. */
  41061. ~SplashScreen();
  41062. /** Creates a SplashScreen object that will display an image.
  41063. As soon as this is called, the SplashScreen will be displayed in the centre of the
  41064. screen. This method will also dispatch any pending messages to make sure that when
  41065. it returns, the splash screen has been completely drawn, and your initialisation
  41066. code can carry on.
  41067. @param title the name to give the component
  41068. @param backgroundImage an image to draw on the component. The component's size
  41069. will be set to the size of this image, and if the image is
  41070. semi-transparent, the component will be made semi-transparent
  41071. too. This image will be deleted (or released from the ImageCache
  41072. if that's how it was created) by the splash screen object when
  41073. it is itself deleted.
  41074. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  41075. should stay visible for. If the initialisation takes longer than
  41076. this time, the splash screen will wait for it to finish before
  41077. disappearing, but if initialisation is very quick, this lets
  41078. you make sure that people get a good look at your splash.
  41079. @param useDropShadow if true, the window will have a drop shadow
  41080. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  41081. the mouse (anywhere)
  41082. */
  41083. void show (const String& title,
  41084. Image* const backgroundImage,
  41085. const int minimumTimeToDisplayFor,
  41086. const bool useDropShadow,
  41087. const bool removeOnMouseClick = true);
  41088. /** Creates a SplashScreen object with a specified size.
  41089. For a custom splash screen, you can use this method to display it at a certain size
  41090. and then override the paint() method yourself to do whatever's necessary.
  41091. As soon as this is called, the SplashScreen will be displayed in the centre of the
  41092. screen. This method will also dispatch any pending messages to make sure that when
  41093. it returns, the splash screen has been completely drawn, and your initialisation
  41094. code can carry on.
  41095. @param title the name to give the component
  41096. @param width the width to use
  41097. @param height the height to use
  41098. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  41099. should stay visible for. If the initialisation takes longer than
  41100. this time, the splash screen will wait for it to finish before
  41101. disappearing, but if initialisation is very quick, this lets
  41102. you make sure that people get a good look at your splash.
  41103. @param useDropShadow if true, the window will have a drop shadow
  41104. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  41105. the mouse (anywhere)
  41106. */
  41107. void show (const String& title,
  41108. const int width,
  41109. const int height,
  41110. const int minimumTimeToDisplayFor,
  41111. const bool useDropShadow,
  41112. const bool removeOnMouseClick = true);
  41113. /** @internal */
  41114. void paint (Graphics& g);
  41115. /** @internal */
  41116. void timerCallback();
  41117. juce_UseDebuggingNewOperator
  41118. private:
  41119. Image* backgroundImage;
  41120. Time earliestTimeToDelete;
  41121. int originalClickCounter;
  41122. SplashScreen (const SplashScreen&);
  41123. const SplashScreen& operator= (const SplashScreen&);
  41124. };
  41125. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  41126. /********* End of inlined file: juce_SplashScreen.h *********/
  41127. #endif
  41128. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  41129. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  41130. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  41131. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  41132. /**
  41133. A thread that automatically pops up a modal dialog box with a progress bar
  41134. and cancel button while it's busy running.
  41135. These are handy for performing some sort of task while giving the user feedback
  41136. about how long there is to go, etc.
  41137. E.g. @code
  41138. class MyTask : public ThreadWithProgressWindow
  41139. {
  41140. public:
  41141. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  41142. {
  41143. }
  41144. ~MyTask()
  41145. {
  41146. }
  41147. void run()
  41148. {
  41149. for (int i = 0; i < thingsToDo; ++i)
  41150. {
  41151. // must check this as often as possible, because this is
  41152. // how we know if the user's pressed 'cancel'
  41153. if (threadShouldExit())
  41154. break;
  41155. // this will update the progress bar on the dialog box
  41156. setProgress (i / (double) thingsToDo);
  41157. // ... do the business here...
  41158. }
  41159. }
  41160. };
  41161. void doTheTask()
  41162. {
  41163. MyTask m;
  41164. if (m.runThread())
  41165. {
  41166. // thread finished normally..
  41167. }
  41168. else
  41169. {
  41170. // user pressed the cancel button..
  41171. }
  41172. }
  41173. @endcode
  41174. @see Thread, AlertWindow
  41175. */
  41176. class JUCE_API ThreadWithProgressWindow : public Thread,
  41177. private Timer
  41178. {
  41179. public:
  41180. /** Creates the thread.
  41181. Initially, the dialog box won't be visible, it'll only appear when the
  41182. runThread() method is called.
  41183. @param windowTitle the title to go at the top of the dialog box
  41184. @param hasProgressBar whether the dialog box should have a progress bar (see
  41185. setProgress() )
  41186. @param hasCancelButton whether the dialog box should have a cancel button
  41187. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  41188. the thread to stop before killing it forcibly (see
  41189. Thread::stopThread() )
  41190. @param cancelButtonText the text that should be shown in the cancel button
  41191. (if it has one)
  41192. */
  41193. ThreadWithProgressWindow (const String& windowTitle,
  41194. const bool hasProgressBar,
  41195. const bool hasCancelButton,
  41196. const int timeOutMsWhenCancelling = 10000,
  41197. const String& cancelButtonText = JUCE_T("Cancel"));
  41198. /** Destructor. */
  41199. ~ThreadWithProgressWindow();
  41200. /** Starts the thread and waits for it to finish.
  41201. This will start the thread, make the dialog box appear, and wait until either
  41202. the thread finishes normally, or until the cancel button is pressed.
  41203. Before returning, the dialog box will be hidden.
  41204. @param threadPriority the priority to use when starting the thread - see
  41205. Thread::startThread() for values
  41206. @returns true if the thread finished normally; false if the user pressed cancel
  41207. */
  41208. bool runThread (const int threadPriority = 5);
  41209. /** The thread should call this periodically to update the position of the progress bar.
  41210. @param newProgress the progress, from 0.0 to 1.0
  41211. @see setStatusMessage
  41212. */
  41213. void setProgress (const double newProgress);
  41214. /** The thread can call this to change the message that's displayed in the dialog box.
  41215. */
  41216. void setStatusMessage (const String& newStatusMessage);
  41217. /** Returns the AlertWindow that is being used.
  41218. */
  41219. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  41220. juce_UseDebuggingNewOperator
  41221. private:
  41222. void timerCallback();
  41223. double progress;
  41224. ScopedPointer <AlertWindow> alertWindow;
  41225. String message;
  41226. CriticalSection messageLock;
  41227. const int timeOutMsWhenCancelling;
  41228. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  41229. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  41230. };
  41231. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  41232. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  41233. #endif
  41234. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  41235. #endif
  41236. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41237. #endif
  41238. #ifndef __JUCE_COLOUR_JUCEHEADER__
  41239. #endif
  41240. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  41241. #endif
  41242. #ifndef __JUCE_COLOURS_JUCEHEADER__
  41243. #endif
  41244. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  41245. #endif
  41246. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  41247. #endif
  41248. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  41249. #endif
  41250. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  41251. #endif
  41252. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  41253. #endif
  41254. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41255. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  41256. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41257. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41258. /**
  41259. Interface class for graphics context objects, used internally by the Graphics class.
  41260. Users are not supposed to create instances of this class directly - do your drawing
  41261. via the Graphics object instead.
  41262. It's a base class for different types of graphics context, that may perform software-based
  41263. or OS-accelerated rendering.
  41264. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  41265. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  41266. context.
  41267. */
  41268. class JUCE_API LowLevelGraphicsContext
  41269. {
  41270. protected:
  41271. LowLevelGraphicsContext();
  41272. public:
  41273. virtual ~LowLevelGraphicsContext();
  41274. /** Returns true if this device is vector-based, e.g. a printer. */
  41275. virtual bool isVectorDevice() const = 0;
  41276. /** Moves the origin to a new position.
  41277. The co-ords are relative to the current origin, and indicate the new position
  41278. of (0, 0).
  41279. */
  41280. virtual void setOrigin (int x, int y) = 0;
  41281. virtual bool clipToRectangle (const Rectangle& r) = 0;
  41282. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  41283. virtual void excludeClipRectangle (const Rectangle& r) = 0;
  41284. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  41285. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform) = 0;
  41286. virtual bool clipRegionIntersects (const Rectangle& r) = 0;
  41287. virtual const Rectangle getClipBounds() const = 0;
  41288. virtual bool isClipEmpty() const = 0;
  41289. virtual void saveState() = 0;
  41290. virtual void restoreState() = 0;
  41291. virtual void setFill (const FillType& fillType) = 0;
  41292. virtual void setOpacity (float newOpacity) = 0;
  41293. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  41294. virtual void fillRect (const Rectangle& r, const bool replaceExistingContents) = 0;
  41295. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  41296. virtual void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  41297. const AffineTransform& transform, const bool fillEntireClipAsTiles) = 0;
  41298. virtual void drawLine (double x1, double y1, double x2, double y2) = 0;
  41299. virtual void drawVerticalLine (const int x, double top, double bottom) = 0;
  41300. virtual void drawHorizontalLine (const int y, double left, double right) = 0;
  41301. virtual void setFont (const Font& newFont) = 0;
  41302. virtual const Font getFont() = 0;
  41303. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  41304. };
  41305. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41306. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  41307. #endif
  41308. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41309. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  41310. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41311. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41312. /**
  41313. An implementation of LowLevelGraphicsContext that turns the drawing operations
  41314. into a PostScript document.
  41315. */
  41316. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  41317. {
  41318. public:
  41319. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  41320. const String& documentTitle,
  41321. const int totalWidth,
  41322. const int totalHeight);
  41323. ~LowLevelGraphicsPostScriptRenderer();
  41324. bool isVectorDevice() const;
  41325. void setOrigin (int x, int y);
  41326. bool clipToRectangle (const Rectangle& r);
  41327. bool clipToRectangleList (const RectangleList& clipRegion);
  41328. void excludeClipRectangle (const Rectangle& r);
  41329. void clipToPath (const Path& path, const AffineTransform& transform);
  41330. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  41331. void saveState();
  41332. void restoreState();
  41333. bool clipRegionIntersects (const Rectangle& r);
  41334. const Rectangle getClipBounds() const;
  41335. bool isClipEmpty() const;
  41336. void setFill (const FillType& fillType);
  41337. void setOpacity (float opacity);
  41338. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  41339. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  41340. void fillPath (const Path& path, const AffineTransform& transform);
  41341. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  41342. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  41343. void drawLine (double x1, double y1, double x2, double y2);
  41344. void drawVerticalLine (const int x, double top, double bottom);
  41345. void drawHorizontalLine (const int x, double top, double bottom);
  41346. const Font getFont();
  41347. void setFont (const Font& newFont);
  41348. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  41349. juce_UseDebuggingNewOperator
  41350. protected:
  41351. OutputStream& out;
  41352. int totalWidth, totalHeight;
  41353. bool needToClip;
  41354. Colour lastColour;
  41355. struct SavedState
  41356. {
  41357. SavedState();
  41358. ~SavedState();
  41359. RectangleList clip;
  41360. int xOffset, yOffset;
  41361. FillType fillType;
  41362. Font font;
  41363. private:
  41364. const SavedState& operator= (const SavedState&);
  41365. };
  41366. OwnedArray <SavedState> stateStack;
  41367. void writeClip();
  41368. void writeColour (const Colour& colour);
  41369. void writePath (const Path& path) const;
  41370. void writeXY (const float x, const float y) const;
  41371. void writeTransform (const AffineTransform& trans) const;
  41372. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  41373. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  41374. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  41375. };
  41376. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41377. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  41378. #endif
  41379. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41380. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  41381. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41382. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41383. class LLGCSavedState;
  41384. /**
  41385. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  41386. its rendering in memory.
  41387. User code is not supposed to create instances of this class directly - do all your
  41388. rendering via the Graphics class instead.
  41389. */
  41390. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  41391. {
  41392. public:
  41393. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  41394. ~LowLevelGraphicsSoftwareRenderer();
  41395. bool isVectorDevice() const;
  41396. void setOrigin (int x, int y);
  41397. bool clipToRectangle (const Rectangle& r);
  41398. bool clipToRectangleList (const RectangleList& clipRegion);
  41399. void excludeClipRectangle (const Rectangle& r);
  41400. void clipToPath (const Path& path, const AffineTransform& transform);
  41401. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  41402. bool clipRegionIntersects (const Rectangle& r);
  41403. const Rectangle getClipBounds() const;
  41404. bool isClipEmpty() const;
  41405. void saveState();
  41406. void restoreState();
  41407. void setFill (const FillType& fillType);
  41408. void setOpacity (float opacity);
  41409. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  41410. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  41411. void fillPath (const Path& path, const AffineTransform& transform);
  41412. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  41413. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  41414. void drawLine (double x1, double y1, double x2, double y2);
  41415. void drawVerticalLine (const int x, double top, double bottom);
  41416. void drawHorizontalLine (const int x, double top, double bottom);
  41417. void setFont (const Font& newFont);
  41418. const Font getFont();
  41419. void drawGlyph (int glyphNumber, float x, float y);
  41420. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  41421. juce_UseDebuggingNewOperator
  41422. protected:
  41423. Image& image;
  41424. ScopedPointer <LLGCSavedState> currentState;
  41425. OwnedArray <LLGCSavedState> stateStack;
  41426. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  41427. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  41428. };
  41429. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41430. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  41431. #endif
  41432. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  41433. #endif
  41434. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  41435. #endif
  41436. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41437. /********* Start of inlined file: juce_DrawableComposite.h *********/
  41438. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41439. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41440. /**
  41441. A drawable object which acts as a container for a set of other Drawables.
  41442. @see Drawable
  41443. */
  41444. class JUCE_API DrawableComposite : public Drawable
  41445. {
  41446. public:
  41447. /** Creates a composite Drawable.
  41448. */
  41449. DrawableComposite();
  41450. /** Destructor. */
  41451. virtual ~DrawableComposite();
  41452. /** Adds a new sub-drawable to this one.
  41453. This passes in a Drawable pointer for this object to look after. To add a copy
  41454. of a drawable, use the form of this method that takes a Drawable reference instead.
  41455. @param drawable the object to add - this will be deleted automatically
  41456. when no longer needed, so the caller mustn't keep any
  41457. pointers to it.
  41458. @param transform the transform to apply to this drawable when it's being
  41459. drawn
  41460. @param index where to insert it in the list of drawables. 0 is the back,
  41461. -1 is the front, or any value from 0 and getNumDrawables()
  41462. can be used
  41463. @see removeDrawable
  41464. */
  41465. void insertDrawable (Drawable* drawable,
  41466. const AffineTransform& transform = AffineTransform::identity,
  41467. const int index = -1);
  41468. /** Adds a new sub-drawable to this one.
  41469. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  41470. for this object to look after, use the form of this method that takes a Drawable
  41471. pointer instead.
  41472. @param drawable the object to add - an internal copy will be made of this object
  41473. @param transform the transform to apply to this drawable when it's being
  41474. drawn
  41475. @param index where to insert it in the list of drawables. 0 is the back,
  41476. -1 is the front, or any value from 0 and getNumDrawables()
  41477. can be used
  41478. @see removeDrawable
  41479. */
  41480. void insertDrawable (const Drawable& drawable,
  41481. const AffineTransform& transform = AffineTransform::identity,
  41482. const int index = -1);
  41483. /** Deletes one of the Drawable objects.
  41484. @param index the index of the drawable to delete, between 0
  41485. and (getNumDrawables() - 1).
  41486. @param deleteDrawable if this is true, the drawable that is removed will also
  41487. be deleted. If false, it'll just be removed.
  41488. @see insertDrawable, getNumDrawables
  41489. */
  41490. void removeDrawable (const int index, const bool deleteDrawable = true);
  41491. /** Returns the number of drawables contained inside this one.
  41492. @see getDrawable
  41493. */
  41494. int getNumDrawables() const throw() { return drawables.size(); }
  41495. /** Returns one of the drawables that are contained in this one.
  41496. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  41497. to find it.
  41498. The pointer returned is managed by this object and will be deleted when no longer
  41499. needed, so be careful what you do with it.
  41500. @see getNumDrawables
  41501. */
  41502. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  41503. /** Returns the transform that applies to one of the drawables that are contained in this one.
  41504. The pointer returned is managed by this object and will be deleted when no longer
  41505. needed, so be careful what you do with it.
  41506. @see getNumDrawables
  41507. */
  41508. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  41509. /** Brings one of the Drawables to the front.
  41510. @param index the index of the drawable to move, between 0
  41511. and (getNumDrawables() - 1).
  41512. @see insertDrawable, getNumDrawables
  41513. */
  41514. void bringToFront (const int index);
  41515. /** @internal */
  41516. void render (const Drawable::RenderingContext& context) const;
  41517. /** @internal */
  41518. void getBounds (float& x, float& y, float& width, float& height) const;
  41519. /** @internal */
  41520. bool hitTest (float x, float y) const;
  41521. /** @internal */
  41522. Drawable* createCopy() const;
  41523. /** @internal */
  41524. ValueTree createValueTree() const throw();
  41525. /** @internal */
  41526. static DrawableComposite* createFromValueTree (const ValueTree& tree) throw();
  41527. juce_UseDebuggingNewOperator
  41528. private:
  41529. OwnedArray <Drawable> drawables;
  41530. OwnedArray <AffineTransform> transforms;
  41531. DrawableComposite (const DrawableComposite&);
  41532. const DrawableComposite& operator= (const DrawableComposite&);
  41533. };
  41534. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41535. /********* End of inlined file: juce_DrawableComposite.h *********/
  41536. #endif
  41537. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41538. /********* Start of inlined file: juce_DrawableImage.h *********/
  41539. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41540. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41541. /**
  41542. A drawable object which is a bitmap image.
  41543. @see Drawable
  41544. */
  41545. class JUCE_API DrawableImage : public Drawable
  41546. {
  41547. public:
  41548. DrawableImage();
  41549. /** Destructor. */
  41550. virtual ~DrawableImage();
  41551. /** Sets the image that this drawable will render.
  41552. An internal copy is made of the image passed-in. If you want to provide an
  41553. image that this object can take charge of without needing to create a copy,
  41554. use the other setImage() method.
  41555. */
  41556. void setImage (const Image& imageToCopy);
  41557. /** Sets the image that this drawable will render.
  41558. An internal copy of this will not be made, so the caller mustn't delete
  41559. the image while it's still being used by this object.
  41560. A good way to use this is with the ImageCache - if you create an image
  41561. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  41562. it'll be released neatly with its reference count being decreased.
  41563. @param imageToUse the image to render
  41564. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  41565. then the image will be deleted when this object no longer
  41566. needs it - unless the image was created by the ImageCache,
  41567. in which case it will be released with ImageCache::release().
  41568. */
  41569. void setImage (Image* imageToUse,
  41570. const bool releaseWhenNotNeeded);
  41571. /** Returns the current image. */
  41572. Image* getImage() const throw() { return image; }
  41573. /** Clears (and possibly deletes) the currently set image. */
  41574. void clearImage();
  41575. /** Sets the opacity to use when drawing the image. */
  41576. void setOpacity (const float newOpacity);
  41577. /** Returns the image's opacity. */
  41578. float getOpacity() const throw() { return opacity; }
  41579. /** Sets a colour to draw over the image's alpha channel.
  41580. By default this is transparent so isn't drawn, but if you set a non-transparent
  41581. colour here, then it will be overlaid on the image, using the image's alpha
  41582. channel as a mask.
  41583. This is handy for doing things like darkening or lightening an image by overlaying
  41584. it with semi-transparent black or white.
  41585. */
  41586. void setOverlayColour (const Colour& newOverlayColour);
  41587. /** Returns the overlay colour. */
  41588. const Colour& getOverlayColour() const throw() { return overlayColour; }
  41589. /** @internal */
  41590. void render (const Drawable::RenderingContext& context) const;
  41591. /** @internal */
  41592. void getBounds (float& x, float& y, float& width, float& height) const;
  41593. /** @internal */
  41594. bool hitTest (float x, float y) const;
  41595. /** @internal */
  41596. Drawable* createCopy() const;
  41597. /** @internal */
  41598. ValueTree createValueTree() const throw();
  41599. /** @internal */
  41600. static DrawableImage* createFromValueTree (const ValueTree& tree) throw();
  41601. juce_UseDebuggingNewOperator
  41602. private:
  41603. Image* image;
  41604. bool canDeleteImage;
  41605. float opacity;
  41606. Colour overlayColour;
  41607. DrawableImage (const DrawableImage&);
  41608. const DrawableImage& operator= (const DrawableImage&);
  41609. };
  41610. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41611. /********* End of inlined file: juce_DrawableImage.h *********/
  41612. #endif
  41613. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  41614. /********* Start of inlined file: juce_DrawablePath.h *********/
  41615. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  41616. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  41617. /**
  41618. A drawable object which renders a filled or outlined shape.
  41619. @see Drawable
  41620. */
  41621. class JUCE_API DrawablePath : public Drawable
  41622. {
  41623. public:
  41624. /** Creates a DrawablePath.
  41625. */
  41626. DrawablePath();
  41627. /** Destructor. */
  41628. virtual ~DrawablePath();
  41629. /** Changes the path that will be drawn.
  41630. @see setFillColour, setStrokeType
  41631. */
  41632. void setPath (const Path& newPath) throw();
  41633. /** Returns the current path. */
  41634. const Path& getPath() const throw() { return path; }
  41635. /** Sets a fill type for the path.
  41636. This colour is used to fill the path - if you don't want the path to be
  41637. filled (e.g. if you're just drawing an outline), set this to a transparent
  41638. colour.
  41639. @see setPath, setStrokeFill
  41640. */
  41641. void setFill (const FillType& newFill) throw();
  41642. /** Returns the current fill type.
  41643. @see setFill
  41644. */
  41645. const FillType& getFill() const throw() { return mainFill; }
  41646. /** Sets the fill type with which the outline will be drawn.
  41647. @see setFill
  41648. */
  41649. void setStrokeFill (const FillType& newStrokeFill) throw();
  41650. /** Returns the current stroke fill.
  41651. @see setStrokeFill
  41652. */
  41653. const FillType& getStrokeFill() const throw() { return strokeFill; }
  41654. /** Changes the properties of the outline that will be drawn around the path.
  41655. If the stroke has 0 thickness, no stroke will be drawn.
  41656. @see setStrokeThickness, setStrokeColour
  41657. */
  41658. void setStrokeType (const PathStrokeType& newStrokeType) throw();
  41659. /** Changes the stroke thickness.
  41660. This is a shortcut for calling setStrokeType.
  41661. */
  41662. void setStrokeThickness (const float newThickness) throw();
  41663. /** Returns the current outline style. */
  41664. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  41665. /** @internal */
  41666. void render (const Drawable::RenderingContext& context) const;
  41667. /** @internal */
  41668. void getBounds (float& x, float& y, float& width, float& height) const;
  41669. /** @internal */
  41670. bool hitTest (float x, float y) const;
  41671. /** @internal */
  41672. Drawable* createCopy() const;
  41673. /** @internal */
  41674. ValueTree createValueTree() const throw();
  41675. /** @internal */
  41676. static DrawablePath* createFromValueTree (const ValueTree& tree) throw();
  41677. juce_UseDebuggingNewOperator
  41678. private:
  41679. Path path, stroke;
  41680. FillType mainFill, strokeFill;
  41681. PathStrokeType strokeType;
  41682. void updateOutline();
  41683. DrawablePath (const DrawablePath&);
  41684. const DrawablePath& operator= (const DrawablePath&);
  41685. };
  41686. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  41687. /********* End of inlined file: juce_DrawablePath.h *********/
  41688. #endif
  41689. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  41690. /********* Start of inlined file: juce_DrawableText.h *********/
  41691. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  41692. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  41693. /**
  41694. A drawable object which renders a line of text.
  41695. @see Drawable
  41696. */
  41697. class JUCE_API DrawableText : public Drawable
  41698. {
  41699. public:
  41700. /** Creates a DrawableText object. */
  41701. DrawableText();
  41702. /** Destructor. */
  41703. virtual ~DrawableText();
  41704. /** Sets the block of text to render */
  41705. void setText (const GlyphArrangement& newText);
  41706. /** Sets a single line of text to render.
  41707. This is a convenient method of adding a single line - for
  41708. more complex text, use the setText() that takes a
  41709. GlyphArrangement instead.
  41710. */
  41711. void setText (const String& newText, const Font& fontToUse);
  41712. /** Returns the text arrangement that was set with setText(). */
  41713. const GlyphArrangement& getText() const throw() { return text; }
  41714. /** Sets the colour of the text. */
  41715. void setColour (const Colour& newColour);
  41716. /** Returns the current text colour. */
  41717. const Colour& getColour() const throw() { return colour; }
  41718. /** @internal */
  41719. void render (const Drawable::RenderingContext& context) const;
  41720. /** @internal */
  41721. void getBounds (float& x, float& y, float& width, float& height) const;
  41722. /** @internal */
  41723. bool hitTest (float x, float y) const;
  41724. /** @internal */
  41725. Drawable* createCopy() const;
  41726. /** @internal */
  41727. ValueTree createValueTree() const throw();
  41728. /** @internal */
  41729. static DrawableText* createFromValueTree (const ValueTree& tree) throw();
  41730. juce_UseDebuggingNewOperator
  41731. private:
  41732. GlyphArrangement text;
  41733. Colour colour;
  41734. DrawableText (const DrawableText&);
  41735. const DrawableText& operator= (const DrawableText&);
  41736. };
  41737. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  41738. /********* End of inlined file: juce_DrawableText.h *********/
  41739. #endif
  41740. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  41741. #endif
  41742. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  41743. /********* Start of inlined file: juce_GlowEffect.h *********/
  41744. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  41745. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  41746. /**
  41747. A component effect that adds a coloured blur around the component's contents.
  41748. (This will only work on non-opaque components).
  41749. @see Component::setComponentEffect, DropShadowEffect
  41750. */
  41751. class JUCE_API GlowEffect : public ImageEffectFilter
  41752. {
  41753. public:
  41754. /** Creates a default 'glow' effect.
  41755. To customise its appearance, use the setGlowProperties() method.
  41756. */
  41757. GlowEffect();
  41758. /** Destructor. */
  41759. ~GlowEffect();
  41760. /** Sets the glow's radius and colour.
  41761. The radius is how large the blur should be, and the colour is
  41762. used to render it (for a less intense glow, lower the colour's
  41763. opacity).
  41764. */
  41765. void setGlowProperties (const float newRadius,
  41766. const Colour& newColour);
  41767. /** @internal */
  41768. void applyEffect (Image& sourceImage, Graphics& destContext);
  41769. juce_UseDebuggingNewOperator
  41770. private:
  41771. float radius;
  41772. Colour colour;
  41773. };
  41774. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  41775. /********* End of inlined file: juce_GlowEffect.h *********/
  41776. #endif
  41777. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  41778. #endif
  41779. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41780. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  41781. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41782. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41783. /**
  41784. An effect filter that reduces the image's opacity.
  41785. This can be used to make a component (and its child components) more
  41786. transparent.
  41787. @see Component::setComponentEffect
  41788. */
  41789. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  41790. {
  41791. public:
  41792. /** Creates the effect object.
  41793. The opacity of the component to which the effect is applied will be
  41794. scaled by the given factor (in the range 0 to 1.0f).
  41795. */
  41796. ReduceOpacityEffect (const float opacity = 1.0f);
  41797. /** Destructor. */
  41798. ~ReduceOpacityEffect();
  41799. /** Sets how much to scale the component's opacity.
  41800. @param newOpacity should be between 0 and 1.0f
  41801. */
  41802. void setOpacity (const float newOpacity);
  41803. /** @internal */
  41804. void applyEffect (Image& sourceImage, Graphics& destContext);
  41805. juce_UseDebuggingNewOperator
  41806. private:
  41807. float opacity;
  41808. };
  41809. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41810. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  41811. #endif
  41812. #ifndef __JUCE_FONT_JUCEHEADER__
  41813. #endif
  41814. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  41815. #endif
  41816. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  41817. #endif
  41818. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  41819. #endif
  41820. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  41821. #endif
  41822. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  41823. #endif
  41824. #ifndef __JUCE_LINE_JUCEHEADER__
  41825. #endif
  41826. #ifndef __JUCE_PATH_JUCEHEADER__
  41827. #endif
  41828. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  41829. /********* Start of inlined file: juce_PathIterator.h *********/
  41830. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  41831. #define __JUCE_PATHITERATOR_JUCEHEADER__
  41832. /**
  41833. Flattens a Path object into a series of straight-line sections.
  41834. Use one of these to iterate through a Path object, and it will convert
  41835. all the curves into line sections so it's easy to render or perform
  41836. geometric operations on.
  41837. @see Path
  41838. */
  41839. class JUCE_API PathFlatteningIterator
  41840. {
  41841. public:
  41842. /** Creates a PathFlatteningIterator.
  41843. After creation, use the next() method to initialise the fields in the
  41844. object with the first line's position.
  41845. @param path the path to iterate along
  41846. @param transform a transform to apply to each point in the path being iterated
  41847. @param tolerence the amount by which the curves are allowed to deviate from the
  41848. lines into which they are being broken down - a higher tolerence
  41849. is a bit faster, but less smooth.
  41850. */
  41851. PathFlatteningIterator (const Path& path,
  41852. const AffineTransform& transform = AffineTransform::identity,
  41853. float tolerence = 6.0f) throw();
  41854. /** Destructor. */
  41855. ~PathFlatteningIterator() throw();
  41856. /** Fetches the next line segment from the path.
  41857. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  41858. so that they describe the new line segment.
  41859. @returns false when there are no more lines to fetch.
  41860. */
  41861. bool next() throw();
  41862. /** The x position of the start of the current line segment. */
  41863. float x1;
  41864. /** The y position of the start of the current line segment. */
  41865. float y1;
  41866. /** The x position of the end of the current line segment. */
  41867. float x2;
  41868. /** The y position of the end of the current line segment. */
  41869. float y2;
  41870. /** Indicates whether the current line segment is closing a sub-path.
  41871. If the current line is the one that connects the end of a sub-path
  41872. back to the start again, this will be true.
  41873. */
  41874. bool closesSubPath;
  41875. /** The index of the current line within the current sub-path.
  41876. E.g. you can use this to see whether the line is the first one in the
  41877. subpath by seeing if it's 0.
  41878. */
  41879. int subPathIndex;
  41880. /** Returns true if the current segment is the last in the current sub-path. */
  41881. bool isLastInSubpath() const { return stackPos == stackBase
  41882. && (index >= path.numElements
  41883. || points [index] == Path::moveMarker); }
  41884. juce_UseDebuggingNewOperator
  41885. private:
  41886. const Path& path;
  41887. const AffineTransform transform;
  41888. float* points;
  41889. float tolerence, subPathCloseX, subPathCloseY;
  41890. bool isIdentityTransform;
  41891. HeapBlock <float> stackBase;
  41892. float* stackPos;
  41893. int index, stackSize;
  41894. PathFlatteningIterator (const PathFlatteningIterator&);
  41895. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  41896. };
  41897. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  41898. /********* End of inlined file: juce_PathIterator.h *********/
  41899. #endif
  41900. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  41901. #endif
  41902. #ifndef __JUCE_POINT_JUCEHEADER__
  41903. #endif
  41904. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41905. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  41906. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41907. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41908. /**
  41909. A rectangle whose co-ordinates can be defined in terms of absolute or
  41910. proportional distances.
  41911. Designed mainly for storing component positions, this gives you a lot of
  41912. control over how each co-ordinate is stored, either as an absolute position,
  41913. or as a proportion of the size of a parent rectangle.
  41914. It also allows you to define the anchor points by which the rectangle is
  41915. positioned, so for example you could specify that the top right of the
  41916. rectangle should be an absolute distance from its parent's bottom-right corner.
  41917. This object can be stored as a string, which takes the form "x y w h", including
  41918. symbols like '%' and letters to indicate the anchor point. See its toString()
  41919. method for more info.
  41920. Example usage:
  41921. @code
  41922. class MyComponent
  41923. {
  41924. void resized()
  41925. {
  41926. // this will set the child component's x to be 20% of our width, its y
  41927. // to be 30, its width to be 150, and its height to be 50% of our
  41928. // height..
  41929. const PositionedRectangle pos1 ("20% 30 150 50%");
  41930. pos1.applyToComponent (*myChildComponent1);
  41931. // this will inset the child component with a gap of 10 pixels
  41932. // around each of its edges..
  41933. const PositionedRectangle pos2 ("10 10 20M 20M");
  41934. pos2.applyToComponent (*myChildComponent2);
  41935. }
  41936. };
  41937. @endcode
  41938. */
  41939. class JUCE_API PositionedRectangle
  41940. {
  41941. public:
  41942. /** Creates an empty rectangle with all co-ordinates set to zero.
  41943. The default anchor point is top-left; the default
  41944. */
  41945. PositionedRectangle() throw();
  41946. /** Initialises a PositionedRectangle from a saved string version.
  41947. The string must be in the format generated by toString().
  41948. */
  41949. PositionedRectangle (const String& stringVersion) throw();
  41950. /** Creates a copy of another PositionedRectangle. */
  41951. PositionedRectangle (const PositionedRectangle& other) throw();
  41952. /** Copies another PositionedRectangle. */
  41953. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  41954. /** Destructor. */
  41955. ~PositionedRectangle() throw();
  41956. /** Returns a string version of this position, from which it can later be
  41957. re-generated.
  41958. The format is four co-ordinates, "x y w h".
  41959. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  41960. - If a co-ordinate is proportional to its parent's width or height, it is stored
  41961. as a percentage, e.g. "80%".
  41962. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  41963. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  41964. the parent's right-hand edge.
  41965. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  41966. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  41967. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  41968. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  41969. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  41970. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  41971. has "c" appended to it. So "-50Rc" would mean that this component's
  41972. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  41973. this component's centre should be placed 40% across the parent's width.
  41974. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  41975. the number has "M" appended to it.
  41976. To reload a stored string, use the constructor that takes a string parameter.
  41977. */
  41978. const String toString() const throw();
  41979. /** Calculates the absolute position, given the size of the space that
  41980. it should go in.
  41981. This will work out any proportional distances and sizes relative to the
  41982. target rectangle, and will return the absolute position.
  41983. @see applyToComponent
  41984. */
  41985. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  41986. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  41987. */
  41988. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  41989. double& x,
  41990. double& y,
  41991. double& width,
  41992. double& height) const throw();
  41993. /** This sets the bounds of the given component to this position.
  41994. This is equivalent to writing:
  41995. @code
  41996. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  41997. @endcode
  41998. @see getRectangle, updateFromComponent
  41999. */
  42000. void applyToComponent (Component& comp) const throw();
  42001. /** Updates this object's co-ordinates to match the given rectangle.
  42002. This will set all co-ordinates based on the given rectangle, re-calculating
  42003. any proportional distances, and using the current anchor points.
  42004. So for example if the x co-ordinate mode is currently proportional, this will
  42005. re-calculate x based on the rectangle's relative position within the target
  42006. rectangle's width.
  42007. If the target rectangle's width or height are zero then it may not be possible
  42008. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  42009. will not be changed.
  42010. */
  42011. void updateFrom (const Rectangle& newPosition,
  42012. const Rectangle& targetSpaceToBeRelativeTo) throw();
  42013. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  42014. */
  42015. void updateFromDouble (const double x, const double y,
  42016. const double width, const double height,
  42017. const Rectangle& targetSpaceToBeRelativeTo) throw();
  42018. /** Updates this object's co-ordinates to match the bounds of this component.
  42019. This is equivalent to calling updateFrom() with the component's bounds and
  42020. it parent size.
  42021. If the component doesn't currently have a parent, then proportional co-ordinates
  42022. might not be updated because it would need to know the parent's size to do the
  42023. maths for this.
  42024. */
  42025. void updateFromComponent (const Component& comp) throw();
  42026. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  42027. enum AnchorPoint
  42028. {
  42029. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  42030. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  42031. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  42032. };
  42033. /** Specifies how an x or y co-ordinate should be interpreted. */
  42034. enum PositionMode
  42035. {
  42036. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  42037. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  42038. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  42039. 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. */
  42040. };
  42041. /** Specifies how the width or height should be interpreted. */
  42042. enum SizeMode
  42043. {
  42044. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  42045. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  42046. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  42047. };
  42048. /** Sets all options for all co-ordinates.
  42049. This requires a reference rectangle to be specified, because if you're changing any
  42050. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  42051. the co-ordinates, and will need to know the parent size so it can calculate this.
  42052. */
  42053. void setModes (const AnchorPoint xAnchorMode,
  42054. const PositionMode xPositionMode,
  42055. const AnchorPoint yAnchorMode,
  42056. const PositionMode yPositionMode,
  42057. const SizeMode widthMode,
  42058. const SizeMode heightMode,
  42059. const Rectangle& targetSpaceToBeRelativeTo) throw();
  42060. /** Returns the anchoring mode for the x co-ordinate.
  42061. To change any of the modes, use setModes().
  42062. */
  42063. AnchorPoint getAnchorPointX() const throw();
  42064. /** Returns the positioning mode for the x co-ordinate.
  42065. To change any of the modes, use setModes().
  42066. */
  42067. PositionMode getPositionModeX() const throw();
  42068. /** Returns the raw x co-ordinate.
  42069. If the x position mode is absolute, then this will be the absolute value. If it's
  42070. proportional, then this will be a fractional proportion, where 1.0 means the full
  42071. width of the parent space.
  42072. */
  42073. double getX() const throw() { return x; }
  42074. /** Sets the raw value of the x co-ordinate.
  42075. See getX() for the meaning of this value.
  42076. */
  42077. void setX (const double newX) throw() { x = newX; }
  42078. /** Returns the anchoring mode for the y co-ordinate.
  42079. To change any of the modes, use setModes().
  42080. */
  42081. AnchorPoint getAnchorPointY() const throw();
  42082. /** Returns the positioning mode for the y co-ordinate.
  42083. To change any of the modes, use setModes().
  42084. */
  42085. PositionMode getPositionModeY() const throw();
  42086. /** Returns the raw y co-ordinate.
  42087. If the y position mode is absolute, then this will be the absolute value. If it's
  42088. proportional, then this will be a fractional proportion, where 1.0 means the full
  42089. height of the parent space.
  42090. */
  42091. double getY() const throw() { return y; }
  42092. /** Sets the raw value of the y co-ordinate.
  42093. See getY() for the meaning of this value.
  42094. */
  42095. void setY (const double newY) throw() { y = newY; }
  42096. /** Returns the mode used to calculate the width.
  42097. To change any of the modes, use setModes().
  42098. */
  42099. SizeMode getWidthMode() const throw();
  42100. /** Returns the raw width value.
  42101. If the width mode is absolute, then this will be the absolute value. If the mode is
  42102. proportional, then this will be a fractional proportion, where 1.0 means the full
  42103. width of the parent space.
  42104. */
  42105. double getWidth() const throw() { return w; }
  42106. /** Sets the raw width value.
  42107. See getWidth() for the details about what this value means.
  42108. */
  42109. void setWidth (const double newWidth) throw() { w = newWidth; }
  42110. /** Returns the mode used to calculate the height.
  42111. To change any of the modes, use setModes().
  42112. */
  42113. SizeMode getHeightMode() const throw();
  42114. /** Returns the raw height value.
  42115. If the height mode is absolute, then this will be the absolute value. If the mode is
  42116. proportional, then this will be a fractional proportion, where 1.0 means the full
  42117. height of the parent space.
  42118. */
  42119. double getHeight() const throw() { return h; }
  42120. /** Sets the raw height value.
  42121. See getHeight() for the details about what this value means.
  42122. */
  42123. void setHeight (const double newHeight) throw() { h = newHeight; }
  42124. /** If the size and position are constance, and wouldn't be affected by changes
  42125. in the parent's size, then this will return true.
  42126. */
  42127. bool isPositionAbsolute() const throw();
  42128. /** Compares two objects. */
  42129. const bool operator== (const PositionedRectangle& other) const throw();
  42130. /** Compares two objects. */
  42131. const bool operator!= (const PositionedRectangle& other) const throw();
  42132. juce_UseDebuggingNewOperator
  42133. private:
  42134. double x, y, w, h;
  42135. uint8 xMode, yMode, wMode, hMode;
  42136. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  42137. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  42138. void decodePosString (const String& s, uint8& mode, double& value) throw();
  42139. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  42140. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  42141. const uint8 xMode, const uint8 wMode,
  42142. const int parentPos, const int parentSize) const throw();
  42143. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  42144. const uint8 xMode, const uint8 wMode,
  42145. const int parentPos, const int parentSize) const throw();
  42146. };
  42147. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  42148. /********* End of inlined file: juce_PositionedRectangle.h *********/
  42149. #endif
  42150. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  42151. #endif
  42152. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  42153. #endif
  42154. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  42155. /********* Start of inlined file: juce_CameraDevice.h *********/
  42156. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  42157. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  42158. #if JUCE_USE_CAMERA
  42159. /**
  42160. Receives callbacks with images from a CameraDevice.
  42161. @see CameraDevice::addListener
  42162. */
  42163. class CameraImageListener
  42164. {
  42165. public:
  42166. CameraImageListener() {}
  42167. virtual ~CameraImageListener() {}
  42168. /** This method is called when a new image arrives.
  42169. This may be called by any thread, so be careful about thread-safety,
  42170. and make sure that you process the data as quickly as possible to
  42171. avoid glitching!
  42172. */
  42173. virtual void imageReceived (Image& image) = 0;
  42174. };
  42175. /**
  42176. Controls any camera capture devices that might be available.
  42177. Use getAvailableDevices() to list the devices that are attached to the
  42178. system, then call openDevice to open one for use. Once you have a CameraDevice
  42179. object, you can get a viewer component from it, and use its methods to
  42180. stream to a file or capture still-frames.
  42181. */
  42182. class JUCE_API CameraDevice
  42183. {
  42184. public:
  42185. /** Destructor. */
  42186. virtual ~CameraDevice();
  42187. /** Returns a list of the available cameras on this machine.
  42188. You can open one of these devices by calling openDevice().
  42189. */
  42190. static const StringArray getAvailableDevices();
  42191. /** Opens a camera device.
  42192. The index parameter indicates which of the items returned by getAvailableDevices()
  42193. to open.
  42194. The size constraints allow the method to choose between different resolutions if
  42195. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  42196. then these will be ignored.
  42197. */
  42198. static CameraDevice* openDevice (int deviceIndex,
  42199. int minWidth = 128, int minHeight = 64,
  42200. int maxWidth = 1024, int maxHeight = 768);
  42201. /** Returns the name of this device */
  42202. const String getName() const { return name; }
  42203. /** Creates a component that can be used to display a preview of the
  42204. video from this camera.
  42205. */
  42206. Component* createViewerComponent();
  42207. /** Starts recording video to the specified file.
  42208. You should use getFileExtension() to find out the correct extension to
  42209. use for your filename.
  42210. If the file exists, it will be deleted before the recording starts.
  42211. This method may not start recording instantly, so if you need to know the
  42212. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  42213. after the recording has finished.
  42214. */
  42215. void startRecordingToFile (const File& file);
  42216. /** Stops recording, after a call to startRecordingToFile().
  42217. */
  42218. void stopRecording();
  42219. /** Returns the file extension that should be used for the files
  42220. that you pass to startRecordingToFile().
  42221. This may be platform-specific, e.g. ".mov" or ".avi".
  42222. */
  42223. static const String getFileExtension();
  42224. /** After calling stopRecording(), this method can be called to return the timestamp
  42225. of the first frame that was written to the file.
  42226. */
  42227. const Time getTimeOfFirstRecordedFrame() const;
  42228. /** Adds a listener to receive images from the camera.
  42229. Be very careful not to delete the listener without first removing it by calling
  42230. removeListener().
  42231. */
  42232. void addListener (CameraImageListener* listenerToAdd);
  42233. /** Removes a listener that was previously added with addListener().
  42234. */
  42235. void removeListener (CameraImageListener* listenerToRemove);
  42236. juce_UseDebuggingNewOperator
  42237. protected:
  42238. /** @internal */
  42239. CameraDevice (const String& name, int index);
  42240. private:
  42241. void* internal;
  42242. bool isRecording;
  42243. String name;
  42244. CameraDevice (const CameraDevice&);
  42245. const CameraDevice& operator= (const CameraDevice&);
  42246. };
  42247. #endif
  42248. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  42249. /********* End of inlined file: juce_CameraDevice.h *********/
  42250. #endif
  42251. #ifndef __JUCE_IMAGE_JUCEHEADER__
  42252. #endif
  42253. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  42254. /********* Start of inlined file: juce_ImageCache.h *********/
  42255. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  42256. #define __JUCE_IMAGECACHE_JUCEHEADER__
  42257. struct ImageCacheItem;
  42258. /**
  42259. A global cache of images that have been loaded from files or memory.
  42260. If you're loading an image and may need to use the image in more than one
  42261. place, this is used to allow the same image to be shared rather than loading
  42262. multiple copies into memory.
  42263. Another advantage is that after images are released, they will be kept in
  42264. memory for a few seconds before it is actually deleted, so if you're repeatedly
  42265. loading/deleting the same image, it'll reduce the chances of having to reload it
  42266. each time.
  42267. @see Image, ImageFileFormat
  42268. */
  42269. class JUCE_API ImageCache : private DeletedAtShutdown,
  42270. private Timer
  42271. {
  42272. public:
  42273. /** Loads an image from a file, (or just returns the image if it's already cached).
  42274. If the cache already contains an image that was loaded from this file,
  42275. that image will be returned. Otherwise, this method will try to load the
  42276. file, add it to the cache, and return it.
  42277. It's very important not to delete the image that is returned - instead use
  42278. the ImageCache::release() method.
  42279. Also, remember that the image returned is shared, so drawing into it might
  42280. affect other things that are using it!
  42281. @param file the file to try to load
  42282. @returns the image, or null if it there was an error loading it
  42283. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  42284. */
  42285. static Image* getFromFile (const File& file);
  42286. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  42287. If the cache already contains an image that was loaded from this block of memory,
  42288. that image will be returned. Otherwise, this method will try to load the
  42289. file, add it to the cache, and return it.
  42290. It's very important not to delete the image that is returned - instead use
  42291. the ImageCache::release() method.
  42292. Also, remember that the image returned is shared, so drawing into it might
  42293. affect other things that are using it!
  42294. @param imageData the block of memory containing the image data
  42295. @param dataSize the data size in bytes
  42296. @returns the image, or null if it there was an error loading it
  42297. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  42298. */
  42299. static Image* getFromMemory (const void* imageData,
  42300. const int dataSize);
  42301. /** Releases an image that was previously created by the ImageCache.
  42302. If an image has been returned by the getFromFile() or getFromMemory() methods,
  42303. it mustn't be deleted directly, but should be released with this method
  42304. instead.
  42305. @see getFromFile, getFromMemory
  42306. */
  42307. static void release (Image* const imageToRelease);
  42308. /** Releases an image if it's in the cache, or deletes it if it isn't cached.
  42309. This is a handy function to use if you want to delete an image but are afraid that
  42310. it might be cached.
  42311. */
  42312. static void releaseOrDelete (Image* const imageToRelease);
  42313. /** Checks whether an image is in the cache or not.
  42314. @returns true if the image is currently in the cache
  42315. */
  42316. static bool isImageInCache (Image* const imageToLookFor);
  42317. /** Increments the reference-count for a cached image.
  42318. If the image isn't in the cache, this method won't do anything.
  42319. */
  42320. static void incReferenceCount (Image* const image);
  42321. /** Checks the cache for an image with a particular hashcode.
  42322. If there's an image in the cache with this hashcode, it will be returned,
  42323. otherwise it will return zero.
  42324. If an image is returned, it must be released with the release() method
  42325. when no longer needed, to maintain the correct reference counts.
  42326. @param hashCode the hash code that would have been associated with the
  42327. image by addImageToCache()
  42328. @see addImageToCache
  42329. */
  42330. static Image* getFromHashCode (const int64 hashCode);
  42331. /** Adds an image to the cache with a user-defined hash-code.
  42332. After calling this, responsibilty for deleting the image will be taken
  42333. by the ImageCache.
  42334. The image will be initially be given a reference count of 1, so call
  42335. the release() method to delete it.
  42336. @param image the image to add
  42337. @param hashCode the hash-code to associate with it
  42338. @see getFromHashCode
  42339. */
  42340. static void addImageToCache (Image* const image,
  42341. const int64 hashCode);
  42342. /** Changes the amount of time before an unused image will be removed from the cache.
  42343. By default this is about 5 seconds.
  42344. */
  42345. static void setCacheTimeout (const int millisecs);
  42346. juce_UseDebuggingNewOperator
  42347. private:
  42348. CriticalSection lock;
  42349. OwnedArray <ImageCacheItem> images;
  42350. ImageCache();
  42351. ImageCache (const ImageCache&);
  42352. const ImageCache& operator= (const ImageCache&);
  42353. ~ImageCache();
  42354. void timerCallback();
  42355. };
  42356. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  42357. /********* End of inlined file: juce_ImageCache.h *********/
  42358. #endif
  42359. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42360. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  42361. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42362. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42363. /**
  42364. Represents a filter kernel to use in convoluting an image.
  42365. @see Image::applyConvolution
  42366. */
  42367. class JUCE_API ImageConvolutionKernel
  42368. {
  42369. public:
  42370. /** Creates an empty convulution kernel.
  42371. @param size the length of each dimension of the kernel, so e.g. if the size
  42372. is 5, it will create a 5x5 kernel
  42373. */
  42374. ImageConvolutionKernel (const int size);
  42375. /** Destructor. */
  42376. ~ImageConvolutionKernel();
  42377. /** Resets all values in the kernel to zero.
  42378. */
  42379. void clear();
  42380. /** Sets the value of a specific cell in the kernel.
  42381. The x and y parameters must be in the range 0 < x < getKernelSize().
  42382. @see setOverallSum
  42383. */
  42384. void setKernelValue (const int x,
  42385. const int y,
  42386. const float value);
  42387. /** Rescales all values in the kernel to make the total add up to a fixed value.
  42388. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  42389. */
  42390. void setOverallSum (const float desiredTotalSum);
  42391. /** Multiplies all values in the kernel by a value. */
  42392. void rescaleAllValues (const float multiplier);
  42393. /** Intialises the kernel for a gaussian blur.
  42394. @param blurRadius this may be larger or smaller than the kernel's actual
  42395. size but this will obviously be wasteful or clip at the
  42396. edges. Ideally the kernel should be just larger than
  42397. (blurRadius * 2).
  42398. */
  42399. void createGaussianBlur (const float blurRadius);
  42400. /** Returns the size of the kernel.
  42401. E.g. if it's a 3x3 kernel, this returns 3.
  42402. */
  42403. int getKernelSize() const { return size; }
  42404. /** Returns a 2-dimensional array of the kernel's values.
  42405. The size of each dimension of the array will be getKernelSize().
  42406. */
  42407. float** getValues() const { return values; }
  42408. /** Applies the kernel to an image.
  42409. @param destImage the image that will receive the resultant convoluted pixels.
  42410. @param sourceImage an optional source image to read from - if this is 0, then the
  42411. destination image will be used as the source. If an image is
  42412. specified, it must be exactly the same size and type as the destination
  42413. image.
  42414. @param x the region of the image to apply the filter to
  42415. @param y the region of the image to apply the filter to
  42416. @param width the region of the image to apply the filter to
  42417. @param height the region of the image to apply the filter to
  42418. */
  42419. void applyToImage (Image& destImage,
  42420. const Image* sourceImage,
  42421. int x,
  42422. int y,
  42423. int width,
  42424. int height) const;
  42425. juce_UseDebuggingNewOperator
  42426. private:
  42427. HeapBlock <float> values;
  42428. const int size;
  42429. // no reason not to implement these one day..
  42430. ImageConvolutionKernel (const ImageConvolutionKernel&);
  42431. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  42432. };
  42433. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42434. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  42435. #endif
  42436. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42437. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  42438. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42439. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42440. /**
  42441. Base-class for codecs that can read and write image file formats such
  42442. as PNG, JPEG, etc.
  42443. This class also contains static methods to make it easy to load images
  42444. from files, streams or from memory.
  42445. @see Image, ImageCache
  42446. */
  42447. class JUCE_API ImageFileFormat
  42448. {
  42449. protected:
  42450. /** Creates an ImageFormat. */
  42451. ImageFileFormat() {}
  42452. public:
  42453. /** Destructor. */
  42454. virtual ~ImageFileFormat() {}
  42455. /** Returns a description of this file format.
  42456. E.g. "JPEG", "PNG"
  42457. */
  42458. virtual const String getFormatName() = 0;
  42459. /** Returns true if the given stream seems to contain data that this format
  42460. understands.
  42461. The format class should only read the first few bytes of the stream and sniff
  42462. for header bytes that it understands.
  42463. @see decodeImage
  42464. */
  42465. virtual bool canUnderstand (InputStream& input) = 0;
  42466. /** Tries to decode and return an image from the given stream.
  42467. This will be called for an image format after calling its canUnderStand() method
  42468. to see if it can handle the stream.
  42469. @param input the stream to read the data from. The stream will be positioned
  42470. at the start of the image data (but this may not necessarily
  42471. be position 0)
  42472. @returns the image that was decoded, or 0 if it fails. It's the
  42473. caller's responsibility to delete this image when no longer needed.
  42474. @see loadFrom
  42475. */
  42476. virtual Image* decodeImage (InputStream& input) = 0;
  42477. /** Attempts to write an image to a stream.
  42478. To specify extra information like encoding quality, there will be appropriate parameters
  42479. in the subclasses of the specific file types.
  42480. @returns true if it nothing went wrong.
  42481. */
  42482. virtual bool writeImageToStream (const Image& sourceImage,
  42483. OutputStream& destStream) = 0;
  42484. /** Tries the built-in decoders to see if it can find one to read this stream.
  42485. There are currently built-in decoders for PNG, JPEG and GIF formats.
  42486. The object that is returned should not be deleted by the caller.
  42487. @see canUnderstand, decodeImage, loadFrom
  42488. */
  42489. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  42490. /** Tries to load an image from a stream.
  42491. This will use the findImageFormatForStream() method to locate a suitable
  42492. codec, and use that to load the image.
  42493. @returns the image that was decoded, or 0 if it fails to load one. It's the
  42494. caller's responsibility to delete this image when no longer needed.
  42495. */
  42496. static Image* loadFrom (InputStream& input);
  42497. /** Tries to load an image from a file.
  42498. This will use the findImageFormatForStream() method to locate a suitable
  42499. codec, and use that to load the image.
  42500. @returns the image that was decoded, or 0 if it fails to load one. It's the
  42501. caller's responsibility to delete this image when no longer needed.
  42502. */
  42503. static Image* loadFrom (const File& file);
  42504. /** Tries to load an image from a block of raw image data.
  42505. This will use the findImageFormatForStream() method to locate a suitable
  42506. codec, and use that to load the image.
  42507. @returns the image that was decoded, or 0 if it fails to load one. It's the
  42508. caller's responsibility to delete this image when no longer needed.
  42509. */
  42510. static Image* loadFrom (const void* rawData,
  42511. const int numBytesOfData);
  42512. };
  42513. /**
  42514. A type of ImageFileFormat for reading and writing PNG files.
  42515. @see ImageFileFormat, JPEGImageFormat
  42516. */
  42517. class JUCE_API PNGImageFormat : public ImageFileFormat
  42518. {
  42519. public:
  42520. PNGImageFormat();
  42521. ~PNGImageFormat();
  42522. const String getFormatName();
  42523. bool canUnderstand (InputStream& input);
  42524. Image* decodeImage (InputStream& input);
  42525. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  42526. };
  42527. /**
  42528. A type of ImageFileFormat for reading and writing JPEG files.
  42529. @see ImageFileFormat, PNGImageFormat
  42530. */
  42531. class JUCE_API JPEGImageFormat : public ImageFileFormat
  42532. {
  42533. public:
  42534. JPEGImageFormat();
  42535. ~JPEGImageFormat();
  42536. /** Specifies the quality to be used when writing a JPEG file.
  42537. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  42538. any negative value is "default" quality
  42539. */
  42540. void setQuality (const float newQuality);
  42541. const String getFormatName();
  42542. bool canUnderstand (InputStream& input);
  42543. Image* decodeImage (InputStream& input);
  42544. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  42545. private:
  42546. float quality;
  42547. };
  42548. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42549. /********* End of inlined file: juce_ImageFileFormat.h *********/
  42550. #endif
  42551. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  42552. #endif
  42553. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42554. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  42555. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42556. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42557. /**
  42558. A class to take care of the logic involved with the loading/saving of some kind
  42559. of document.
  42560. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  42561. functions you need for documents that get saved to a file, so this class attempts
  42562. to abstract most of the boring stuff.
  42563. Your subclass should just implement all the pure virtual methods, and you can
  42564. then use the higher-level public methods to do the load/save dialogs, to warn the user
  42565. about overwriting files, etc.
  42566. The document object keeps track of whether it has changed since it was last saved or
  42567. loaded, so when you change something, call its changed() method. This will set a
  42568. flag so it knows it needs saving, and will also broadcast a change message using the
  42569. ChangeBroadcaster base class.
  42570. @see ChangeBroadcaster
  42571. */
  42572. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  42573. {
  42574. public:
  42575. /** Creates a FileBasedDocument.
  42576. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  42577. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  42578. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  42579. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  42580. */
  42581. FileBasedDocument (const String& fileExtension,
  42582. const String& fileWildCard,
  42583. const String& openFileDialogTitle,
  42584. const String& saveFileDialogTitle);
  42585. /** Destructor. */
  42586. virtual ~FileBasedDocument();
  42587. /** Returns true if the changed() method has been called since the file was
  42588. last saved or loaded.
  42589. @see resetChangedFlag, changed
  42590. */
  42591. bool hasChangedSinceSaved() const { return changedSinceSave; }
  42592. /** Called to indicate that the document has changed and needs saving.
  42593. This method will also trigger a change message to be sent out using the
  42594. ChangeBroadcaster base class.
  42595. After calling the method, the hasChangedSinceSaved() method will return true, until
  42596. it is reset either by saving to a file or using the resetChangedFlag() method.
  42597. @see hasChangedSinceSaved, resetChangedFlag
  42598. */
  42599. virtual void changed();
  42600. /** Sets the state of the 'changed' flag.
  42601. The 'changed' flag is set to true when the changed() method is called - use this method
  42602. to reset it or to set it without also broadcasting a change message.
  42603. @see changed, hasChangedSinceSaved
  42604. */
  42605. void setChangedFlag (const bool hasChanged);
  42606. /** Tries to open a file.
  42607. If the file opens correctly, the document's file (see the getFile() method) is set
  42608. to this new one; if it fails, the document's file is left unchanged, and optionally
  42609. a message box is shown telling the user there was an error.
  42610. @returns true if the new file loaded successfully
  42611. @see loadDocument, loadFromUserSpecifiedFile
  42612. */
  42613. bool loadFrom (const File& fileToLoadFrom,
  42614. const bool showMessageOnFailure);
  42615. /** Asks the user for a file and tries to load it.
  42616. This will pop up a dialog box using the title, file extension and
  42617. wildcard specified in the document's constructor, and asks the user
  42618. for a file. If they pick one, the loadFrom() method is used to
  42619. try to load it, optionally showing a message if it fails.
  42620. @returns true if a file was loaded; false if the user cancelled or if they
  42621. picked a file which failed to load correctly
  42622. @see loadFrom
  42623. */
  42624. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  42625. /** A set of possible outcomes of one of the save() methods
  42626. */
  42627. enum SaveResult
  42628. {
  42629. savedOk = 0, /**< indicates that a file was saved successfully. */
  42630. userCancelledSave, /**< indicates that the user aborted the save operation. */
  42631. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  42632. };
  42633. /** Tries to save the document to the last file it was saved or loaded from.
  42634. This will always try to write to the file, even if the document isn't flagged as
  42635. having changed.
  42636. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  42637. true, it will prompt the user to pick a file, as if
  42638. saveAsInteractive() was called.
  42639. @param showMessageOnFailure if true it will show a warning message when if the
  42640. save operation fails
  42641. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  42642. */
  42643. SaveResult save (const bool askUserForFileIfNotSpecified,
  42644. const bool showMessageOnFailure);
  42645. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  42646. it if they say yes.
  42647. If you've got a document open and want to close it (e.g. to quit the app), this is the
  42648. method to call.
  42649. If the document doesn't need saving it'll return the value savedOk so
  42650. you can go ahead and delete the document.
  42651. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  42652. return savedOk, so again, you can safely delete the document.
  42653. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  42654. close-document operation.
  42655. And if they click "save changes", it'll try to save and either return savedOk, or
  42656. failedToWriteToFile if there was a problem.
  42657. @see save, saveAs, saveAsInteractive
  42658. */
  42659. SaveResult saveIfNeededAndUserAgrees();
  42660. /** Tries to save the document to a specified file.
  42661. If this succeeds, it'll also change the document's internal file (as returned by
  42662. the getFile() method). If it fails, the file will be left unchanged.
  42663. @param newFile the file to try to write to
  42664. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  42665. the user first if they want to overwrite it
  42666. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  42667. use the saveAsInteractive() method to ask the user for a
  42668. filename
  42669. @param showMessageOnFailure if true and the write operation fails, it'll show
  42670. a message box to warn the user
  42671. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  42672. */
  42673. SaveResult saveAs (const File& newFile,
  42674. const bool warnAboutOverwritingExistingFiles,
  42675. const bool askUserForFileIfNotSpecified,
  42676. const bool showMessageOnFailure);
  42677. /** Prompts the user for a filename and tries to save to it.
  42678. This will pop up a dialog box using the title, file extension and
  42679. wildcard specified in the document's constructor, and asks the user
  42680. for a file. If they pick one, the saveAs() method is used to try to save
  42681. to this file.
  42682. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  42683. the user first if they want to overwrite it
  42684. @see saveIfNeededAndUserAgrees, save, saveAs
  42685. */
  42686. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  42687. /** Returns the file that this document was last successfully saved or loaded from.
  42688. When the document object is created, this will be set to File::nonexistent.
  42689. It is changed when one of the load or save methods is used, or when setFile()
  42690. is used to explicitly set it.
  42691. */
  42692. const File getFile() const { return documentFile; }
  42693. /** Sets the file that this document thinks it was loaded from.
  42694. This won't actually load anything - it just changes the file stored internally.
  42695. @see getFile
  42696. */
  42697. void setFile (const File& newFile);
  42698. protected:
  42699. /** Overload this to return the title of the document.
  42700. This is used in message boxes, filenames and file choosers, so it should be
  42701. something sensible.
  42702. */
  42703. virtual const String getDocumentTitle() = 0;
  42704. /** This method should try to load your document from the given file.
  42705. If it fails, it should return an error message. If it succeeds, it should return
  42706. an empty string.
  42707. */
  42708. virtual const String loadDocument (const File& file) = 0;
  42709. /** This method should try to write your document to the given file.
  42710. If it fails, it should return an error message. If it succeeds, it should return
  42711. an empty string.
  42712. */
  42713. virtual const String saveDocument (const File& file) = 0;
  42714. /** This is used for dialog boxes to make them open at the last folder you
  42715. were using.
  42716. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  42717. the last document that was used - you might want to store this value
  42718. in a static variable, or even in your application's properties. It should
  42719. be a global setting rather than a property of this object.
  42720. This method works very well in conjunction with a RecentlyOpenedFilesList
  42721. object to manage your recent-files list.
  42722. As a default value, it's ok to return File::nonexistent, and the document
  42723. object will use a sensible one instead.
  42724. @see RecentlyOpenedFilesList
  42725. */
  42726. virtual const File getLastDocumentOpened() = 0;
  42727. /** This is used for dialog boxes to make them open at the last folder you
  42728. were using.
  42729. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  42730. the last document that was used - you might want to store this value
  42731. in a static variable, or even in your application's properties. It should
  42732. be a global setting rather than a property of this object.
  42733. This method works very well in conjunction with a RecentlyOpenedFilesList
  42734. object to manage your recent-files list.
  42735. @see RecentlyOpenedFilesList
  42736. */
  42737. virtual void setLastDocumentOpened (const File& file) = 0;
  42738. public:
  42739. juce_UseDebuggingNewOperator
  42740. private:
  42741. File documentFile;
  42742. bool changedSinceSave;
  42743. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  42744. FileBasedDocument (const FileBasedDocument&);
  42745. const FileBasedDocument& operator= (const FileBasedDocument&);
  42746. };
  42747. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42748. /********* End of inlined file: juce_FileBasedDocument.h *********/
  42749. #endif
  42750. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  42751. #endif
  42752. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42753. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  42754. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42755. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42756. /**
  42757. Manages a set of files for use as a list of recently-opened documents.
  42758. This is a handy class for holding your list of recently-opened documents, with
  42759. helpful methods for things like purging any non-existent files, automatically
  42760. adding them to a menu, and making persistence easy.
  42761. @see File, FileBasedDocument
  42762. */
  42763. class JUCE_API RecentlyOpenedFilesList
  42764. {
  42765. public:
  42766. /** Creates an empty list.
  42767. */
  42768. RecentlyOpenedFilesList();
  42769. /** Destructor. */
  42770. ~RecentlyOpenedFilesList();
  42771. /** Sets a limit for the number of files that will be stored in the list.
  42772. When addFile() is called, then if there is no more space in the list, the
  42773. least-recently added file will be dropped.
  42774. @see getMaxNumberOfItems
  42775. */
  42776. void setMaxNumberOfItems (const int newMaxNumber);
  42777. /** Returns the number of items that this list will store.
  42778. @see setMaxNumberOfItems
  42779. */
  42780. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  42781. /** Returns the number of files in the list.
  42782. The most recently added file is always at index 0.
  42783. */
  42784. int getNumFiles() const;
  42785. /** Returns one of the files in the list.
  42786. The most recently added file is always at index 0.
  42787. */
  42788. const File getFile (const int index) const;
  42789. /** Returns an array of all the absolute pathnames in the list.
  42790. */
  42791. const StringArray& getAllFilenames() const throw() { return files; }
  42792. /** Clears all the files from the list. */
  42793. void clear();
  42794. /** Adds a file to the list.
  42795. The file will be added at index 0. If this file is already in the list, it will
  42796. be moved up to index 0, but a file can only appear once in the list.
  42797. If the list already contains the maximum number of items that is permitted, the
  42798. least-recently added file will be dropped from the end.
  42799. */
  42800. void addFile (const File& file);
  42801. /** Checks each of the files in the list, removing any that don't exist.
  42802. You might want to call this after reloading a list of files, or before putting them
  42803. on a menu.
  42804. */
  42805. void removeNonExistentFiles();
  42806. /** Adds entries to a menu, representing each of the files in the list.
  42807. This is handy for creating an "open recent file..." menu in your app. The
  42808. menu items are numbered consecutively starting with the baseItemId value,
  42809. and can either be added as complete pathnames, or just the last part of the
  42810. filename.
  42811. If dontAddNonExistentFiles is true, then each file will be checked and only those
  42812. that exist will be added.
  42813. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  42814. pointers to file objects. Any files that appear in this list will not be added to the
  42815. menu - the reason for this is that you might have a number of files already open, so
  42816. might not want these to be shown in the menu.
  42817. It returns the number of items that were added.
  42818. */
  42819. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  42820. const int baseItemId,
  42821. const bool showFullPaths,
  42822. const bool dontAddNonExistentFiles,
  42823. const File** filesToAvoid = 0);
  42824. /** Returns a string that encapsulates all the files in the list.
  42825. The string that is returned can later be passed into restoreFromString() in
  42826. order to recreate the list. This is handy for persisting your list, e.g. in
  42827. a PropertiesFile object.
  42828. @see restoreFromString
  42829. */
  42830. const String toString() const;
  42831. /** Restores the list from a previously stringified version of the list.
  42832. Pass in a stringified version created with toString() in order to persist/restore
  42833. your list.
  42834. @see toString
  42835. */
  42836. void restoreFromString (const String& stringifiedVersion);
  42837. juce_UseDebuggingNewOperator
  42838. private:
  42839. StringArray files;
  42840. int maxNumberOfItems;
  42841. };
  42842. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42843. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  42844. #endif
  42845. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  42846. #endif
  42847. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42848. /********* Start of inlined file: juce_SystemClipboard.h *********/
  42849. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42850. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42851. /**
  42852. Handles reading/writing to the system's clipboard.
  42853. */
  42854. class JUCE_API SystemClipboard
  42855. {
  42856. public:
  42857. /** Copies a string of text onto the clipboard */
  42858. static void copyTextToClipboard (const String& text) throw();
  42859. /** Gets the current clipboard's contents.
  42860. Obviously this might have come from another app, so could contain
  42861. anything..
  42862. */
  42863. static const String getTextFromClipboard() throw();
  42864. };
  42865. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42866. /********* End of inlined file: juce_SystemClipboard.h *********/
  42867. #endif
  42868. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  42869. #endif
  42870. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  42871. #endif
  42872. #endif
  42873. /********* End of inlined file: juce_app_includes.h *********/
  42874. #endif
  42875. #if JUCE_MSVC
  42876. #pragma warning (pop)
  42877. #pragma pack (pop)
  42878. #endif
  42879. #if JUCE_MAC || JUCE_IPHONE
  42880. #pragma align=reset
  42881. #endif
  42882. END_JUCE_NAMESPACE
  42883. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  42884. #ifdef JUCE_NAMESPACE
  42885. // this will obviously save a lot of typing, but can be disabled by
  42886. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  42887. using namespace JUCE_NAMESPACE;
  42888. /* On the Mac, these symbols are defined in the Mac libraries, so
  42889. these macros make it easier to reference them without writing out
  42890. the namespace every time.
  42891. If you run into difficulties where these macros interfere with the contents
  42892. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  42893. the comments in that file for more information.
  42894. */
  42895. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  42896. #define Component JUCE_NAMESPACE::Component
  42897. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  42898. #define Point JUCE_NAMESPACE::Point
  42899. #define Button JUCE_NAMESPACE::Button
  42900. #endif
  42901. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  42902. it easier to use the juce version explicitly.
  42903. If you run into difficulties where this macro interferes with other 3rd party header
  42904. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  42905. file for more information.
  42906. */
  42907. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  42908. #define Rectangle JUCE_NAMESPACE::Rectangle
  42909. #endif
  42910. #endif
  42911. #endif
  42912. /* Easy autolinking to the right JUCE libraries under win32.
  42913. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  42914. including this header file.
  42915. */
  42916. #if JUCE_MSVC
  42917. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  42918. /** If you want your application to link to Juce as a DLL instead of
  42919. a static library (on win32), just define the JUCE_DLL macro before
  42920. including juce.h
  42921. */
  42922. #ifdef JUCE_DLL
  42923. #ifdef JUCE_DEBUG
  42924. #define AUTOLINKEDLIB "JUCE_debug.lib"
  42925. #else
  42926. #define AUTOLINKEDLIB "JUCE.lib"
  42927. #endif
  42928. #else
  42929. #ifdef JUCE_DEBUG
  42930. #ifdef _WIN64
  42931. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  42932. #else
  42933. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  42934. #endif
  42935. #else
  42936. #ifdef _WIN64
  42937. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  42938. #else
  42939. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  42940. #endif
  42941. #endif
  42942. #endif
  42943. #pragma comment(lib, AUTOLINKEDLIB)
  42944. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  42945. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  42946. #endif
  42947. // Auto-link the other win32 libs that are needed by library calls..
  42948. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  42949. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  42950. // Auto-links to various win32 libs that are needed by library calls..
  42951. #pragma comment(lib, "kernel32.lib")
  42952. #pragma comment(lib, "user32.lib")
  42953. #pragma comment(lib, "shell32.lib")
  42954. #pragma comment(lib, "gdi32.lib")
  42955. #pragma comment(lib, "vfw32.lib")
  42956. #pragma comment(lib, "comdlg32.lib")
  42957. #pragma comment(lib, "winmm.lib")
  42958. #pragma comment(lib, "wininet.lib")
  42959. #pragma comment(lib, "ole32.lib")
  42960. #pragma comment(lib, "advapi32.lib")
  42961. #pragma comment(lib, "ws2_32.lib")
  42962. #pragma comment(lib, "comsupp.lib")
  42963. #pragma comment(lib, "version.lib")
  42964. #if JUCE_OPENGL
  42965. #pragma comment(lib, "OpenGL32.Lib")
  42966. #pragma comment(lib, "GlU32.Lib")
  42967. #endif
  42968. #if JUCE_QUICKTIME
  42969. #pragma comment (lib, "QTMLClient.lib")
  42970. #endif
  42971. #if JUCE_USE_CAMERA
  42972. #pragma comment (lib, "Strmiids.lib")
  42973. #endif
  42974. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  42975. #endif
  42976. #endif
  42977. #endif
  42978. /*
  42979. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  42980. AppSubClass is the name of a class derived from JUCEApplication.
  42981. See the JUCEApplication class documentation (juce_Application.h) for more details.
  42982. */
  42983. #if defined (JUCE_GCC) || defined (__MWERKS__)
  42984. #define START_JUCE_APPLICATION(AppClass) \
  42985. int main (int argc, char* argv[]) \
  42986. { \
  42987. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  42988. }
  42989. #elif JUCE_WINDOWS
  42990. #ifdef _CONSOLE
  42991. #define START_JUCE_APPLICATION(AppClass) \
  42992. int main (int, char* argv[]) \
  42993. { \
  42994. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42995. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42996. }
  42997. #elif ! defined (_AFXDLL)
  42998. #ifdef _WINDOWS_
  42999. #define START_JUCE_APPLICATION(AppClass) \
  43000. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  43001. { \
  43002. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  43003. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  43004. }
  43005. #else
  43006. #define START_JUCE_APPLICATION(AppClass) \
  43007. int __stdcall WinMain (int, int, const char*, int) \
  43008. { \
  43009. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  43010. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  43011. }
  43012. #endif
  43013. #endif
  43014. #endif
  43015. #endif // __JUCE_JUCEHEADER__
  43016. /********* End of inlined file: juce.h *********/
  43017. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__